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

namespace App\Exports;

use App\Models\Registration;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;

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

    protected $startDate;
    protected $endDate;
    protected $search;
    protected $priority;
    protected $reportType;
    protected $query;

    public function __construct($startDate = null, $endDate = null, $search = null, $priority = null, $reportType = 'online_registration')
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
        $this->search = $search;
        $this->priority = $priority;
        $this->reportType = $reportType;
        
        // Initialize the appropriate query
        $this->initializeQuery();
    }
    
    private function initializeQuery()
    {
        if ($this->reportType == 'online_registration') {
            $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}%");
                });
            }

            $this->query = $query->orderBy('visit_date', 'desc')
                            ->orderBy('visit_time', 'asc');
        } else {
            // Queue reports (all, online, offline)
            $query = DB::table('transaksi');
            
            // Apply specific filters based on queue type
            if ($this->reportType === 'online_queue') {
                $query->where('id_online', '>', 0);
            } elseif ($this->reportType === 'offline_queue') {
                $query->where('id_online', 0);
            }
            
            // Date range filter
            if ($this->startDate) {
                $query->whereDate('waktudatang', '>=', $this->startDate);
            }
            if ($this->endDate) {
                $query->whereDate('waktudatang', '<=', $this->endDate);
            }

            // Search filter
            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}%")
                      ->orWhere('nomorantrian', 'like', "%{$search}%");
                });
            }
            
            $this->query = $query->orderBy('waktudatang', 'desc');
        }
    }

    /**
     * @return Builder
     */
    public function query()
    {
        return $this->query;
    }

    public function headings(): array
    {
        if ($this->reportType == 'online_registration') {
            return [
                'Kode Booking',
                'Nama',
                'Jenis Kelamin',
                'NIK',
                'No. KK',
                'No. Telepon',
                'Email',
                'Topik Aduan',
                'Status',
                'Pendamping',
                'Tanggal Kunjungan',
                'Jam Kunjungan',
                'Tanggal Pendaftaran'
            ];
        } else {
            // For queue reports (all, online, offline)
            return [
                'No. Antrian',
                'Kode Booking',
                'Nama',
                'Jenis Kelamin',
                'NIK',
                'No. KK',
                'No. Telepon',
                'Email',
                'Topik Aduan',
                'Status',
                'Tipe Registrasi',
                'Pendamping',
                'Waktu Kedatangan'
            ];
        }
    }

    public function map($row): array
    {
        if ($this->reportType == 'online_registration') {
            return [
                $row->booking_code,
                $row->name,
                $row->gender == 'L' ? 'Laki-laki' : 'Perempuan',
                $row->nik,
                $row->no_kk ?? '-',
                $row->phone,
                $row->email ?? '-',
                $row->topic ?? '-',
                $row->priority ? 'Kelompok Rentan/Difabel' : 'Reguler',
                $row->pendamping ?? '-',
                $row->visit_date,
                $row->visit_time,
                $row->created_at
            ];
        } else {
            // For queue reports (all, online, offline)
            $registrationType = $row->id_online ? 'Online' : 'Offline';
            
            return [
                $row->nomorantrian,
                $row->booking_code != '-' ? $row->booking_code : '-',
                $row->name,
                $row->gender == 'L' ? 'Laki-laki' : 'Perempuan',
                $row->nik,
                $row->no_kk ?? '-',
                $row->phone,
                $row->email ?? '-',
                $row->topic ?? '-',
                $row->priority ? 'Kelompok Rentan/Difabel' : 'Reguler',
                $registrationType,
                $row->pendamping ?? '-',
                $row->waktudatang
            ];
        }
    }
}