<?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\WithTitle;

class InvoiceExport implements FromCollection, WithHeadings, WithMapping, WithTitle
{
    protected $invoice;

    public function __construct(Invoice $invoice)
    {
        $this->invoice = $invoice->load(['client', 'supplier', 'items.product']);
    }

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

    public function headings(): array
    {
        return [
            'Produit/Service',
            'Description',
            'Quantité',
            'Unité',
            'Prix unitaire (MAD)',
            'Taux TVA (%)',
            'Total HT (MAD)',
            'Total TVA (MAD)',
            'Total TTC (MAD)',
        ];
    }

    public function map($item): array
    {
        return [
            $item->product_name,
            $item->description,
            $item->quantity,
            $item->unit,
            number_format($item->unit_price, 2),
            $item->vat_rate,
            number_format($item->total_ht, 2),
            number_format($item->total_vat, 2),
            number_format($item->total_ttc, 2),
        ];
    }

    public function title(): string
    {
        return 'Facture ' . $this->invoice->number;
    }
}