<?php

namespace App\Exports;

use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
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 GradesExport implements FromArray, WithStyles, WithTitle, ShouldAutoSize, WithEvents
{
    protected $grades;
    protected $exam;
    protected int $dataStart = 5; // baris 1-3 = info, baris 4 = heading, baris 5+ = data

    public function __construct($grades, $exam = null)
    {
        $this->grades = $grades;
        $this->exam   = $exam;
    }

    public function title(): string
    {
        return 'Laporan Nilai';
    }

    public function array(): array
    {
        // ── Baris 1-3: Info ──────────────────────────────────────
        $rows = [
            ['LAPORAN NILAI UJIAN', '', '', '', '', '', '', ''],
            ['Ujian: ' . ($this->exam?->title ?? '-'), '', '', '', '', '', '', ''],
            ['Dicetak: ' . Carbon::now()->isoFormat('D MMMM Y, HH:mm') . ' WIB', '', '', '', '', '', '', ''],
            // ── Baris 4: Heading ──────────────────────────────────
            ['No.', 'Nama Siswa', 'Sesi', 'Ruangan / Kelas', 'Mata Pelajaran', 'Jumlah Benar', 'Nilai Akhir', 'Keterangan'],
        ];

        // ── Baris 5+: Data ────────────────────────────────────────
        $no = 1;
        foreach ($this->grades as $row) {
            $grade = floatval($row->grade ?? 0);
            $ket   = $grade >= 80 ? 'Sangat Baik'
                   : ($grade >= 70 ? 'Baik'
                   : ($grade >= 60 ? 'Cukup'
                   : 'Kurang'));

            $rows[] = [
                $no++,
                $row->student->name ?? '-',
                $row->exam_session->title ?? '-',
                $row->exam->classroom->title ?? '-',
                $row->exam->lesson->title ?? '-',
                $row->total_correct ?? 0,
                $grade,
                $ket,
            ];
        }

        return $rows;
    }

    public function styles(Worksheet $sheet): array
    {
        $lastCol    = 'H';
        $headingRow = 4;
        $dataStart  = $this->dataStart;
        $totalRows  = count($this->grades) + $headingRow;

        // ── Merge & style info baris 1-3 ─────────────────────────
        $sheet->mergeCells("A1:{$lastCol}1");
        $sheet->getStyle('A1')->applyFromArray([
            'font'      => ['bold' => true, 'size' => 14, 'color' => ['argb' => 'FF1E3A5F']],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
        ]);
        $sheet->getRowDimension(1)->setRowHeight(28);

        $sheet->mergeCells("A2:{$lastCol}2");
        $sheet->getStyle('A2')->applyFromArray([
            'font'      => ['bold' => true, 'size' => 11, 'color' => ['argb' => 'FF374151']],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
        ]);
        $sheet->getRowDimension(2)->setRowHeight(20);

        $sheet->mergeCells("A3:{$lastCol}3");
        $sheet->getStyle('A3')->applyFromArray([
            'font'      => ['italic' => true, 'size' => 9, 'color' => ['argb' => 'FF6B7280']],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
        ]);
        $sheet->getRowDimension(3)->setRowHeight(16);

        // ── Heading row (baris 4) ────────────────────────────────
        $sheet->getStyle("A{$headingRow}:{$lastCol}{$headingRow}")->applyFromArray([
            'font' => [
                'bold'  => true,
                'color' => ['argb' => 'FFFFFFFF'],
                'size'  => 10,
            ],
            'fill' => [
                'fillType'   => Fill::FILL_SOLID,
                'startColor' => ['argb' => 'FF1E3A8A'],
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical'   => Alignment::VERTICAL_CENTER,
                'wrapText'   => true,
            ],
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color'       => ['argb' => 'FF93C5FD'],
                ],
            ],
        ]);
        $sheet->getRowDimension($headingRow)->setRowHeight(26);

        // ── Data rows ────────────────────────────────────────────
        for ($r = $dataStart; $r <= $totalRows; $r++) {
            $bgColor  = ($r % 2 === 0) ? 'FFF0F6FF' : 'FFFFFFFF';
            $gradeVal = floatval($sheet->getCell("G{$r}")->getValue());

            // Baris alternating
            $sheet->getStyle("A{$r}:{$lastCol}{$r}")->applyFromArray([
                'fill' => [
                    'fillType'   => Fill::FILL_SOLID,
                    'startColor' => ['argb' => $bgColor],
                ],
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => Border::BORDER_HAIR,
                        'color'       => ['argb' => 'FFD1D5DB'],
                    ],
                ],
                'alignment' => ['vertical' => Alignment::VERTICAL_CENTER],
            ]);
            $sheet->getRowDimension($r)->setRowHeight(22);

            // Center: No., Jumlah Benar, Nilai Akhir, Keterangan
            $sheet->getStyle("A{$r}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
            $sheet->getStyle("F{$r}:H{$r}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

            // Warna nilai akhir
            $fillArgb = 'FFDCFCE7'; $fontArgb = 'FF166534'; // hijau
            if ($gradeVal < 60)      { $fillArgb = 'FFFEE2E2'; $fontArgb = 'FF991B1B'; } // merah
            elseif ($gradeVal < 70)  { $fillArgb = 'FFFFF7ED'; $fontArgb = 'FF9A3412'; } // orange
            elseif ($gradeVal < 80)  { $fillArgb = 'FFFEF9C3'; $fontArgb = 'FF854D0E'; } // kuning

            $sheet->getStyle("G{$r}")->applyFromArray([
                'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['argb' => $fillArgb]],
                'font' => ['bold' => true, 'color' => ['argb' => $fontArgb]],
            ]);
        }

        // ── Outer border seluruh tabel ────────────────────────────
        if ($totalRows >= $headingRow) {
            $sheet->getStyle("A{$headingRow}:{$lastCol}{$totalRows}")->applyFromArray([
                'borders' => [
                    'outline' => [
                        'borderStyle' => Border::BORDER_MEDIUM,
                        'color'       => ['argb' => 'FF1E3A8A'],
                    ],
                ],
            ]);
        }

        // ── Lebar kolom manual ────────────────────────────────────
        $sheet->getColumnDimension('A')->setWidth(6);
        $sheet->getColumnDimension('F')->setWidth(15);
        $sheet->getColumnDimension('G')->setWidth(14);
        $sheet->getColumnDimension('H')->setWidth(14);

        // ── Freeze header ─────────────────────────────────────────
        $sheet->freezePane("A{$dataStart}");

        return [];
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                $event->sheet->getDelegate()->getTabColor()->setARGB('FF1E3A8A');
            },
        ];
    }
}