<?php

namespace App\Http\Controllers\Admin\Settings;

use App\Http\Controllers\Controller;
use App\Traits\RefreshesSettingsCache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class AppSettingsController extends Controller
{
    use RefreshesSettingsCache;

    private array $menuSettings = [
        'menu_voucher_enabled' => true,
        'menu_shop_enabled' => true,
        'menu_topspender_enabled' => true,
        'menu_ingame_enabled' => true,
        'menu_streamer_enabled' => true,
        'menu_event_enabled' => true,
        'menu_topup_enabled' => true,
        'streamer_registration_open' => true,
    ];

    public function index()
    {
        $settings = [];

        foreach ($this->menuSettings as $key => $default) {
            $setting = DB::table('settings')->where('key', $key)->first();

            if (! $setting) {
                DB::table('settings')->insert([
                    'key' => $key,
                    'value' => $default ? '1' : '0',
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
                $settings[$key] = $default;
            } else {
                $settings[$key] = $setting->value === '1';
            }
        }

        return Inertia::render('admin/settings/apps/index', [
            'menuVoucherEnabled' => $settings['menu_voucher_enabled'],
            'menuShopEnabled' => $settings['menu_shop_enabled'],
            'menuTopspenderEnabled' => $settings['menu_topspender_enabled'],
            'menuIngameEnabled' => $settings['menu_ingame_enabled'],
            'menuStreamerEnabled' => $settings['menu_streamer_enabled'],
            'menuEventEnabled' => $settings['menu_event_enabled'],
            'menuTopupEnabled' => $settings['menu_topup_enabled'],
            'streamerRegistrationOpen' => $settings['streamer_registration_open'],
        ]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'menu_voucher_enabled' => 'required|boolean',
            'menu_shop_enabled' => 'required|boolean',
            'menu_topspender_enabled' => 'required|boolean',
            'menu_ingame_enabled' => 'required|boolean',
            'menu_streamer_enabled' => 'required|boolean',
            'menu_event_enabled' => 'required|boolean',
            'menu_topup_enabled' => 'required|boolean',
            'streamer_registration_open' => 'required|boolean',
        ]);

        foreach ($this->menuSettings as $key => $default) {
            $value = $request->input($key) ? '1' : '0';

            DB::table('settings')->updateOrInsert(
                ['key' => $key],
                ['value' => $value, 'updated_at' => now()]
            );
        }

        $this->refreshSettingsCache();

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