<?php

namespace App\Exports;

use App\Models\Invoice;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class LaporanExport implements 
    FromCollection, 
    WithHeadings, 
    WithMapping, 
    ShouldAutoSize, 
    WithStyles, 
    WithColumnFormatting,
    WithEvents
{
    protected $startDate, $endDate, $status, $search, $userId;
    protected $totalAmount = 0;
    protected $rowCount = 0;

    public function __construct($startDate, $endDate, $status, $search, $userId = null)
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
        $this->status = $status;
        $this->search = $search;
        $this->userId = $userId; 
    }

    public function collection()
    {
        $query = Invoice::with('user')
            ->whereBetween('created_at', [$this->startDate . ' 00:00:00', $this->endDate . ' 23:59:59']);

        // ✅ FILTER USER
        if ($this->userId) {
            $query->where('user_id', $this->userId);
        }
        if ($this->status && $this->status !== 'all') {
            $query->where('status', $this->status);
        }
        if ($this->search) {
            $query->where(function($q) {
                $q->where('invoice_number', 'LIKE', "%{$this->search}%")
                  ->orWhereHas('user', function($sub) {
                      $sub->where('name', 'LIKE', "%{$this->search}%");
                  });
            });
        }

        $invoices = $query->orderBy('created_at', 'desc')->get();
        
        $this->totalAmount = $invoices->sum('total_amount');
        $this->rowCount = $invoices->count();

        return $invoices;
    }

    public function headings(): array
    {
        return [
            'No',
            'ID Tagihan',
            'Pelanggan',
            'Total (Rp)',
            'Status',
            'Metode Pembayaran',
            'Tgl Dibuat',
            'Tgl Dibayar',
        ];
    }

    public function map($invoice): array
    {
        static $no = 0;
        $no++;
        return [
            $no,
            $invoice->invoice_number,
            $invoice->user->name ?? '-',
            (int) $invoice->total_amount,
            ucfirst($invoice->status),
            $invoice->payment_method ?? '-',
            $invoice->created_at->format('d M Y, H:i'),
            $invoice->paid_at ? $invoice->paid_at->format('d M Y, H:i') : '-',
        ];
    }

    public function columnFormats(): array
    {
        return [
            'D' => '#,##0', // Format rupiah tanpa desimal
        ];
    }

    public function styles(Worksheet $sheet)
    {
        // Header: Bold + Background Biru + Putih
        $sheet->getStyle('A1:H1')->applyFromArray([
            'font' => ['bold' => true, 'size' => 11, 'color' => ['rgb' => 'FFFFFF']],
            'fill' => [
                'fillType' => 'solid',
                'startColor' => ['rgb' => '00529C'],
            ],
            'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
        ]);

        // Semua border
        $lastRow = $sheet->getHighestRow();
        $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
            'borders' => [
                'allBorders' => [
                    'borderStyle' => 'thin',
                    'color' => ['rgb' => 'D1D5DB'],
                ],
            ],
        ]);

        // Alignment tengah
        $sheet->getStyle('A1:H' . $lastRow)->getAlignment()
            ->setVertical('center');

        return [];
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function(AfterSheet $event) {
                $sheet = $event->sheet->getDelegate();
                $lastRow = $sheet->getHighestRow();
                $totalRow = $lastRow + 2;

                // Auto Filter
                $sheet->setAutoFilter('A1:H' . $lastRow);

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

                // ✅ TOTAL DI BAWAH
                $sheet->setCellValue('C' . $totalRow, 'TOTAL');
                $sheet->setCellValue('D' . $totalRow, $this->totalAmount);

                // Style Total
                $sheet->getStyle('C' . $totalRow . ':D' . $totalRow)->applyFromArray([
                    'font' => ['bold' => true, 'size' => 12],
                    'fill' => [
                        'fillType' => 'solid',
                        'startColor' => ['rgb' => 'F3F4F6'],
                    ],
                    'borders' => [
                        'top' => ['borderStyle' => 'double', 'color' => ['rgb' => '00529C']],
                        'bottom' => ['borderStyle' => 'double', 'color' => ['rgb' => '00529C']],
                    ],
                ]);

                $sheet->getStyle('D' . $totalRow)->getNumberFormat()
                    ->setFormatCode('#,##0');
            },
        ];
    }
}