<?php

namespace App\Exports;

use App\Models\Sale;
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 SalesExport implements FromQuery, WithHeadings, WithMapping, WithStyles
{
    public function __construct(private array $filters = []) {}

    public function query(): Builder
    {
        $q = Sale::with(['client', 'owner'])
            ->orderBy('sale_date', 'desc');

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

        return $q;
    }

    public function headings(): array
    {
        return [
            'ID', 'Cliente', 'Título', 'Origen', 'Tipo', 'Fecha Venta',
            'Moneda', 'Bruto', 'Fee Plataforma', 'Neto', 'Cobrado', 'Saldo', 'Estado',
            'F. Cobro Esperada', 'Responsable',
        ];
    }

    public function map($sale): array
    {
        return [
            $sale->id,
            $sale->client?->name,
            $sale->title,
            $sale->origin?->label(),
            $sale->sale_type?->label(),
            $sale->sale_date?->format('d/m/Y'),
            $sale->currency?->value,
            number_format((float) $sale->gross_amount, 2),
            number_format((float) $sale->platform_fee, 2),
            number_format($sale->net_expected, 2),
            number_format((float) $sale->collected_amount_cached, 2),
            number_format($sale->balance, 2),
            $sale->payment_status?->label(),
            $sale->expected_collect_date?->format('d/m/Y'),
            $sale->owner?->name,
        ];
    }

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