<?php

namespace App\Exports;

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

class ContributionsExport implements FromCollection, WithHeadings, WithMapping
{
    public function collection()
    {
        $query = Contribution::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',
            'Member Phone',
            'Amount (TZS)',
            'Payment Method',
            'Date',
            'Created At',
        ];
    }

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