<?php

namespace App\Traits;

use App\Models\Reservation;
use Illuminate\Support\Facades\Auth;

trait RequiresHotelId
{
    protected static function bootRequiresHotelId()
    {
        static::creating(function ($model) {
            if (empty($model->hotel_id)) {
                // Try reservation context first
                if (!empty($model->reservation_id)) {
                    $reservation = Reservation::find($model->reservation_id);
                    if ($reservation && $reservation->hotel_id) {
                        $model->hotel_id = $reservation->hotel_id;
                    }
                }

                // Then try authenticated user context
                if (empty($model->hotel_id) && Auth::check()) {
                    $user = Auth::user();
                    if ($user->role === 'super_admin') {
                        $hotelId = request()->get('hotel_id');
                        $model->hotel_id = $hotelId ?: ($user->hotel_id ?? optional($user->hotel)->id);
                    } else {
                        $model->hotel_id = $user->hotel_id ?? optional($user->hotel)->id;
                    }
                }
            }

            if (empty($model->hotel_id)) {
                throw new \Exception('hotel_id is required for ' . get_class($model));
            }
        });
    }
}
