<?php

namespace App\Exports;

use App\Models\Account;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class AccountsExport implements FromCollection, WithHeadings
{
    protected $filters;

    // Accept filters from controller
    public function __construct($filters)
    {
        $this->filters = $filters;
    }

    public function collection()
    {
        $query = Account::with('user', 'type');

        // Apply search
        if (!empty($this->filters['search'])) {
            $search = $this->filters['search'];

            $query->where('account_number', 'LIKE', "%$search%")
                  ->orWhereHas('user', function($q) use ($search) {
                      $q->where('name', 'LIKE', "%$search%")
                        ->orWhere('email', 'LIKE', "%$search%");
                  });
        }

        // Filter by account type
        if (!empty($this->filters['type'])) {
            $query->where('account_type_id', $this->filters['type']);
        }

        // Filter by status
        if (!empty($this->filters['status'])) {
            $query->where('status', $this->filters['status']);
        }

        return $query->get()->map(function($acc) {
            return [
                'account_number' => $acc->account_number,
                'member_name' => $acc->user->name,
                'member_email' => $acc->user->email,
                'account_type' => $acc->type->name,
                'balance' => $acc->balance,
                'status' => ucfirst($acc->status),
                'created_at' => $acc->created_at->format('Y-m-d H:i'),
            ];
        });
    }

    public function headings(): array
    {
        return [
            'Account Number',
            'Member Name',
            'Member Email',
            'Account Type',
            'Balance (UGX)',
            'Status',
            'Created At'
        ];
    }
}
