<?php

namespace App\Exports;

use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class RevenueByTransactionExport implements FromCollection, WithHeadings, WithMapping, WithColumnFormatting, WithEvents, ShouldAutoSize
{
    public function __construct(
        private Collection $rows,
        private array $summary
    ) {}

    public function collection()
    {
        return $this->rows;
    }

    public function headings(): array
    {
        return [
            'Tanggal Bayar',
            'Invoice',
            'Pelanggan',
            'Status',
            'Jenis',
            'Rekening',
            'Kasir',
            'Dibayar',
            'Kembalian',
            'Pendapatan Bersih',
        ];
    }

    public function map($row): array
    {
        $paymentDate = null;

        if (!empty($row->payment_date)) {
            $paymentDate = $row->payment_date instanceof \DateTimeInterface
                ? $row->payment_date
                : Carbon::parse($row->payment_date);
        }

        return [
            $paymentDate ? ExcelDate::dateTimeToExcel($paymentDate) : null,
            $row->invoice_number ?? '-',
            $row->customer_name ?? '-',
            $row->status_label ?? '-',
            $row->payment_method_label ?? '-',
            $row->payment_account_label ?? '-',
            $row->cashier_name ?? '-',
            (float) ($row->paid_amount ?? 0),
            (float) ($row->change_amount ?? 0),
            (float) ($row->net_amount ?? $row->amount ?? 0),
        ];
    }

    public function columnFormats(): array
    {
        return [
            'A' => 'dd/mm/yyyy hh:mm',
            'H' => '"Rp" #,##0',
            'I' => '"Rp" #,##0',
            'J' => '"Rp" #,##0',
        ];
    }

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

                $sheet->getStyle('A1:J1')->getFont()->setBold(true);
                $sheet->freezePane('A2');

                $lastRow = $sheet->getHighestRow();
                $totalRow = $lastRow + 1;

                $sheet->setCellValue("A{$totalRow}", 'Total ' . $this->rows->count() . ' Pembayaran Masuk');
                $sheet->mergeCells("A{$totalRow}:I{$totalRow}");
                $sheet->setCellValue("J{$totalRow}", (float) ($this->summary['total_revenue'] ?? 0));

                $sheet->getStyle("A{$totalRow}:J{$totalRow}")->getFont()->setBold(true);
                $sheet->getStyle("J{$totalRow}")->getNumberFormat()->setFormatCode('"Rp" #,##0');
            },
        ];
    }
}
