<?php

namespace App\Exports;

use App\Models\Payment;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class PaymentsExport implements FromQuery, WithHeadings, WithMapping, WithStyles
{
    public function __construct(private array $filters = []) {}

    public function query(): Builder
    {
        $q = Payment::with(['sale.client', 'account'])
            ->orderBy('payment_date', 'desc');

        if (!empty($this->filters['currency'])) {
            $q->where('currency', $this->filters['currency']);
        }
        if (!empty($this->filters['date_from'])) {
            $q->whereDate('payment_date', '>=', $this->filters['date_from']);
        }
        if (!empty($this->filters['date_to'])) {
            $q->whereDate('payment_date', '<=', $this->filters['date_to']);
        }

        return $q;
    }

    public function headings(): array
    {
        return [
            'ID', 'Cliente', 'Venta', 'Cuenta', 'Fecha Pago',
            'Moneda', 'Monto', 'Comisión', 'Neto', 'Nota',
        ];
    }

    public function map($payment): array
    {
        return [
            $payment->id,
            $payment->sale?->client?->name,
            $payment->sale?->title,
            $payment->account?->name,
            $payment->payment_date?->format('d/m/Y'),
            $payment->currency?->value,
            number_format((float) $payment->amount, 2),
            number_format((float) $payment->fee_amount, 2),
            number_format((float) $payment->net_amount, 2),
            $payment->note,
        ];
    }

    public function styles(Worksheet $sheet): array
    {
        return [1 => ['font' => ['bold' => true]]];
    }
}
