<?php
// app/Exports/RegistrationsExport.php

namespace App\Exports;

use App\Models\Registration;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Illuminate\Http\Request;

class RegistrationsExport implements FromQuery, WithHeadings, WithMapping
{
    use Exportable;

    protected $startDate;
    protected $endDate;
    protected $search;
    protected $priority;

    public function __construct($startDate = null, $endDate = null, $search = null, $priority = null)
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
        $this->search = $search;
        $this->priority = $priority;
    }

    public function query()
    {
        $query = Registration::query();

        if ($this->startDate) {
            $query->whereDate('visit_date', '>=', $this->startDate);
        }
        if ($this->endDate) {
            $query->whereDate('visit_date', '<=', $this->endDate);
        }
        if ($this->priority !== null) {
            $query->where('priority', $this->priority);
        }
        if ($this->search) {
            $search = $this->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('nik', 'like', "%{$search}%")
                  ->orWhere('booking_code', 'like', "%{$search}%");
            });
        }

        return $query->orderBy('visit_date', 'desc')
                    ->orderBy('visit_time', 'asc');
    }

    public function headings(): array
    {
        return [
            'Kode Booking',
            'Nama',
            'NIK',
            'No. Telepon',
            'Email',
            'Topik Aduan',
            'Status',
            'Pendamping',
            'Tanggal Kunjungan',
            'Jam Kunjungan',
            'Tanggal Pendaftaran'
        ];
    }

    public function map($registration): array
    {
        return [
            $registration->booking_code,
            $registration->name,
            $registration->nik,
            $registration->phone,
            $registration->email,
            $registration->topic,
            $registration->priority ? 'Kelompok Rentan/Difabel' : 'Reguler',
            $registration->pendamping ?: '-',
            $registration->visit_date,
            $registration->visit_time,
            $registration->created_at
        ];
    }
}