<?php

namespace App\Http\Controllers;

use App\Models\BookingPriceAdjustment;
use App\Models\PriceModifier;
use App\Models\Room;
use App\Models\RoomCategory;
use Illuminate\Http\Request;
use Inertia\Inertia;

class PriceSettingController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $roomCategories = RoomCategory::orderBy('sort_order', 'asc')->with('rooms')->get();
        $priceModifires = PriceModifier::orderBy('priority', 'asc')->get();
        $priceAdjustment =  BookingPriceAdjustment::latest()->get();


        $roomCategories->transform(function ($item) {
            return [
                'id' => $item->id,
                'short_name' => $item->short_name,
                'base_price' => $item->base_price,
                'rooms' => $item->rooms->map(fn($room) => [
                    'id' => $room->id,
                    'room_number' => $room->room_number,
                    'price_override' => $room->price_override,
                ])
            ];
        });

        $priceModifires->transform(function ($item) {
            return [
                'id' => $item->id,
                'name' => $item->name,
                'calculation' => $item->calculation,
                'operation' => $item->operation,
                'value' => $item->value,
                'type' => $item->type
            ];
        });

        return Inertia::render('dashboard/price-settings/index', [
            'roomCategories' => $roomCategories,
            'priceModifires' => $priceModifires,
            'priceAdjustment' => $priceAdjustment
        ]);
    }

    public function updateRoom(Request $request, $id)
    {
        $request->validate([
            'price' => ['nullable', 'numeric']
        ]);

        $room = Room::findOrFail($id);
        $room->price_override = $request->price;
        $room->save();

        return back()->with('success', 'Room price updated');
    }

    public function updateCategory(Request $request, $id)
    {
        $request->validate([
            'price' => ['required', 'numeric']
        ]);

        $category = RoomCategory::findOrFail($id);
        $category->base_price = $request->price;
        $category->save();

        return back()->with('success', 'Category price updated');
    }
}
