<?php

namespace App\Controllers\View;

use CodeIgniter\Controller;
use App\Models\PreferencesModel;

class UiController extends Controller
{
    public function style()
    {
        $styleCfg = config('Style');
        $accent = (string) $this->request->getGet('accent');
        $menu   = (string) $this->request->getGet('menu');
        $menuBg = (string) $this->request->getGet('menu_bg');
        $menuTx = (string) $this->request->getGet('menu_text');
        $menuMd = (string) $this->request->getGet('menu_mode'); // optional: 'light'|'dark'|'auto'

        $updates = [];
        if ($accent && isset(($styleCfg->stylePalettes ?? [])[$accent])) {
            session()->set('style_color', $accent);
            $updates['style_color'] = $accent;
        }
        if ($menu && isset(($styleCfg->menuPalettes ?? [])[$menu])) {
            session()->set('menu_color', $menu);
            $updates['menu_color'] = $menu;
            $updates['menu_custom_bg'] = null;
            $updates['menu_custom_text'] = null;
            $updates['menu_custom_mode'] = null;
        } elseif (strtolower($menu) === 'custom' || ($menuBg !== '' || $menuTx !== '')) {
            // Allow custom menu colors via GET: menu=custom&menu_bg=#hex&menu_text=#hex&menu_mode=dark|light|auto
            $bg = $this->normalizeHex($menuBg);
            $tx = $this->normalizeHex($menuTx);
            if ($bg === '' && $tx === '') {
                // no valid values; ignore
            } else {
                if ($bg === '') $bg = '#0f172a';
                if ($tx === '') $tx = '#ffffff';
                $mode = in_array($menuMd, ['light','dark','auto'], true) ? $menuMd : 'auto';
                session()->set('menu_color', 'custom');
                session()->set('menu_custom_bg', $bg);
                session()->set('menu_custom_text', $tx);
                session()->set('menu_custom_mode', $mode);
                $updates['menu_color'] = 'custom';
                $updates['menu_custom_bg'] = $bg;
                $updates['menu_custom_text'] = $tx;
                $updates['menu_custom_mode'] = $mode;
            }
        }

        $userId = (int) session()->get('user_id');
        if ($userId && !empty($updates)) {
            $prefsModel = new PreferencesModel();
            $existing = $prefsModel->where('user_id', $userId)->first();
            if ($existing) {
                $prefsModel->update($existing['id'], $updates);
            } else {
                $updates['user_id'] = $userId;
                $prefsModel->insert($updates);
            }
        }

        // Redirect back to referrer or home
        $back = (string) $this->request->getGet('back');
        if ($back) return redirect()->to($back);
        $ref = $this->request->getServer('HTTP_REFERER');
        if ($ref) return redirect()->to($ref);
        return redirect()->to(site_url('/'));
    }

    /**
     * Normalize a CSS hex color (#RGB or #RRGGBB). Returns '' on failure.
     */
    private function normalizeHex(string $hex): string
    {
        $h = trim($hex);
        if ($h === '') return '';
        if ($h[0] !== '#') $h = '#' . $h;
        if (preg_match('/^#([0-9a-fA-F]{3})$/', $h, $m)) {
            // Expand #RGB to #RRGGBB
            $r = $m[1][0]; $g = $m[1][1]; $b = $m[1][2];
            return '#' . $r . $r . $g . $g . $b . $b;
        }
        if (preg_match('/^#([0-9a-fA-F]{6})$/', $h)) return strtoupper($h);
        return '';
    }

    /**
     * Choose navbar mode based on background luminance: 'dark' for dark BG, else 'light'.
     */
    private function autoModeForBg(string $hexBg): string
    {
        $hex = ltrim($hexBg, '#');
        if (strlen($hex) !== 6) return 'dark';
        $r = hexdec(substr($hex,0,2));
        $g = hexdec(substr($hex,2,2));
        $b = hexdec(substr($hex,4,2));
        // Relative luminance approximation
        $lum = (0.2126*$r + 0.7152*$g + 0.0722*$b) / 255.0;
        return ($lum < 0.5) ? 'dark' : 'light';
    }
}
