<?php

namespace App\Exports;

use App\Models\Penugasan;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithDrawings;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

class PenugasanExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize, WithDrawings, WithEvents
{
    protected $columns;

    public function __construct(array $columns = [])
    {
        $this->columns = $columns;
    }

    public function collection()
    {
        return Penugasan::with(['petugas', 'pembuat'])->latest()->get();
    }

    public function headings(): array
    {
        if (empty($this->columns)) {
            return [
                'No', 'Nomor Surat', 'Kegiatan', 'Lokasi', 'Keterangan',
                'Tanggal Mulai', 'Tanggal Selesai', 'Status', 'Catatan Status',
                'Daftar Petugas', 'Dibuat Oleh', 'Dokumentasi'
            ];
        }

        $headings = ['No'];
        $map = [
            'nomor_surat' => 'Nomor Surat',
            'kegiatan' => 'Nama Kegiatan',
            'lokasi' => 'Lokasi',
            'keterangan' => 'Deskripsi',
            'tanggal_mulai' => 'Tanggal Pelaksanaan',
            'status' => 'Status',
            'status_note' => 'Catatan Status',
            'petugas' => 'Petugas',
            'pembuat' => 'Dibuat Oleh',
            'dokumentasi' => 'Dokumentasi'
        ];

        foreach ($this->columns as $col) {
            if (isset($map[$col])) {
                $headings[] = $map[$col];
            }
        }

        return $headings;
    }

    public function map($penugasan): array
    {
        static $no = 1;

        if (empty($this->columns)) {
            $namaPetugas = $penugasan->petugas->map(function($p) {
                return $p->name ?? $p->username; 
            })->implode(', ');

            return [
                $no++,
                $penugasan->nomor_surat ?? '-',
                $penugasan->kegiatan,
                $penugasan->lokasi ?? '-',
                $penugasan->keterangan ?? '-',
                $penugasan->tanggal_mulai,
                $penugasan->tanggal_selesai ?? '-',
                strtoupper($penugasan->status),
                $penugasan->status_note ?? '-',
                $namaPetugas ?: 'Belum ada petugas',
                $penugasan->pembuat->name ?? 'System',
                $penugasan->lampiran ? '' : 'Tidak ada'
            ];
        }

        $row = [$no++];
        
        foreach ($this->columns as $col) {
            switch ($col) {
                case 'nomor_surat':
                    $row[] = $penugasan->nomor_surat ?? '-';
                    break;
                case 'kegiatan':
                    $row[] = $penugasan->kegiatan;
                    break;
                case 'lokasi':
                    $row[] = $penugasan->lokasi ?? '-';
                    break;
                case 'keterangan':
                    $row[] = $penugasan->keterangan ?? '-';
                    break;
                case 'tanggal_mulai':
                    $row[] = $penugasan->tanggal_mulai;
                    break;
                case 'status':
                    $row[] = strtoupper($penugasan->status);
                    break;
                case 'status_note':
                    $row[] = $penugasan->status_note ?? '-';
                    break;
                case 'petugas':
                    $namaPetugas = $penugasan->petugas->map(function($p) {
                        return $p->name ?? $p->username; 
                    })->implode(', ');
                    $row[] = $namaPetugas ?: 'Belum ada petugas';
                    break;
                case 'pembuat':
                    $row[] = $penugasan->pembuat->name ?? 'System';
                    break;
                case 'dokumentasi':
                    $row[] = $penugasan->lampiran ? '' : 'Tidak ada';
                    break;
            }
        }

        return $row;
    }

    public function drawings()
    {
        $drawings = [];
        $rowNum = 2; // Data starts at row 2
        $penugasans = $this->collection();

        $headings = $this->headings();
        $colIndex = array_search('Dokumentasi', $headings);

        if ($colIndex !== false) {
            $colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex + 1); // +1 because Excel is 1-based, array_search is 0-based

            foreach ($penugasans as $penugasan) {
                if ($penugasan->lampiran && \Storage::disk('public')->exists($penugasan->lampiran)) {
                    $drawing = new Drawing();
                    $drawing->setName('Dokumentasi');
                    $drawing->setDescription('Dokumentasi');
                    $drawing->setPath(storage_path('app/public/' . $penugasan->lampiran));
                    $drawing->setHeight(70);
                    $drawing->setCoordinates($colLetter . $rowNum);
                    $drawing->setOffsetX(5);
                    $drawing->setOffsetY(5);
                    $drawings[] = $drawing;
                }
                $rowNum++;
            }
        }

        return $drawings;
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function(AfterSheet $event) {
                $penugasans = $this->collection();
                $rowNum = 2;
                
                $headings = $this->headings();
                $hasDokumentasi = in_array('Dokumentasi', $headings);

                if ($hasDokumentasi) {
                    foreach ($penugasans as $penugasan) {
                        if ($penugasan->lampiran && \Storage::disk('public')->exists($penugasan->lampiran)) {
                            $event->sheet->getDelegate()->getRowDimension($rowNum)->setRowHeight(60);
                        }
                        $rowNum++;
                    }

                    $colIndex = array_search('Dokumentasi', $headings);
                    $colLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex + 1);
                    $event->sheet->getDelegate()->getColumnDimension($colLetter)->setWidth(20);
                }
            },
        ];
    }
}