<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BookingController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'room_id' => 'required|exists:rooms,id',
            'check_in' => 'required|date|after:today',
            'check_out' => 'required|date|after:check_in',
        ]);

        $room = \App\Models\Room::findOrFail($validated['room_id']);
        
        // Check room availability
        if (!$room->isAvailable($validated['check_in'], $validated['check_out'])) {
            return back()->withErrors([
                'dates' => 'This room is not available for the selected dates. Please choose different dates.'
            ])->withInput();
        }
        
        // Calculate total price
        $checkIn = \Carbon\Carbon::parse($validated['check_in']);
        $checkOut = \Carbon\Carbon::parse($validated['check_out']);
        $days = $checkIn->diffInDays($checkOut);
        $totalPrice = $room->price * $days;

        $booking = \App\Models\Booking::create([
            'user_id' => auth()->id(),
            'room_id' => $validated['room_id'],
            'check_in' => $validated['check_in'],
            'check_out' => $validated['check_out'],
            'total_price' => $totalPrice,
            'status' => 'pending',
            'payment_status' => 'pending',
        ]);

        // Send booking confirmation email
        try {
            \Mail::to($booking->user->email)->send(new \App\Mail\BookingConfirmation($booking));
        } catch (\Exception $e) {
            // Log error but don't fail the booking
            \Log::error('Failed to send booking confirmation email: ' . $e->getMessage());
        }

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

    public function confirmation(\App\Models\Booking $booking)
    {
        if ($booking->user_id !== auth()->id()) {
            abort(403);
        }
        
        return view('bookings.confirmation', compact('booking'));
    }

    /**
     * Check room availability via AJAX
     */
    public function checkAvailability(Request $request)
    {
        $validated = $request->validate([
            'room_id' => 'required|exists:rooms,id',
            'check_in' => 'required|date|after:today',
            'check_out' => 'required|date|after:check_in',
        ]);

        $room = \App\Models\Room::findOrFail($validated['room_id']);
        $isAvailable = $room->isAvailable($validated['check_in'], $validated['check_out']);

        return response()->json([
            'available' => $isAvailable,
            'message' => $isAvailable 
                ? 'Room is available for the selected dates!' 
                : 'This room is already booked for the selected dates. Please choose different dates.',
            'booked_dates' => $room->getBookedDates(),
        ]);
    }
}
