<?php

namespace AleshaCMS\Http\Controllers\Admin;

use AleshaCMS\Http\Controllers\Controller;
use AleshaCMS\CMS\Theme\ThemeManager;
use AleshaCMS\Models\CMS\Setting;
use Illuminate\Http\Request;

class ThemeController extends Controller
{
    public function __construct(protected ThemeManager $themes) {}

    public function index(Request $request)
    {
        $themes = $this->themes->getAvailableThemes();

        if ($request->wantsJson()) {
            return response()->json(['data' => $themes]);
        }

        return view('admin.themes.index', compact('themes'));
    }

    public function activate(Request $request)
    {
        $request->validate(['theme' => 'required|string']);
        $this->themes->setActive($request->theme);

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'message' => 'Theme activated.', 'active' => $request->theme]);
        }

        return back()->with('success', 'Theme activated.');
    }

    public function getColors(Request $request)
    {
        $request->validate(['theme' => 'required|string']);
        $colors = Setting::get('theme_colors.' . $request->theme, []);
        $config = $this->themes->getConfig($request->theme);
        return response()->json(['colors' => $colors, 'definitions' => $config['colors'] ?? []]);
    }

    public function saveColors(Request $request)
    {
        $request->validate(['theme' => 'required|string', 'colors' => 'required|array']);
        Setting::set('theme_colors.' . $request->theme, $request->colors, 'theme');
        return response()->json(['success' => true, 'message' => 'Colors saved.']);
    }
}
