<?php

namespace App\Http\Controllers;

use App\Models\Hall;
use App\Models\HallBooking;
use Illuminate\Http\Request;
use Carbon\Carbon;

class HallBookingController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'hall_id' => 'required|exists:halls,id',
            'event_date' => 'required|date|after_or_equal:today',
            'event_type' => 'required|string|max:255',
        ]);

        $hall = Hall::findOrFail($validated['hall_id']);

        // Check if already booked for that date
        $exists = HallBooking::where('hall_id', $hall->id)
            ->where('event_date', $validated['event_date'])
            ->whereIn('status', ['confirmed', 'pending'])
            ->exists();

        if ($exists) {
            return back()->with('error', 'The hall is already booked or has a pending request for this date.');
        }

        $booking = HallBooking::create([
            'user_id' => auth()->id(),
            'hall_id' => $hall->id,
            'event_date' => $validated['event_date'],
            'event_type' => $validated['event_type'],
            'total_price' => $hall->price_per_day,
            'status' => 'pending',
        ]);

        return redirect()->route('hall-booking.confirmation', $booking->id)->with('success', 'Booking request submitted successfully!');
    }

    public function confirmation(HallBooking $booking)
    {
        if ($booking->user_id !== auth()->id()) {
            abort(403);
        }
        return view('halls.confirmation', compact('booking'));
    }
}
