<?php

namespace App\Exports;

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

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

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

    public function collection()
    {
        $query = Deposit::query();
        // Apply filters based on the provided inputs
        if (isset($this->filters['filter_status']) && $this->filters['filter_status'] !== '') {
            $query->where('status', $this->filters['filter_status']);
        }

        if (isset($this->filters['filter_user']) && $this->filters['filter_user'] !== '') {
            $query->whereHas('user', function($query){
                $query->where('username', 'like', "%".escape_input($this->filters['filter_user'])."%");
            });
        }

        if (isset($this->filters['filter_method']) && $this->filters['filter_method'] !== '') {
            $query->where('deposit_method_name', $this->filters['filter_method']);
        }

            // Apply filters based on the provided inputs
        if (!empty($this->filters['filter_start_date']) && !empty($this->filters['filter_end_date'])) {
            $start_date = month_format($this->filters['filter_start_date']);
            $end_date = month_format($this->filters['filter_end_date']);
            $query->whereRaw('DATE(created_at) BETWEEN "'.date('Y-m-d', strtotime($start_date)).'" AND "'.date('Y-m-d', strtotime($end_date)).'"');
        }


        // Add more filters as needed

        return $query->get(['id', 'user_id', 'deposit_method_name', 'amount', 'balance', 'status', 'created_at']);
    }

    public function headings(): array
    {
        return [
            'ID & Tanggal',  // id & created_at
            'Pengguna',      // user_id
            'Metode',       // service_name
            'Jumlah',  // price
            'Saldo Didapat', // saldo didapat
            'Status',        // status
        ];
    }

    public function map($deposit): array
    {
        return [
            $deposit->id . ' & ' . $deposit->created_at,
            $deposit->user ? $deposit->user->username : 'Unknown User',
            $deposit->deposit_method_name,
            $deposit->amount,
            $deposit->balance,
            $deposit->status,
        ];
    }
}
