<?php

namespace App\Http\Controllers;

use App\Models\RoomAvailability;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Inertia\Inertia;

class SettingController extends Controller
{
    public function index()
    {

        // Get all availabilities with room info and creator
        $availabilities = RoomAvailability::with(['room', 'creator'])
            ->orderBy('start_date', 'desc')
            ->get();


        $settings = Setting::orderBy('group')->orderBy('key')->get();
        return Inertia::render('dashboard/settings/index', ['settings' => $settings, 'availabilities' => $availabilities]);
    }

    public function update(Request $request)
    {
        foreach ($request->all() as $key => $value) {
            $setting = Setting::where('key', $key)->first();
            if ($setting) {
                // Handle JSON and boolean types
                if ($setting->type === 'json' && is_array($value)) {
                    $setting->value = json_encode($value);
                } elseif ($setting->type === 'boolean') {
                    $setting->value = $value ? 1 : 0;
                } else {
                    $setting->value = $value;
                }

                $setting->save();
                Cache::forget($key); // Clear cache
            }
        }

        return back()->with('success', 'Settings updated successfully.');
    }
}
