<?php

namespace App\Filament\Exports;

use App\Enums\VehicleType;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Builder;

use pxlrbt\FilamentExcel\Actions\Tables\ExportAction;
use pxlrbt\FilamentExcel\Exports\ExcelExport;
use pxlrbt\FilamentExcel\Columns\Column;

use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\WithStyles;

use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;

class VehicleExporter extends ExcelExport implements WithStyles
{
    public function setUp()
    {
        $this
            ->modifyQueryUsing(function (Builder $query) {
                return $query->with([
                    'employee', 'country', 'trailer', 'certificates'
                ]);
            })
            ->withFilename('export-vehicles-' . date('YmdHis'))
            ->withColumns([
                Column::make('country.alpha_2')
                    ->heading('ÜLKE'),

                Column::make('license_plate')
                    ->heading('PLAKA'),

                Column::make('vehicle_type_id')
                    ->heading('ARAÇ TÜRÜ')
                    ->formatStateUsing(fn ($state): string => VehicleType::from($state)->getLabel()),

                Column::make('vin')
                    ->heading('ŞASİ NUMARASI'),

                Column::make('make')
                    ->heading('MARKA'),

                Column::make('model')
                    ->heading('MODEL'),

                Column::make('year')
                    ->heading('ÜRETİM YILI'),

                Column::make('color')
                    ->heading('RENK'),

                Column::make('length')
                    ->heading('UZUNLUK')
                    ->formatStateUsing(fn ($record) => $record->length ? $record->length.'m' : ''),

                Column::make('width')
                    ->heading('GENİŞLİK')
                    ->formatStateUsing(fn ($record) => $record->length ? $record->length.'m' : ''),

                Column::make('height')
                    ->heading('YÜKSEKLİK')
                    ->formatStateUsing(fn ($record) => $record->length ? $record->length.'m' : ''),

                Column::make('has_double_deck')
                    ->heading('ÇİFT KAT')
                    ->formatStateUsing(function ($record) {
                        if ($record->vehicle_type_id == 3) {
                            return $record->has_double_deck ? 'Evet' : 'Hayır';
                        }

                        return '';
                    }),

                Column::make('has_partition')
                    ->heading('EK BÖLME')
                    ->formatStateUsing(function ($record) {
                        if ($record->vehicle_type_id == 3) {
                            return $record->has_partition ? 'Evet' : 'Hayır';
                        }

                        return '';
                    }),

                Column::make('has_textile')
                    ->heading('TEKSTİL')
                    ->formatStateUsing(function ($record) {
                        if ($record->vehicle_type_id == 3) {
                            return $record->has_textile ? 'Evet' : 'Hayır';
                        }

                        return '';
                    }),

                Column::make('has_adr_certificate')
                    ->heading('ADR BELGESİ')
                    ->formatStateUsing(function ($record) {
                        return $record->has_adr_certificate ? 'Var' : 'Yok';
                    }),

                Column::make('traffic_insurance')
                    ->heading('TRAFİK SİGORTASI')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('insurance')
                    ->heading('KASKO')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('vehicle_inspection')
                    ->heading('ARAÇ MUAYENESİ')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('green_card')
                    ->heading('YEŞİL KART')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 4)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('l_certificate')
                    ->heading('L BELGESİ')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 5)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('aitm_certificate')
                    ->heading('AİTM BELGESİ')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 6)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('frc_certificate')
                    ->heading('FRC BELGESİ')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 7)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('roder_certificate')
                    ->heading('RODER BELGESİ')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 8)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('registration_card')
                    ->heading('TAŞIT KARTI')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 9)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('tachograph_inspection')
                    ->heading('TÜV BELGESİ')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 10)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('imm_certificate')
                    ->heading('İMM BELGESİ')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 11)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? 'Süresi doldu.' : '-')
                            : $expiryDate->isoFormat('LL');
                    }),

                Column::make('euro_norm_id')
                    ->heading('EURO NORM'),

                Column::make('fuel_type_id')
                    ->heading('YAKIT TÜRÜ'),

                Column::make('employee.fullname')
                    ->heading('ŞOFÖR BİLGİSİ'),

                Column::make('trailer.license_plate')
                    ->heading('DORSE'),
            ]);
    }

    public function styles(Worksheet $sheet)
    {
        // En son kullanılan satır ve sütunu al
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();

        // En son kullanılan hücre aralığını belirle
        $usedRange = 'A1:' . $highestColumn . $highestRow;

        // Tüm hücreler için kenarlık stili
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    'color' => ['argb' => 'FF000000'],
                ],
            ],
            'alignment' => [
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT,
            ],
        ];

        // İlk satır için başlık stili
        $headerStyleArray = [
            'font' => [
                'bold' => true,
                'color' => ['argb' => Color::COLOR_WHITE],
            ],
            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => ['argb' => 'FF1E88E5'], // Daha hoş bir renk, örneğin mavi
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
            ],
        ];

        // Zebra deseni için satır renkleri
        $oddRowStyleArray = [
            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => ['argb' => 'FFFFFFFF'], // Beyaz
            ],
        ];

        $evenRowStyleArray = [
            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => ['argb' => 'FFF2F2F2'], // Hafif gri
            ],
        ];

        // Belirlenen aralığa kenarlık ve dikey hizalama stili uygula
        $sheet->getStyle($usedRange)->applyFromArray($styleArray);

        // İlk satıra başlık stili uygula
        $sheet->getStyle('A1:' . $highestColumn . '1')->applyFromArray($headerStyleArray);

        // İlk satırın hücre yüksekliğini artır
        $sheet->getRowDimension('1')->setRowHeight(30);

        // Zebra deseni uygulamak ve normal satır yüksekliğini artırmak için döngü
        for ($row = 2; $row <= $highestRow; $row++) {
            // Zebra deseni uygulama
            if ($row % 2 == 0) {
                $sheet->getStyle('A' . $row . ':' . $highestColumn . $row)->applyFromArray($evenRowStyleArray);
            } else {
                $sheet->getStyle('A' . $row . ':' . $highestColumn . $row)->applyFromArray($oddRowStyleArray);
            }

            // Normal satır yüksekliğini artır
            $sheet->getRowDimension($row)->setRowHeight(24); // Hücre yüksekliğini artır
        }

        return [];
    }
}
