<?php

use Carbon\Carbon;
use App\Models\Room;
use Illuminate\Support\Facades\DB;

if (!function_exists('calculateRoomPrice')) {

    function calculateRoomPrice($roomId, $checkIn, $checkOut)
    {
        $room = Room::findOrFail($roomId);
        $total = 0;

        $start = Carbon::parse($checkIn);
        $end   = Carbon::parse($checkOut);

        while ($start < $end) {

            // 1️⃣ Exact date price
            $datePrice = DB::table('room_date_prices')
                ->where('room_id', $roomId)
                ->where('date', $start->toDateString())
                ->value('price');

            if ($datePrice) {
                $price = $datePrice;
            } else {

                // 2️⃣ Rule based price
                $rule = DB::table('room_price_rules')
                    ->where('room_id', $roomId)
                    ->whereDate('start_date', '<=', $start)
                    ->whereDate('end_date', '>=', $start)
                    ->first();

                if ($rule) {
                    $dayColumn = strtolower($start->format('l')) . '_price';
                    $price = $rule->$dayColumn ?? $room->price_per_night;
                } else {
                    // 3️⃣ Default room price
                    $price = $room->price_per_night;
                }
            }

            $total += $price;
            $start->addDay();
        }

        return $total;
    }
}
