<?php
namespace App\Modules\HR\Reports\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

class MissedPunchesExport implements
    FromCollection,
    WithHeadings,
    WithColumnWidths,
    WithStyles,
    WithTitle
{
    protected $records;
    protected $filters;

    public function __construct($data)
    {
        $this->records = $data['records'];
        $this->filters = $data['filters'] ?? [];
    }

    public function title(): string
    {
        return 'Missed Punches';
    }

    public function headings(): array
    {
        return [
            '#',
            'Emp Code',
            'Employee Name',
            'Department',
            'Designation',
            'Date',
            'In Time',
            'Out Time',
            'Missed',
        ];
    }

    public function collection()
    {
        return $this->records->values()->map(function ($row, $i) {
            if (is_null($row->in_time) && is_null($row->out_time)) {
                $status = 'Both Missing';
            } elseif (is_null($row->in_time)) {
                $status = 'In Missing';
            } else {
                $status = 'Out Missing';
            }

            $name = trim(
                $row->employee->first_name . ' ' .
                ($row->employee->middle_name ?? '') . ' ' .
                $row->employee->last_name
            );

            return [
                $i + 1,
                $row->employee->employee_code,
                $name,
                optional($row->employee->department)->name ?? '',
                optional($row->employee->designation)->name ?? '',
                $row->attendance->attendance_date->format('Y-m-d'),
                $row->in_time  ? $row->in_time->format('H:i')  : '',
                $row->out_time ? $row->out_time->format('H:i') : '',
                $status,
            ];
        });
    }

    public function columnWidths(): array
    {
        return [
            'A' => 6,    // #
            'B' => 14,   // Emp Code
            'C' => 32,   // Employee Name
            'D' => 24,   // Department
            'E' => 24,   // Designation
            'F' => 14,   // Date
            'G' => 12,   // In Time
            'H' => 12,   // Out Time
            'I' => 16,   // Missed
        ];
    }

    public function styles(Worksheet $sheet)
    {
        $lastRow = $this->records->count() + 1;

        // Heading row style
        $sheet->getStyle('A1:I1')->applyFromArray([
            'font' => [
                'bold'  => true,
                'size'  => 11,
                'color' => ['rgb' => 'FFFFFF'],
            ],
            'fill' => [
                'fillType'   => Fill::FILL_SOLID,
                'startColor' => ['rgb' => '2C3E50'],
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical'   => Alignment::VERTICAL_CENTER,
            ],
        ]);

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

        // Set heading row height
        $sheet->getRowDimension(1)->setRowHeight(20);

        // Data rows — borders + alternating fill
        if ($lastRow > 1) {
            $sheet->getStyle("A2:I{$lastRow}")->applyFromArray([
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => Border::BORDER_THIN,
                        'color'       => ['rgb' => 'DCE0E3'],
                    ],
                ],
                'alignment' => [
                    'vertical' => Alignment::VERTICAL_CENTER,
                ],
            ]);
        }

        // Alternate row colors
        for ($row = 2; $row <= $lastRow; $row++) {
            if ($row % 2 === 0) {
                $sheet->getStyle("A{$row}:I{$row}")->applyFromArray([
                    'fill' => [
                        'fillType'   => Fill::FILL_SOLID,
                        'startColor' => ['rgb' => 'F4F6F8'],
                    ],
                ]);
            }
        }

        // Center-align specific columns
        if ($lastRow > 1) {
            $sheet->getStyle("A2:A{$lastRow}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); // #
            $sheet->getStyle("F2:H{$lastRow}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); // Date, In, Out
            $sheet->getStyle("I2:I{$lastRow}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); // Status
        }

        // Color the "Missed" column cells by status
        for ($row = 2; $row <= $lastRow; $row++) {
            $val = $sheet->getCell("I{$row}")->getValue();
            if ($val === 'Both Missing') {
                $sheet->getStyle("I{$row}")->applyFromArray([
                    'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
                    'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'C0392B']],
                ]);
            } elseif ($val === 'In Missing') {
                $sheet->getStyle("I{$row}")->applyFromArray([
                    'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
                    'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'E67E22']],
                ]);
            } elseif ($val === 'Out Missing') {
                $sheet->getStyle("I{$row}")->applyFromArray([
                    'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
                    'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'D35400']],
                ]);
            }

            // Highlight empty In/Out time cells
            if ($sheet->getCell("G{$row}")->getValue() === '') {
                $sheet->getStyle("G{$row}")->getFont()->getColor()->setRGB('C0392B');
            }
            if ($sheet->getCell("H{$row}")->getValue() === '') {
                $sheet->getStyle("H{$row}")->getFont()->getColor()->setRGB('C0392B');
            }
        }

        // Outer border around the full table
        if ($lastRow > 1) {
            $sheet->getStyle("A1:I{$lastRow}")->applyFromArray([
                'borders' => [
                    'outline' => [
                        'borderStyle' => Border::BORDER_MEDIUM,
                        'color'       => ['rgb' => '2C3E50'],
                    ],
                ],
            ]);
        }

        return [];
    }
}
