<?php

namespace App\Filament\Exports;

use App\Models\Transmittal;
use pxlrbt\FilamentExcel\Columns\Column;
use pxlrbt\FilamentExcel\Exports\ExcelExport;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

class TransmittalExcelExport extends ExcelExport
{
    public function setUp(): void
    {
        $this->fromTable()
            ->withFilename('transmittals-' . now()->format('Y-m-d'))
            ->modifyQueryUsing(
                fn ($query) => $query->with([
                    'client',
                    'branch',
                    'files.notes',
                    'files.remarks',
                ])
            )
            ->withColumns([
                Column::make('series')
                    ->heading('series'),
                Column::make('client')
                    ->heading('Client')
                    ->formatStateUsing(fn (Transmittal $record) => $record->client?->company),
                Column::make('branch')
                    ->heading('Branch')
                    ->formatStateUsing(fn (Transmittal $record) => $record->branch?->code),
                Column::make('files')
                    ->heading('files')
                    ->formatStateUsing(
                        fn (Transmittal $record) => $record->files
                            ->pluck('description')
                            ->filter()
                            ->join(PHP_EOL)
                    ),
            ]);
    }

    public function registerEvents(): array
    {
        $recordIds = $this->getRecordIds();

        return [
            AfterSheet::class => function (AfterSheet $event) use ($recordIds) {
                $sheet = $event->sheet->getDelegate();

                $sheet->insertNewRowBefore(1, 2);
                $sheet->mergeCells('A1:F1');
                $sheet->getRowDimension(1)->setRowHeight(90);
                $sheet->getStyle('A1:F1')
                    ->getAlignment()
                    ->setHorizontal(Alignment::HORIZONTAL_CENTER);
                

                $logo = new Drawing();
                $logo->setName('MKM Logo');
                $logo->setDescription('MKM Tax & Accounting Services');
                $logo->setPath(public_path('images/logo-light.png'));
                $logo->setHeight(100);
                $logo->setOffsetX(120);
                $logo->setOffsetY(10);

                $logo->setCoordinates('A1');
                $logo->setWorksheet($sheet);

                $transmittal = Transmittal::with(['client', 'branch', 'files.notes', 'files.remarks'])->find($recordIds[0] ?? null);

                if ($transmittal) {
                    $sheet->mergeCells('A2:F2');
                    $sheet->setCellValue('A2', $transmittal->client?->company);

                    $sheet->getStyle('A2')->getFont()->setBold(true);
                    $sheet->getStyle('A2')->getAlignment()->setHorizontal('center');
                }

                // Headings row
                $sheet->setCellValue('A3', 'series');
                $sheet->setCellValue('B3', 'Client');
                $sheet->setCellValue('C3', 'Branch');
                $sheet->setCellValue('D3', 'files');
                $sheet->setCellValue('E3', 'notes');
                $sheet->setCellValue('F3', 'remarks');

                $sheet->getStyle('A3:F3')->getFont()->setBold(true);
                $sheet->getStyle('A3:F3')->getAlignment()->setHorizontal('center');

                $rows = [];
                $firstRow = true;

                if ($transmittal) {
                    foreach ($transmittal->files as $file) {
                        $fileNotes = $file->notes->pluck('comment')->values();
                        $fileRemarks = $file->remarks->pluck('remark')->values();

                        $maxLines = max(1, $fileNotes->count(), $fileRemarks->count());

                        for ($i = 0; $i < $maxLines; $i++) {
                            $rows[] = [
                                'series' => $firstRow ? $transmittal->series : '',
                                'client' => $firstRow ? $transmittal->client?->company : '',
                                'branch' => $firstRow ? $transmittal->branch?->code : '',
                                'file' => $i === 0 ? $file->description : '',
                                'note' => $fileNotes[$i] ?? '',
                                'remark' => $fileRemarks[$i] ?? '',
                            ];

                            $firstRow = false;
                        }
                    }
                }

                $currentRow = 4;

                foreach ($rows as $dataRow) {
                    $sheet->setCellValue("A{$currentRow}", $dataRow['series']);
                    $sheet->setCellValue("B{$currentRow}", $dataRow['client']);
                    $sheet->setCellValue("C{$currentRow}", $dataRow['branch']);
                    $sheet->setCellValue("D{$currentRow}", $dataRow['file']);
                    $sheet->setCellValue("E{$currentRow}", $dataRow['note']);
                    $sheet->setCellValue("F{$currentRow}", $dataRow['remark']);

                    $currentRow++;
                }

                $lastRow = max($currentRow - 1, 3);

                $sheet->getStyle("A3:F{$lastRow}")
                    ->getBorders()
                    ->getAllBorders()
                    ->setBorderStyle(Border::BORDER_THIN);
            },
        ];
    }
}
