<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\Room;
use Illuminate\Http\Request;
use Carbon\Carbon;

class BookingController extends Controller
{
    public function checkAvailability(Request $request)
    {
        $validated = $request->validate([
            'check_in' => 'required|date|after_or_equal:today',
            'check_out' => 'required|date|after:check_in',
            'adults' => 'required|integer|min:1',
            'children' => 'nullable|integer|min:0',
        ]);

        $availableRooms = Room::whereDoesntHave('bookings', function ($query) use ($validated) {
            $query->where(function ($q) use ($validated) {
                $q->whereBetween('check_in', [$validated['check_in'], $validated['check_out']])
                  ->orWhereBetween('check_out', [$validated['check_in'], $validated['check_out']])
                  ->orWhere(function ($q2) use ($validated) {
                      $q2->where('check_in', '<=', $validated['check_in'])
                         ->where('check_out', '>=', $validated['check_out']);
                  });
            })->whereIn('status', ['confirmed', 'checked_in']);
        })->get();

        return response()->json([
            'available_rooms' => $availableRooms,
            'check_in' => $validated['check_in'],
            'check_out' => $validated['check_out'],
        ]);
    }

    public function reserve(Request $request)
    {
        $validated = $request->validate([
            'room_id' => 'required|exists:rooms,id',
            'check_in' => 'required|date|after_or_equal:today',
            'check_out' => 'required|date|after:check_in',
            'adults' => 'required|integer|min:1',
            'children' => 'nullable|integer|min:0',
            'guest_name' => 'required|string|max:255',
            'guest_email' => 'required|email|max:255',
            'guest_phone' => 'required|string|max:20',
            'special_requests' => 'nullable|string',
        ]);

        $validated['status'] = 'pending';
        $booking = Booking::create($validated);

        // Load the room relationship for emails
        $booking->load('room');

        // Send email to customer
        try {
            \Illuminate\Support\Facades\Mail::to($booking->guest_email)
                ->send(new \App\Mail\BookingConfirmation($booking));
        } catch (\Exception $e) {
            \Log::error('Failed to send booking confirmation email: ' . $e->getMessage());
        }

        // Send email to admin
        try {
            \Illuminate\Support\Facades\Mail::to('kcsuman1415@gmail.com')
                ->send(new \App\Mail\NewBookingNotification($booking));
        } catch (\Exception $e) {
            \Log::error('Failed to send admin notification email: ' . $e->getMessage());
        }

        return redirect()->back()->with('success', 'Your booking request has been submitted successfully! A confirmation email has been sent to your email address. We will contact you shortly.');
    }
}

