<?php

namespace App\Services\ImportExport\Handlers;

use App\Models\Expense;

class ExpensesHandler extends AbstractModuleHandler
{
    public function key(): string
    {
        return 'expenses';
    }

    public function label(): string
    {
        return 'Expenses';
    }

    public function permissionModule(): string
    {
        return 'finance';
    }

    public function exportData(array $filters): array
    {
        $query = Expense::query()->with(['supplier', 'account'])->latest('expense_date');

        if ($status = ($filters['status'] ?? null)) {
            $query->where('status', $status);
        }

        $expenses = $query->get();

        return [
            'title' => 'Expenses Export',
            'sheet_name' => 'Expenses',
            'headings' => ['Expense #', 'Supplier', 'Account', 'Date', 'Amount', 'On Credit', 'Status', 'Description'],
            'rows' => $expenses->map(fn (Expense $e) => [
                $e->expense_number,
                $e->supplier?->name ?? '—',
                $e->account ? "{$e->account->code} — {$e->account->name}" : '—',
                optional($e->expense_date)->format('Y-m-d'),
                number_format((float) $e->amount, 2, '.', ''),
                $e->on_credit ? 'Yes' : 'No',
                $e->status,
                $e->description,
            ])->all(),
            'filters' => $this->filterSummary($filters),
            'totals' => ['Count' => $expenses->count(), 'Total' => number_format((float) $expenses->sum('amount'), 2)],
        ];
    }
}
