<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use App\Models\Activity;
use App\Models\Attendance;
use App\Services\ExcelExportService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

class ExportController extends Controller
{
    /**
     * Export attendance data to Excel with full formatting
     */
    public function exportAttendance(Request $request)
    {
        $user = auth()->user();
        $company = $user->company;

        if (!$company) {
            abort(404, 'Company not found');
        }

        // Get date range from request or default to current month
        $startDate = $request->get('start_date')
            ? Carbon::parse($request->get('start_date'))
            : Carbon::now()->startOfMonth();
        $endDate = $request->get('end_date')
            ? Carbon::parse($request->get('end_date'))
            : Carbon::now()->endOfMonth();

        // Get attendances for the user
        // Include activities for URAIAN and OUTPUT columns
        // Include location (unified), office (legacy), businessTripLocation (legacy) for KETERANGAN column
        $attendances = Attendance::where('user_id', $user->id)
            ->whereBetween('date', [$startDate, $endDate])
            ->with(['location', 'office', 'businessTripLocation', 'activities'])
            ->orderBy('date')
            ->get();

        // Use ExcelExportService for formatted export
        $exportService = new ExcelExportService();
        $path = $exportService->exportAttendance(
            $attendances,
            $company,
            $startDate,
            $endDate,
            $user
        );

        // Download the file
        $fullPath = storage_path('app/' . $path);

        return response()->download($fullPath)->deleteFileAfterSend(true);
    }

    /**
     * Export activity data to Excel with full formatting
     */
    public function exportActivity(Request $request)
    {
        $user = auth()->user();
        $company = $user->company;

        if (!$company) {
            abort(404, 'Company not found');
        }

        // Get date range from request or default to current month
        $startDate = $request->get('start_date')
            ? Carbon::parse($request->get('start_date'))
            : Carbon::now()->startOfMonth();
        $endDate = $request->get('end_date')
            ? Carbon::parse($request->get('end_date'))
            : Carbon::now()->endOfMonth();

        // Get activities for the user
        $activities = Activity::where('user_id', $user->id)
            ->whereBetween('date', [$startDate, $endDate])
            ->with('attendance')
            ->orderBy('date')
            ->orderBy('start_time')
            ->get();

        // Create Excel file
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Laporan Aktivitas');

        // Column widths
        $columnWidths = [
            'A' => 4,      // NO
            'B' => 12,     // TANGGAL
            'C' => 11,     // Hari
            'D' => 14,     // WAKTU
            'E' => 70,     // URAIAN (Aktivitas)
            'F' => 55,     // OUTPUT
            'G' => 18,     // CATATAN
        ];

        foreach ($columnWidths as $col => $width) {
            $sheet->getColumnDimension($col)->setWidth($width);
        }

        // Indonesian names
        $monthNames = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
            5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
            9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember',
        ];
        $dayNames = [
            'Monday' => 'Senin', 'Tuesday' => 'Selasa', 'Wednesday' => 'Rabu',
            'Thursday' => 'Kamis', 'Friday' => 'Jumat', 'Saturday' => 'Sabtu', 'Sunday' => 'Minggu',
        ];
        $shortMonthNames = [
            1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr', 5 => 'May', 6 => 'Jun',
            7 => 'Jul', 8 => 'Aug', 9 => 'Sep', 10 => 'Oct', 11 => 'Nov', 12 => 'Dec',
        ];

        $currentRow = 1;

        // Add logo if exists
        if ($company->logo && Storage::disk('public')->exists($company->logo)) {
            try {
                $drawing = new Drawing();
                $drawing->setName('Logo');
                $drawing->setDescription('Company Logo');
                $drawing->setPath(Storage::disk('public')->path($company->logo));
                $drawing->setHeight(60);
                $drawing->setCoordinates('A1');
                $drawing->setWorksheet($sheet);
            } catch (\Exception $e) {
                // Skip logo if error
            }
        }

