<?php

namespace App\Exports;

use App\Exports\Concerns\SanitizaCeldasExcel;
use App\Models\Factura;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class VentasExport implements FromCollection, WithHeadings, WithMapping
{
    use SanitizaCeldasExcel;

    public function __construct(private int $mes, private int $anio)
    {
    }

    public function collection()
    {
        return Factura::with('cliente')
            ->whereMonth('created_at', $this->mes)
            ->whereYear('created_at', $this->anio)
            ->orderBy('numero')
            ->get();
    }

    public function headings(): array
    {
        return ['N° Factura', 'Fecha', 'Cliente', 'Cédula/RIF', 'Subtotal', 'Impuestos', 'Total', 'Estado'];
    }

    public function map($factura): array
    {
        $impuestos = collect($factura->impuestos_desglose ?? [])
            ->map(fn ($g) => "{$g['nombre']}: ".number_format($g['monto'], 2))
            ->implode(' / ');

        return [
            $factura->numeroFormateado(),
            $factura->created_at->format('d/m/Y'),
            $this->celda($factura->cliente->nombre),
            $factura->cliente->cedula,
            (float) $factura->subtotal,
            $impuestos ?: '—',
            (float) $factura->total,
            $factura->esNotaCredito() ? 'Nota de crédito' : 'Pagada',
        ];
    }
}
