<?php

namespace App\Exports;

use App\Models\Transaction;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class TransactionsExport implements FromCollection, WithHeadings, WithMapping
{
    public function collection()
    {
        $query = Transaction::with('member');
        $user = auth()->user();

        if ($user->role === 'regional-treasurer' && $user->region) {
            $query->whereHas('member.leader', function($q) use ($user) {
                $q->where('region', $user->region);
            });
        }

        return $query->latest()->get();
    }

    public function headings(): array
    {
        return [
            'ID',
            'Member Name',
            'Amount (TZS)',
            'Type',
            'Payment Method',
            'Description',
            'Date',
            'Created At',
        ];
    }

    public function map($transaction): array
    {
        return [
            $transaction->id,
            $transaction->member->name ?? 'N/A',
            $transaction->amount,
            ucfirst(str_replace('_', ' ', $transaction->transaction_type)),
            ucfirst(str_replace('_', ' ', $transaction->payment_method ?? 'N/A')),
            $transaction->description ?? '',
            $transaction->transaction_date,
            $transaction->created_at->format('Y-m-d H:i:s'),
        ];
    }
}
