<?php

namespace App\Exports;

use App\Models\Payment;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class PaymentHistoryExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize, WithStyles
{
    public function __construct(
        private int $associationId,
        private ?string $dateFrom = null,
        private ?string $dateTo = null
    ) {}

    public function collection(): Collection
    {
        $query = Payment::where('association_id', $this->associationId)
            ->with(['user:id,firstname,surname,email'])
            ->orderByDesc('paid_at');

        if ($this->dateFrom) {
            $query->where('paid_at', '>=', $this->dateFrom);
        }
        if ($this->dateTo) {
            $query->where('paid_at', '<=', $this->dateTo);
        }

        return $query->get();
    }

    public function headings(): array
    {
        return [
            'Reference',
            'Member',
            'Email',
            'Amount',
            'Currency',
            'Payment Method',
            'Status',
            'Paid At',
            'Created At',
        ];
    }

    /**
     * @param Payment $payment
     */
    public function map($payment): array
    {
        return [
            $payment->reference ?? '—',
            $payment->user ? trim($payment->user->firstname . ' ' . $payment->user->surname) : '—',
            $payment->user?->email ?? '—',
            $payment->amount,
            $payment->currency ?? 'NGN',
            ucfirst(str_replace('_', ' ', $payment->gateway ?? 'Unknown')),
            ucfirst($payment->status),
            $payment->paid_at?->format('Y-m-d H:i') ?? '—',
            $payment->created_at?->format('Y-m-d H:i'),
        ];
    }

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