<?php

namespace App\Exports;

use App\Models\JobApplication;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

class ApplicationsExport implements FromCollection, WithHeadings, WithMapping, WithStyles, ShouldAutoSize, WithCustomCsvSettings, WithEvents
{
    public function __construct(private int $jobPostingId)
    {
    }

    public function collection()
    {
        return JobApplication::with('jobPosting')
            ->where('job_posting_id', $this->jobPostingId)
            ->latest()
            ->get();
    }

    public function headings(): array
    {
        return [
            'ID',           // A
            'Ad Soyad',     // B
            'E-posta',      // C
            'Telefon',      // D
            'Başvuru Tarihi', // E
            'Durum',        // F
            'LinkedIn',     // G
            'Kaynak',       // H
            'İç Notlar',    // I
            'CV Dosyası',   // J
        ];
    }

    public function map($application): array
    {
        return [
            $application->id,
            $application->full_name,
            $application->email,
            $application->phone,
            $application->created_at->format('d.m.Y H:i'),
            $application->status_label,
            $application->linkedin_url ?? '',
            $application->source ?? '',
            $application->internal_notes ?? '',
            $application->cv_original_name,
        ];
    }

    public function styles(Worksheet $sheet): array
    {
        // Header row — dark navy
        return [
            1 => [
                'font' => [
                    'bold'  => true,
                    'color' => ['rgb' => 'FFFFFF'],
                    'size'  => 11,
                ],
                'fill' => [
                    'fillType'   => Fill::FILL_SOLID,
                    'startColor' => ['rgb' => '1E3A5F'],
                ],
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                    'vertical'   => Alignment::VERTICAL_CENTER,
                ],
            ],
        ];
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                $sheet = $event->sheet->getDelegate();
                $highestRow = $sheet->getHighestRow();

                // Column header colors (row 1 already handled by styles())
                // Column-specific header accent colors
                $headerColors = [
                    'A' => '374151', // ID — dark gray
                    'B' => '1E40AF', // Ad Soyad — blue
                    'C' => '065F46', // E-posta — green
                    'D' => '7C3AED', // Telefon — purple
                    'E' => '1E3A5F', // Tarih — navy
                    'F' => '92400E', // Durum — amber
                    'G' => '0369A1', // LinkedIn — sky
                    'H' => '374151', // Kaynak — gray
                    'I' => '374151', // Notlar — gray
                    'J' => '374151', // CV — gray
                ];

                foreach ($headerColors as $col => $color) {
                    $sheet->getStyle($col . '1')->applyFromArray([
                        'fill' => [
                            'fillType'   => Fill::FILL_SOLID,
                            'startColor' => ['rgb' => $color],
                        ],
                    ]);
                }

                // Row height for header
                $sheet->getRowDimension(1)->setRowHeight(22);

                // Data rows — alternating background + status coloring
                for ($row = 2; $row <= $highestRow; $row++) {
                    $isEven = ($row % 2 === 0);
                    $rowBg  = $isEven ? 'F8FAFC' : 'FFFFFF';

                    // Base row style
                    $sheet->getStyle("A{$row}:J{$row}")->applyFromArray([
                        'fill' => [
                            'fillType'   => Fill::FILL_SOLID,
                            'startColor' => ['rgb' => $rowBg],
                        ],
                        'font' => ['size' => 10],
                        'alignment' => ['vertical' => Alignment::VERTICAL_CENTER],
                    ]);

                    // Date column (E) — light blue tint
                    $sheet->getStyle("E{$row}")->applyFromArray([
                        'fill' => [
                            'fillType'   => Fill::FILL_SOLID,
                            'startColor' => ['rgb' => 'EFF6FF'],
                        ],
                        'font' => ['color' => ['rgb' => '1E40AF']],
                    ]);

                    // Status column (F) — conditional color
                    $statusCell  = $sheet->getCell("F{$row}")->getValue();
                    $statusColor = match (true) {
                        str_contains((string) $statusCell, 'Yeni')      => ['bg' => 'DBEAFE', 'fg' => '1E40AF'],
                        str_contains((string) $statusCell, 'İncelendi') => ['bg' => 'FEF9C3', 'fg' => '92400E'],
                        str_contains((string) $statusCell, 'Görüşme')   => ['bg' => 'EDE9FE', 'fg' => '6D28D9'],
                        str_contains((string) $statusCell, 'Reddedildi')=> ['bg' => 'FEE2E2', 'fg' => '991B1B'],
                        str_contains((string) $statusCell, 'İşe')       => ['bg' => 'D1FAE5', 'fg' => '065F46'],
                        default                                          => ['bg' => 'F3F4F6', 'fg' => '374151'],
                    };

                    $sheet->getStyle("F{$row}")->applyFromArray([
                        'fill' => [
                            'fillType'   => Fill::FILL_SOLID,
                            'startColor' => ['rgb' => $statusColor['bg']],
                        ],
                        'font' => [
                            'bold'  => true,
                            'color' => ['rgb' => $statusColor['fg']],
                        ],
                        'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
                    ]);

                    // Row height
                    $sheet->getRowDimension($row)->setRowHeight(18);
                }

                // Outer border for the whole table
                if ($highestRow >= 2) {
                    $sheet->getStyle("A1:J{$highestRow}")->applyFromArray([
                        'borders' => [
                            'allBorders' => [
                                'borderStyle' => Border::BORDER_THIN,
                                'color'       => ['rgb' => 'E5E7EB'],
                            ],
                            'outline' => [
                                'borderStyle' => Border::BORDER_MEDIUM,
                                'color'       => ['rgb' => '1E3A5F'],
                            ],
                        ],
                    ]);
                }

                // Freeze header row
                $sheet->freezePane('A2');

                // Auto-filter
                $sheet->setAutoFilter("A1:J1");
            },
        ];
    }

    public function getCsvSettings(): array
    {
        return [
            'use_bom'                => true,
            'output_encoding'        => 'UTF-8',
            'delimiter'              => ';',   // Noktalı virgül — Excel'de otomatik sütun ayrımı
            'enclosure'              => '"',
            'line_ending'            => PHP_EOL,
            'include_separator_line' => false,
            'excel_compatibility'    => false,
        ];
    }
}