        // Header: Title
        $sheet->mergeCells('B2:F3');
        $sheet->setCellValue('B2', 'LAPORAN AKTIVITAS BULANAN');
        $sheet->getStyle('B2')->applyFromArray([
            'font' => ['bold' => true, 'size' => 18],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER,
            ],
        ]);

        // Company name
        $sheet->mergeCells('B4:F4');
        $sheet->setCellValue('B4', strtoupper($company->name));
        $sheet->getStyle('B4')->applyFromArray([
            'font' => ['bold' => true, 'size' => 10],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
        ]);

        // Employee info
        $sheet->setCellValue('A7', 'NAMA');
        $sheet->mergeCells('B7:C7');
        $sheet->setCellValue('B7', $user->name);
        $sheet->getStyle('B7:C7')->applyFromArray([
            'borders' => ['bottom' => ['borderStyle' => Border::BORDER_THIN]],
        ]);

        $sheet->setCellValue('A8', 'POSISI');
        $sheet->mergeCells('B8:C8');
        $sheet->setCellValue('B8', $user->position ?? $user->department ?? 'Karyawan');
        $sheet->getStyle('B8:C8')->applyFromArray([
            'borders' => ['bottom' => ['borderStyle' => Border::BORDER_THIN]],
        ]);

        $sheet->setCellValue('A9', 'BULAN');
        $sheet->mergeCells('B9:C9');
        $sheet->setCellValue('B9', $monthNames[$startDate->month] . ' ' . $startDate->year);
        $sheet->getStyle('B9:C9')->applyFromArray([
            'borders' => ['bottom' => ['borderStyle' => Border::BORDER_THIN]],
        ]);

        $currentRow = 11;

        // Table Headers
        $headers = [
            'A' => 'NO',
            'B' => 'TANGGAL',
            'C' => 'HARI',
            'D' => 'WAKTU',
            'E' => 'AKTIVITAS',
            'F' => 'OUTPUT',
            'G' => 'CATATAN',
        ];

        // Merge header cells vertically
        foreach (array_keys($headers) as $col) {
            $sheet->mergeCells("{$col}11:{$col}12");
        }

        foreach ($headers as $col => $header) {
            $sheet->setCellValue("{$col}11", $header);
        }

        // Style headers
        $sheet->getStyle("A11:G12")->applyFromArray([
            'font' => ['bold' => true, 'size' => 10, 'color' => ['rgb' => 'FFFFFF']],
            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => ['rgb' => '003399'],
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER,
                'wrapText' => true,
            ],
            'borders' => [
                'allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => '000000']],
            ],
        ]);

        $currentRow = 13;
        $no = 1;

        // Data rows
        foreach ($activities as $activity) {
            $date = Carbon::parse($activity->date);
            $dateStr = $date->format('d') . '-' . $shortMonthNames[$date->month] . '-' . $date->format('y');
            $dayName = $dayNames[$date->format('l')] ?? $date->format('l');

            $startTime = $activity->start_time ? Carbon::parse($activity->start_time)->format('H:i') : '';
            $endTime = $activity->end_time ? Carbon::parse($activity->end_time)->format('H:i') : '';
            $timeRange = $startTime && $endTime ? "{$startTime} - {$endTime}" : ($startTime ?: '');

            $sheet->setCellValue("A{$currentRow}", $no);
            $sheet->setCellValue("B{$currentRow}", $dateStr);
            $sheet->setCellValue("C{$currentRow}", $dayName);
            $sheet->setCellValue("D{$currentRow}", $timeRange);
            $sheet->setCellValue("E{$currentRow}", $activity->activity ?? '');
            $sheet->setCellValue("F{$currentRow}", $activity->output ?? '');
            $sheet->setCellValue("G{$currentRow}", $activity->notes ?? '');

            // Highlight if no output
            if (empty($activity->output)) {
                $sheet->getStyle("A{$currentRow}:G{$currentRow}")->applyFromArray([
                    'fill' => [
                        'fillType' => Fill::FILL_SOLID,
                        'startColor' => ['rgb' => 'FFFF00'],
                    ],
                ]);
            }

            // Style data row
            $sheet->getStyle("A{$currentRow}:G{$currentRow}")->applyFromArray([
                'font' => ['size' => 9],
                'alignment' => ['vertical' => Alignment::VERTICAL_TOP, 'wrapText' => true],
                'borders' => [
                    'allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => '000000']],
                ],
            ]);

            $sheet->getRowDimension($currentRow)->setRowHeight(-1);

            $no++;
            $currentRow++;
        }

        // Summary
        $currentRow += 2;
        $sheet->setCellValue("A{$currentRow}", "Total aktivitas: " . $activities->count());
        $sheet->getStyle("A{$currentRow}")->getFont()->setBold(true);

        // Signature section
        $currentRow += 3;
        $signatureRow = $currentRow;

        $sheet->mergeCells("A{$signatureRow}:C{$signatureRow}");
        $sheet->setCellValue("A{$signatureRow}", 'Mengetahui,');
        $sheet->getStyle("A{$signatureRow}")->applyFromArray([
            'font' => ['bold' => true, 'size' => 10],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
        ]);

        $signatureDate = Carbon::now()->format('j') . ' ' . $monthNames[Carbon::now()->month] . ' ' . Carbon::now()->year;
        $city = $company->city ?? 'Jakarta';
        $sheet->mergeCells("F{$signatureRow}:G{$signatureRow}");
        $sheet->setCellValue("F{$signatureRow}", "{$city}, {$signatureDate}");
        $sheet->getStyle("F{$signatureRow}")->applyFromArray([
            'font' => ['bold' => true, 'size' => 10],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
        ]);

        $currentRow += 6;

        $sheet->mergeCells("A{$currentRow}:C{$currentRow}");
        $sheet->setCellValue("A{$currentRow}", $company->team_leader_name ?? '..............................');
        $sheet->getStyle("A{$currentRow}")->applyFromArray([
            'font' => ['bold' => true, 'size' => 10],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
        ]);

        $sheet->mergeCells("F{$currentRow}:G{$currentRow}");
        $sheet->setCellValue("F{$currentRow}", $user->name);
        $sheet->getStyle("F{$currentRow}")->applyFromArray([
            'font' => ['bold' => true, 'size' => 10],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
        ]);

        $currentRow++;

        $sheet->mergeCells("A{$currentRow}:C{$currentRow}");
        $sheet->setCellValue("A{$currentRow}", $company->team_leader_position ?? 'Team Leader');
        $sheet->getStyle("A{$currentRow}")->applyFromArray([
            'font' => ['bold' => true, 'size' => 10],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
        ]);

        $sheet->mergeCells("F{$currentRow}:G{$currentRow}");
        $sheet->setCellValue("F{$currentRow}", $user->position ?? 'Karyawan');
        $sheet->getStyle("F{$currentRow}")->applyFromArray([
            'font' => ['bold' => true, 'size' => 10],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
        ]);

        // Generate file
        $filename = 'laporan_aktivitas_' . str_replace(' ', '_', strtolower($user->name)) . '_' . $startDate->format('Ymd') . '-' . $endDate->format('Ymd') . '.xlsx';
        $path = 'exports/' . $filename;
        $fullPath = storage_path('app/' . $path);

        $dir = dirname($fullPath);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        $writer = new Xlsx($spreadsheet);
        $writer->save($fullPath);

        return response()->download($fullPath)->deleteFileAfterSend(true);
    }

    /**
     * Download exported file from exports directory
     * Used by Filament action redirect
     */
    public function downloadFile(Request $request)
    {
        $filename = $request->get('file');

        if (!$filename) {
            abort(400, 'Filename is required');
        }

        // Sanitize filename to prevent directory traversal
        $filename = basename($filename);

        $fullPath = storage_path('app/exports/' . $filename);

        if (!file_exists($fullPath)) {
            abort(404, 'File not found');
        }

        // Determine content type based on extension
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
        $contentType = match ($extension) {
            'csv' => 'text/csv',
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'xls' => 'application/vnd.ms-excel',
            default => 'application/octet-stream',
        };

        return response()->download($fullPath, $filename, [
            'Content-Type' => $contentType,
        ])->deleteFileAfterSend(true);
    }
}
