<?php

namespace App\Exports;

use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\Exportable;
use Carbon\Carbon;

class BookingsExport implements FromView
{
    use Exportable;

    protected $room;
    protected $request;

    protected $models = [
        'meeting_room_1'  => \App\Models\MeetingRoom1::class,
        'meeting_room_4'  => \App\Models\MeetingRoom4::class,
        'meeting_room_5'  => \App\Models\MeetingRoom5::class,
        'guest_room_1'    => \App\Models\GuestRoom1::class,
        'guest_room_2'    => \App\Models\GuestRoom2::class,
        'meeting_room_qc' => \App\Models\RoomQc::class,
        'training_room_1' => \App\Models\TrainingRoom1::class,
        'training_room_2' => \App\Models\TrainingRoom2::class,
        'training_room_3' => \App\Models\TrainingRoom3::class,
    ];

    public function __construct($room, $request)
    {
        $this->room = $room;
        $this->request = $request;
    }

    public function view(): View
    {
        $model = $this->models[$this->room];
        $query = $model::query();

        // Filter cepat
        if ($range = $this->request->range) {
            if ($range === 'today') {
                $query->whereDate('date', Carbon::today());
            } elseif ($range === 'week') {
                $query->whereBetween('date', [
                    Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()
                ]);
            } elseif ($range === 'month') {
                $query->whereMonth('date', Carbon::now()->month)
                      ->whereYear('date', Carbon::now()->year);
            }
        }

        // Filter custom date
        if ($this->request->start_date && $this->request->end_date) {
            $query->whereBetween('date', [
                $this->request->start_date,
                $this->request->end_date
            ]);
        }

        $bookings = $query->orderBy('date')->orderBy('start_time')->get();

        return view('admin.exports.bookings_excel', [
            'bookings' => $bookings,
            'room'     => $this->room,
        ]);
    }
}
