<?php

namespace Core\App\Controllers;

use Core\App\Models\ThemeSettings;
use Core\App\Services\ThemeAssetService;
use Core\System\Request;
use Core\System\Response;

class ThemeCustomizerController
{
    protected ThemeSettings $settings;

    public function __construct()
    {
        $this->settings = new ThemeSettings();
    }

    public function index()
    {
        $current = $this->settings->getAll();

        ThemeAssetService::ensureFrontendCss($current);

        view_admin('theme_customizer/index', [
            'settings' => $current,
            'defaults' => ThemeAssetService::frontendDefaults(),
            'fontMap'  => ThemeAssetService::fontMap(),
        ]);
    }

    public function save()
    {
        $data = Request::input();

        if (isset($data['logo'])) {
            $this->settings->set('logo', $data['logo']);
        }

        if (isset($data['colors'])) {
            $this->settings->set('colors', $data['colors']);
        }

        if (isset($data['fonts'])) {
            $this->settings->set('fonts', $data['fonts']);
        }

        if (isset($data['custom_css'])) {
            $this->settings->set('custom_css', $data['custom_css']);
        }

        /* ===============================
           Admin Panel Theme (SAFE ADD)
        =============================== */
        $this->settings->set('admin_theme', [
            'fonts'  => $data['admin_fonts']  ?? [],
            'colors' => $data['admin_colors'] ?? [],
            'mode'   => $data['admin_mode']   ?? 'light',
        ]);
        /* =============================== */

        ThemeAssetService::writeFrontendCss($this->settings->getAll());

        return Response::redirect('/admin/appearance/customize?success=1');
    }
}
