<?php

namespace App\Http\Controllers;

use App\Models\RoomType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Concerns\ResolvesTenantHotel;

class RoomTypeController extends Controller
{
    use ResolvesTenantHotel;

    protected function getHotelId()
    {
        return $this->tenantHotelIdOrAbort();
    }

    /**
     * Display a listing of the room types.
     */
    public function index()
    {
        $hotelId = $this->getHotelId();
        $roomTypes = RoomType::where('hotel_id', $hotelId)->withCount('rooms')->get();
        return response()->json($roomTypes);
    }

    /**
     * Store a newly created room type.
     */
 public function store(Request $request)
{
    // Debug: See what data is being received
    \Log::info('Room Type Store Request:', $request->all());
    
    // Also dump and die for immediate feedback (remove after testing)
    // dd($request->all());
    
    $hotelId = $this->getHotelId();

    if (!$hotelId) {
        return redirect()->route('login')->with('error', 'Hotel ID not found. Please login again.');
    }

    $validator = Validator::make($request->all(), [
        'name' => [
            'required', 'string', 'max:255',
            Rule::unique('room_types', 'name')->where(fn ($q) => $q->where('hotel_id', $hotelId)),
        ],
        'code' => [
            'nullable', 'string', 'max:50',
            Rule::unique('room_types', 'code')->where(fn ($q) => $q->where('hotel_id', $hotelId)),
        ],
        'default_capacity' => 'required|integer|min:1|max:10',
        'max_capacity' => 'nullable|integer|min:1|max:20',
        'description' => 'nullable|string',
        'is_active' => 'sometimes|boolean',
        'has_breakfast' => 'sometimes|boolean'
    ]);

    if ($validator->fails()) {
        \Log::error('Validation failed:', $validator->errors()->toArray());
        return redirect()->back()
            ->withErrors($validator)
            ->withInput();
    }

    try {
        $data = [
            'hotel_id' => $hotelId,
            'name' => $request->name,
            'code' => $request->code,
            'description' => $request->description,
            'default_capacity' => $request->default_capacity,
            'max_capacity' => $request->max_capacity,
            'is_active' => $request->has('is_active') ? 1 : 0,
            'has_breakfast' => $request->has('has_breakfast') ? 1 : 0,
        ];
        
        \Log::info('Attempting to save:', $data);
        
        $roomType = RoomType::create($data);
        
        \Log::info('Saved successfully:', ['id' => $roomType->id]);
        
        return redirect()->route('rooms.index')
            ->with('success', 'Room type "' . $roomType->name . '" created successfully!');
            
    } catch (\Exception $e) {
        \Log::error('Error creating room type: ' . $e->getMessage());
        \Log::error('Stack trace: ' . $e->getTraceAsString());
        
        return redirect()->back()
            ->with('error', 'Error creating room type: ' . $e->getMessage())
            ->withInput();
    }
}
    /**
     * Display the specified room type.
     */
    public function show($id)
    {
        $hotelId = $this->getHotelId();
        $roomType = RoomType::where('hotel_id', $hotelId)->with('rooms')->findOrFail($id);
        return response()->json($roomType);
    }

    /**
     * Show the form for editing the specified room type.
     */
    public function edit($id)
    {
        $hotelId = $this->getHotelId();
        $roomType = RoomType::where('hotel_id', $hotelId)->findOrFail($id);
        return response()->json($roomType);
    }

    /**
     * Update the specified room type.
     */
    public function update(Request $request, $id)
    {
        $hotelId = $this->getHotelId();
        $roomType = RoomType::where('hotel_id', $hotelId)->findOrFail($id);

        $validator = Validator::make($request->all(), [
            'name' => [
                'required', 'string', 'max:255',
                Rule::unique('room_types', 'name')
                    ->where(fn ($q) => $q->where('hotel_id', $hotelId))
                    ->ignore($id),
            ],
            'code' => [
                'nullable', 'string', 'max:50',
                Rule::unique('room_types', 'code')
                    ->where(fn ($q) => $q->where('hotel_id', $hotelId))
                    ->ignore($id),
            ],
            'default_capacity' => 'required|integer|min:1|max:10',
            'description' => 'nullable|string',
            'is_active' => 'sometimes|boolean'
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $roomType->update([
            'name' => $request->name,
            'code' => $request->code,
            'default_capacity' => $request->default_capacity,
            'description' => $request->description,
            'is_active' => $request->has('is_active')
        ]);

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

    /**
     * Remove the specified room type.
     */
    public function destroy($id)
    {
        $hotelId = $this->getHotelId();
        $roomType = RoomType::where('hotel_id', $hotelId)->findOrFail($id);
        
        // Check if there are rooms using this type
        if ($roomType->rooms()->count() > 0) {
            return redirect()->back()
                ->with('error', 'Cannot delete room type that has rooms assigned.');
        }
        
        $roomType->delete();

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

    /**
     * Get room types for dropdown.
     */
    public function getForDropdown()
    {
        $hotelId = $this->getHotelId();
        $roomTypes = RoomType::where('hotel_id', $hotelId)
            ->active()
            ->orderBy('name')
            ->get(['id', 'name', 'code', 'default_capacity']);
        
        return response()->json($roomTypes);
    }
    
}