<?php

namespace App\Exports;

use App\Enums\PaymentStatus;
use App\Models\Sale;
use App\Models\SystemSetting;
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 CxCExport implements FromQuery, WithHeadings, WithMapping, WithStyles
{
    private float $rate;

    public function __construct(private array $filters = [])
    {
        $this->rate = (float) SystemSetting::current()->exchange_rate_usd_bob;
    }

    public function query(): Builder
    {
        $q = Sale::with('client')
            ->where('payment_status', '!=', PaymentStatus::Paid->value)
            ->orderBy('expected_collect_date');

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

        return $q;
    }

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

    public function map($sale): array
    {
        $hasDate  = (bool) $sale->expected_collect_date;
        $isPast   = $hasDate && $sale->expected_collect_date->isPast();
        $daysOver = $isPast ? (int) now()->diffInDays($sale->expected_collect_date) : 0;

        return [
            $sale->id,
            $sale->client?->name,
            $sale->title,
            $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),
            $daysOver > 0 ? '+' . $daysOver . ' días' : 'Al día',
            $sale->expected_collect_date?->format('d/m/Y'),
            $sale->payment_status?->label(),
        ];
    }

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