<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Room;
use App\Models\RoomType;
use Illuminate\Support\Facades\DB;

class RoomController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:view-rooms')->only(['index', 'show']);
        $this->middleware('permission:create-rooms')->only(['create', 'store']);
        $this->middleware('permission:edit-rooms')->only(['edit', 'update']);
        $this->middleware('permission:delete-rooms')->only(['destroy']);
    }

    public function index(Request $request)
    {
        $query = Room::with('roomType')->where('deleteStatus', false);

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('room_no', 'like', "%{$search}%")
                  ->orWhere('floor', 'like', "%{$search}%")
                  ->orWhereHas('roomType', function($roomTypeQuery) use ($search) {
                      $roomTypeQuery->where('room_type', 'like', "%{$search}%");
                  });
            });
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('room_status', $request->status);
        }

        // Filter by room type
        if ($request->filled('room_type_id')) {
            $query->where('room_type_id', $request->room_type_id);
        }

        // Pagination
        $perPage = $request->get('per_page', 10);
        $rooms = $query->orderBy('room_no')->paginate($perPage);
        $roomTypes = RoomType::all();
        
        return view('backend.rooms.index', compact('rooms', 'roomTypes'));
    }

    public function create()
    {
        $roomTypes = RoomType::all();
        return view('backend.rooms.create', compact('roomTypes'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'room_type_id' => 'required|exists:room_types,room_type_id',
            'bathroom_type' => 'required|in:Private Bathroom,Shared Bathroom',
            'room_no' => 'required|string|max:10|unique:rooms,room_no',
            'floor' => 'nullable|string|max:10',
            'description' => 'nullable|string|max:500',
            'capacity' => 'nullable|string|max:10',
            'amenities' => 'nullable|string|max:500',
            'price_per_night' => 'nullable|numeric|min:0',
            'room_status' => 'required|in:Available,Occupied,Maintenance,Booked',
        ]);

        Room::create([
            'room_type_id' => $request->room_type_id,
            'bathroom_type' => $request->bathroom_type,
            'room_no' => $request->room_no,
            'floor' => $request->floor,
            'description' => $request->description,
            'capacity' => $request->capacity ?? '2',
            'amenities' => $request->amenities,
            'price_per_night' => $request->price_per_night,
            'room_status' => $request->room_status,
            'status' => $request->room_status === 'Booked' || $request->room_status === 'Occupied',
            'check_in_status' => $request->room_status === 'Occupied',
            'check_out_status' => false,
            'deleteStatus' => false,
        ]);

        return redirect()->route('rooms.index')->with('success', 'Room added successfully!');
    }

    public function show(Room $room)
    {
        $room->load(['roomType', 'bookings.customer']);
        return view('backend.rooms.show', compact('room'));
    }

    public function edit(Room $room)
    {
        $roomTypes = RoomType::all();
        return view('backend.rooms.edit', compact('room', 'roomTypes'));
    }

    public function update(Request $request, Room $room)
    {
        $request->validate([
            'room_type_id' => 'required|exists:room_types,room_type_id',
            'bathroom_type' => 'required|in:Private Bathroom,Shared Bathroom',
            'room_no' => 'required|string|max:10|unique:rooms,room_no,' . $room->room_id . ',room_id',
            'floor' => 'nullable|string|max:10',
            'description' => 'nullable|string|max:500',
            'capacity' => 'nullable|string|max:10',
            'amenities' => 'nullable|string|max:500',
            'price_per_night' => 'nullable|numeric|min:0',
            'room_status' => 'required|in:Available,Occupied,Maintenance,Booked',
        ]);

        $room->update([
            'room_type_id' => $request->room_type_id,
            'bathroom_type' => $request->bathroom_type,
            'room_no' => $request->room_no,
            'floor' => $request->floor,
            'description' => $request->description,
            'capacity' => $request->capacity ?? '2',
            'amenities' => $request->amenities,
            'price_per_night' => $request->price_per_night,
            'room_status' => $request->room_status,
            'status' => $request->room_status === 'Booked' || $request->room_status === 'Occupied',
            'check_in_status' => $request->room_status === 'Occupied',
        ]);

        return redirect()->route('rooms.index')->with('success', 'Room updated successfully!');
    }

    public function destroy(Room $room)
    {
        // Check if room has active bookings
        $activeBookings = $room->bookings()->where('check_out', '>=', now()->format('Y-m-d'))->count();
        
        if ($activeBookings > 0) {
            return back()->with('error', 'Cannot delete room. It has active bookings.');
        }

        $room->update(['deleteStatus' => true]);
        return redirect()->route('rooms.index')->with('success', 'Room deleted successfully!');
    }

    public function updateStatus(Request $request, Room $room)
    {
        $request->validate([
            'room_status' => 'required|in:Available,Occupied,Maintenance,Booked',
        ]);

        $room->update([
            'room_status' => $request->room_status,
            'status' => $request->room_status === 'Booked' || $request->room_status === 'Occupied',
            'check_in_status' => $request->room_status === 'Occupied',
        ]);

        return back()->with('success', 'Room status updated successfully!');
    }
}
