<?php

namespace App\Exports;

use App\Models\GmailSale;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class GmailSalesExport implements FromCollection, WithHeadings
{
    protected $status;
    protected $fromDate;
    protected $toDate;
    protected $search;
    protected $ids;

    public function __construct(array $filters = [])
    {
        $this->status = $filters['status'] ?? null;
        $this->fromDate = $filters['from_date'] ?? null;
        $this->toDate = $filters['to_date'] ?? null;
        $this->search = $filters['search'] ?? null;
        $this->ids = isset($filters['ids']) && is_array($filters['ids'])
            ? array_values(array_unique(array_map('intval', $filters['ids'])))
            : [];
    }

    public function collection()
    {
        $query = GmailSale::query();

        if ($this->ids !== []) {
            $query->whereIn('id', $this->ids);
        }

        if ($this->status) {
            $query->where('status', $this->status);
        }

        if (!empty($this->fromDate) && !empty($this->toDate)) {
            $query->whereBetween('created_at', [
                Carbon::parse($this->fromDate)->startOfDay(),
                Carbon::parse($this->toDate)->endOfDay(),
            ]);
        }

        if (!empty($this->search)) {
            $gmailList = preg_split('/[\s,]+/', (string) $this->search, -1, PREG_SPLIT_NO_EMPTY);

            if (is_array($gmailList) && $gmailList !== []) {
                $query->where(function ($innerQuery) use ($gmailList) {
                    foreach ($gmailList as $gmail) {
                        $innerQuery->orWhere('gmail', 'LIKE', '%' . $gmail . '%');
                    }
                });
            }
        }

        return $query->latest()->get([
            'gmail',
            'gmail_password',
        ]);
    }

    public function headings(): array
    {
        return [
            'Gmail',
            'Password',
        ];
    }
}
