<?php

namespace App\Exports;

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

class RevenueByProductExport implements FromCollection, WithHeadings, WithMapping, WithColumnFormatting, WithEvents, ShouldAutoSize
{
    private int $i = 0;

    public function __construct(
        private Collection $rows,
        private array $summary
    ) {}

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

    public function headings(): array
    {
        return ['#', 'Produk', 'Order', 'Qty', 'Pendapatan', '%'];
    }

    public function map($row): array
    {
        $this->i++;
        $total = (float)($this->summary['total_revenue'] ?? 0);
        $pct = $total > 0 ? ((float)$row->total_revenue / $total) : 0; // 0..1 untuk format persen excel

        return [
            $this->i,
            $row->name,
            (int)$row->total_orders,
            (int)$row->total_qty,
            (float)$row->total_revenue,
            $pct,
        ];
    }

    public function columnFormats(): array
    {
        return [
            'C' => NumberFormat::FORMAT_NUMBER,
            'D' => NumberFormat::FORMAT_NUMBER,
            'E' => '"Rp" #,##0',
            'F' => '0.0%',
        ];
    }

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

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

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

                $sheet->setCellValue("A{$totalRow}", "Total");
                $sheet->mergeCells("A{$totalRow}:D{$totalRow}");
                $sheet->setCellValue("E{$totalRow}", (float)($this->summary['total_revenue'] ?? 0));
                $sheet->setCellValue("F{$totalRow}", 1);

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