<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ThemeHelper;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

/**
 * Theme Studio — admin page for runtime customization of platform colors
 * across the frontend marketing site, admin panel, and user dashboard,
 * in both light and dark modes.
 *
 * The actual storage + CSS emission lives in App\Helpers\ThemeHelper;
 * this controller is a thin orchestrator that handles the form lifecycle.
 */
class ThemeStudioController extends Controller
{
    public function index(): View
    {
        return view('admin.theme-studio', [
            'config'   => ThemeHelper::getConfig(),
            'defaults' => ThemeHelper::getDefaults(),
        ]);
    }

    /**
     * Validation is loose-but-safe: each token must be a hex string.
     * The helper itself rejects unknown keys, so an attacker can't add
     * arbitrary CSS via field-name injection.
     */
    public function save(Request $request): RedirectResponse
    {
        $rules = [];
        foreach (['light', 'dark'] as $mode) {
            foreach (array_keys(ThemeHelper::getDefaults()['light']) as $token) {
                $rules["{$mode}.{$token}"] = ['required', 'regex:/^#([0-9a-f]{3}|[0-9a-f]{6})$/i'];
            }
        }

        $data = $request->validate($rules);

        ThemeHelper::save($data);

        return back()->with('success', 'Theme saved. Refresh the page to see changes site-wide.');
    }

    public function reset(): RedirectResponse
    {
        ThemeHelper::reset();
        return back()->with('success', 'Theme reset to defaults.');
    }
}
