<?php

namespace App\Exports;

use App\Models\Expense;
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 ExpenseSummaryExport 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 = Expense::where('association_id', $this->associationId)
            ->with(['expenseCategory:id,name', 'expenseable'])
            ->orderByDesc('expense_date');

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

        return $query->get();
    }

    public function headings(): array
    {
        return [
            'Title',
            'Category',
            'Custom Category',
            'Amount',
            'Currency',
            'Vendor',
            'Status',
            'Payment Method',
            'Expense Date',
            'Linked To',
        ];
    }

    /**
     * @param Expense $expense
     */
    public function map($expense): array
    {
        $linkedTo = '—';
        if ($expense->expenseable) {
            $linkedTo = class_basename($expense->expenseable_type) . ': ' . ($expense->expenseable->title ?? $expense->expenseable->name ?? '—');
        }

        return [
            $expense->title,
            Expense::CATEGORIES[$expense->category] ?? ucfirst(str_replace('_', ' ', $expense->category)),
            $expense->expenseCategory?->name ?? '—',
            $expense->amount,
            $expense->currency ?? 'NGN',
            $expense->vendor_name ?? '—',
            ucfirst(str_replace('_', ' ', $expense->status)),
            $expense->payment_method ?? '—',
            $expense->expense_date?->format('Y-m-d'),
            $linkedTo,
        ];
    }

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