<?php
namespace Core\System;

use Core\App\Models\ThemeSettings;
use Core\App\Models\ProductModel;

class ThemeManager
{
    protected static string $activeTheme = 'matjari';

    /**
     * Shared data between layout & views
     */
    protected static array $shared = [];

    /**
     * Runtime cache (🔥 PERFORMANCE)
     */
    protected static array $settingsCache = [];
    protected static bool $settingsLoaded = false;
    protected static ?string $cachedFavicon = null;
    protected static ?array $cachedActiveProduct = null;

    /**
     * Global settings table cache (loaded once per request)
     */
    protected static array $globalSettingsCache = [];
    protected static bool $globalSettingsLoaded = false;

    /* =====================================================
       THEME
    ===================================================== */

    public static function activeTheme(): string
    {
        return self::$activeTheme;
    }

    public static function loadActiveTheme(): void
    {
        $theme = 'matjari';

        if (is_dir(ROOT_PATH . '/themes/' . $theme)) {
            self::$activeTheme = $theme;
        }
    }

    public static function viewPath(string $view): string
    {
        return ROOT_PATH . "/themes/" . self::$activeTheme . "/templates/" . $view . ".php";
    }

    public static function render(string $template, array $data = []): void
    {
        self::loadActiveTheme();

        $contentFile = self::viewPath($template);

        if (!file_exists($contentFile)) {
            // Log error without exposing server file paths to the client
            error_log('ThemeManager: template not found — ' . $contentFile);
            http_response_code(404);
            echo 'Page not found.';
            return;
        }

        extract(self::$shared);
        extract($data);

        $layoutFile = ROOT_PATH . '/themes/' . self::$activeTheme . '/templates/layout.php';

        if (file_exists($layoutFile)) {
            include $layoutFile;
        } else {
            include $contentFile;
        }
    }

    /* =====================================================
       SHARED DATA
    ===================================================== */

    public static function share(string $key, $value): void
    {
        self::$shared[$key] = $value;
    }

    public static function getShared(string $key, $default = null)
    {
        return self::$shared[$key] ?? $default;
    }

    /* =====================================================
       SETTINGS (🔥 CACHED)
    ===================================================== */

    protected static function loadSettings(): void
    {
        if (self::$settingsLoaded) {
            return;
        }

        $model = new ThemeSettings();
        self::$settingsCache = $model->getAll(); // ⚠️ مرة واحدة فقط
        self::$settingsLoaded = true;
    }

    /**
     * Load ALL rows from global settings table once per request.
     */
    protected static function loadGlobalSettings(): void
    {
        if (self::$globalSettingsLoaded) {
            return;
        }

        self::$globalSettingsLoaded = true;

        try {
            $db   = \db();
            $stmt = $db->query("SELECT setting_key, setting_value FROM settings");
            $rows = $stmt->fetchAll(\PDO::FETCH_KEY_PAIR);
            self::$globalSettingsCache = is_array($rows) ? $rows : [];
        } catch (\Throwable $e) {
            self::$globalSettingsCache = [];
        }
    }

    public static function getSetting(string $key, $default = null)
    {
        /**
         * ✅ Priority 1: Global settings table (cached single batch load)
         */
        self::loadGlobalSettings();

        if (
            array_key_exists($key, self::$globalSettingsCache) &&
            self::$globalSettingsCache[$key] !== null &&
            self::$globalSettingsCache[$key] !== ''
        ) {
            return self::$globalSettingsCache[$key];
        }

        /**
         * ✅ Priority 2: Theme settings (cached)
         */
        self::loadSettings();
        return self::$settingsCache[$key] ?? $default;
    }

    public static function setSetting(string $key, $value)
    {
        $model = new ThemeSettings();
        $result = $model->set($key, $value);

        // Update local caches directly
        self::$settingsCache[$key] = $value;
        self::$globalSettingsCache[$key] = $value;

        return $result;
    }

    /* =====================================================
       URL NORMALIZER (CRITICAL)
    ===================================================== */

    protected static function normalizeAssetUrl($path): string
    {
        $path = trim((string)$path);

        if ($path === '') {
            return '';
        }

        // Absolute URL stays as is
        if (preg_match('#^https?://#i', $path)) {
            return $path;
        }

        // Root path stays as is
        if ($path[0] === '/') {
            return $path;
        }

        // Make root-relative
        return '/' . $path;
    }

    /* =====================================================
       FAVICON (🔥 CACHED)
    ===================================================== */

    public static function getFavicon(
        string $fallback = '/admin/assets/adminlte-assets/img/favicon.ico'
    ): string {
        if (self::$cachedFavicon !== null) {
            return self::$cachedFavicon;
        }

        try {
            $db = \db();

            $stmt = $db->prepare("
                SELECT setting_value
                FROM settings
                WHERE setting_key = 'favicon'
                LIMIT 1
            ");
            $stmt->execute();

            $favicon = $stmt->fetchColumn();

            if (!empty($favicon)) {
                self::$cachedFavicon = self::normalizeAssetUrl($favicon);
                return self::$cachedFavicon;
            }
        } catch (\Throwable $e) {
            // silent fallback
        }

        self::$cachedFavicon = $fallback;
        return self::$cachedFavicon;
    }

    /* =====================================================
       ACTIVE PRODUCT (🔥 CACHED)
    ===================================================== */

    public static function getActiveProduct(): ?array
    {
        if (self::$cachedActiveProduct !== null) {
            return self::$cachedActiveProduct;
        }

        self::loadSettings();

        $productId = self::$settingsCache['active_product_id'] ?? null;

        if (!$productId) {
            return null;
        }

        $productModel = new ProductModel();
        $product = $productModel->getById((int)$productId);

        self::$cachedActiveProduct = $product ?: null;

        return self::$cachedActiveProduct;
    }
}
