<?php

namespace App\Exports;

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

class LoansExport implements FromCollection, WithHeadings, WithMapping
{
    public function collection()
    {
        $query = Loan::with(['user', 'leaderApprover', 'approver', 'disburser']);
        $user = auth()->user();

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

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

    public function headings(): array
    {
        return [
            'ID',
            'Member Name',
            'Member Email',
            'Amount (TZS)',
            'Purpose',
            'Status',
            'Requested Date',
            'Leader Approved By',
            'Leader Approved Date',
            'Final Approved By',
            'Final Approved Date',
            'Disbursed By',
            'Disbursed Date',
            'Payment Amount',
            'Payment Method',
        ];
    }

    public function map($loan): array
    {
        return [
            $loan->id,
            $loan->user->name ?? 'N/A',
            $loan->user->email ?? 'N/A',
            $loan->amount,
            $loan->purpose,
            $loan->getStatusText(),
            $loan->created_at->format('Y-m-d'),
            $loan->leaderApprover->name ?? 'N/A',
            $loan->leader_approved_at ? $loan->leader_approved_at->format('Y-m-d') : 'N/A',
            $loan->approver->name ?? 'N/A',
            $loan->approved_at ? $loan->approved_at->format('Y-m-d') : 'N/A',
            $loan->disburser->name ?? 'N/A',
            $loan->disbursed_at ? $loan->disbursed_at->format('Y-m-d') : 'N/A',
            $loan->payment_amount ?? 'N/A',
            $loan->payment_method ? ucfirst(str_replace('_', ' ', $loan->payment_method)) : 'N/A',
        ];
    }
}
