<?php

namespace App\Exports;

use App\Models\User;
use App\Models\SellerWithdrawal;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Illuminate\Http\Request;

class SellerWalletExport implements FromCollection, WithHeadings, WithMapping
{
    protected $filters;

    public function __construct($filters)
    {
        $this->filters = $filters;
    }

    public function collection()
    {
        $query = User::select('id', 'first_name', 'last_name','phone', 'current_balance', 'pending_balance', 'total_earnings');
        $query->whereHas('roles', function ($q) {
            $q->where('title', 'Seller');
        });

        if (!empty($this->filters['name'])) {
            $query->where('first_name', 'like', '%' . $this->filters['name'] . '%')->orWhere('last_name', 'like', '%' . $this->filters['name'] . '%');
        }

        if (!empty($this->filters['full_phone'])) {
            $query->where('phone', 'like', '%' . $this->filters['full_phone'] . '%');
        }

        if(!empty($this->filters['form_current_balance']) && empty($this->filters['to_current_balance'])){
            $query = $query->where('current_balance','>=',$this->filters['form_current_balance']);
        }
        if(!empty($this->filters['to_current_balance']) && empty($this->filters['form_current_balance'])){
            $query = $query->where('current_balance','<=',$this->filters['to_current_balance']);
        }

        if (!empty($this->filters['form_current_balance']) && !empty($this->filters['to_current_balance'])) {
            $query->whereBetween('current_balance', [$this->filters['form_current_balance'], $this->filters['to_current_balance']]);
        }
        if (!empty($this->filters['selectedIds'])) {
            $query->whereIn('id', $this->filters['selectedIds']);
        }

        return $query->get();
    }

    public function headings(): array
    {
        return ["ID", "First Name","Last Name", "Phone Number", "Current Balance", "Pending Balance", "Last Withdrawal", "Total Earnings"];
    }

    public function map($user): array
    {
        $lastWith = SellerWithdrawal::where('user_id', $user->id)->latest()->first();
        return [
            $user->id,
            $user->first_name ?? '-',
            $user->last_name ?? '-',
            $user->phone ?? '-',
            isset($user->current_balance) ? $user->current_balance : '0',
            isset($user->pending_balance) ? $user->pending_balance : '0',
            $lastWith ? $lastWith->amount : 0,
            isset($user->total_earnings) ? $user->total_earnings : '0',
        ];
    }
}
