<?php
declare(strict_types=1);

if (!function_exists('cms_default_config')) {
    function cms_default_config(): array
    {
        return [
            'site_title' => 'Satta4uMatka',
            'active_theme' => 'default',
            'info_chart_base_slug' => 'info-chart',
            'active_plugins' => [],
            'homepage_blocks' => ['header', 'live', 'final', 'keywords', 'results', 'notice', 'links', 'free', 'weekly', 'charts', 'static'],
            'db_host' => 'localhost',
            'db_name' => '',
            'db_user' => 'root',
            'db_pass' => '',
            'admin' => [
                'username' => 'admin',
                'password_hash' => '',
            ],
        ];
    }
}

if (!function_exists('cms_config_path')) {
    function cms_config_path(?string $rootPath = null): string
    {
        $basePath = $rootPath ?: (defined('CMS_ROOT') ? CMS_ROOT : dirname(__DIR__));
        return rtrim($basePath, '/\\') . '/core/config.json';
    }
}

if (!function_exists('cms_available_themes')) {
    function cms_available_themes(?string $rootPath = null): array
    {
        $basePath = $rootPath ?: (defined('CMS_ROOT') ? CMS_ROOT : dirname(__DIR__));
        $themesPath = rtrim($basePath, '/\\') . '/content/themes';

        if (!is_dir($themesPath)) {
            return [];
        }

        $themeDirs = glob($themesPath . '/*', GLOB_ONLYDIR);
        if ($themeDirs === false) {
            return [];
        }

        $themes = [];
        foreach ($themeDirs as $themeDir) {
            $themes[] = basename($themeDir);
        }

        sort($themes);

        return $themes;
    }
}

if (!function_exists('cms_parse_theme_metadata')) {
    function cms_parse_theme_metadata(string $themeSlug, ?string $rootPath = null): array
    {
        $basePath = $rootPath ?: (defined('CMS_ROOT') ? CMS_ROOT : dirname(__DIR__));
        $themeDir = rtrim($basePath, '/\\') . '/content/themes/' . $themeSlug;
        $styleFile = $themeDir . '/style.css';

        $metadata = [
            'slug' => $themeSlug,
            'name' => $themeSlug,
            'version' => '1.0.0',
            'author' => '',
            'description' => '',
            'screenshot' => is_file($themeDir . '/screenshot.png') ? '/content/themes/' . rawurlencode($themeSlug) . '/screenshot.png' : '',
            'directory' => $themeDir,
        ];

        if (!is_file($styleFile)) {
            return $metadata;
        }

        $contents = (string) file_get_contents($styleFile);
        $map = [
            'Theme Name' => 'name',
            'Version' => 'version',
            'Author' => 'author',
            'Description' => 'description',
        ];

        foreach ($map as $header => $key) {
            if (preg_match('/^\s*' . preg_quote($header, '/') . '\s*:\s*(.+)$/mi', $contents, $matches)) {
                $metadata[$key] = trim((string) $matches[1]);
            }
        }

        if ((string) $metadata['name'] === '') {
            $metadata['name'] = $themeSlug;
        }

        return $metadata;
    }
}

if (!function_exists('cms_themes_registry')) {
    function cms_themes_registry(?string $rootPath = null): array
    {
        $themes = cms_available_themes($rootPath);
        $registry = [];

        foreach ($themes as $themeSlug) {
            $registry[$themeSlug] = cms_parse_theme_metadata($themeSlug, $rootPath);
        }

        return $registry;
    }
}

if (!function_exists('cms_normalize_config')) {
    function cms_normalize_config(array $config, ?string $rootPath = null): array
    {
        $defaults = cms_default_config();
        $config = array_replace_recursive($defaults, $config);

        $config['site_title'] = trim((string) ($config['site_title'] ?? $defaults['site_title']));
        if ($config['site_title'] === '') {
            $config['site_title'] = $defaults['site_title'];
        }

        $availableThemes = cms_available_themes($rootPath);
        $activeTheme = trim((string) ($config['active_theme'] ?? $defaults['active_theme']));
        if ($activeTheme === '' || (!empty($availableThemes) && !in_array($activeTheme, $availableThemes, true))) {
            $activeTheme = in_array($defaults['active_theme'], $availableThemes, true) ? $defaults['active_theme'] : ($availableThemes[0] ?? $defaults['active_theme']);
        }
        $config['active_theme'] = $activeTheme;

        $infoChartBaseSlug = strtolower(trim((string) ($config['info_chart_base_slug'] ?? $defaults['info_chart_base_slug'])));
        $infoChartBaseSlug = preg_replace('/[^a-z0-9\-]/', '-', $infoChartBaseSlug) ?: $defaults['info_chart_base_slug'];
        $infoChartBaseSlug = trim($infoChartBaseSlug, '-');
        if ($infoChartBaseSlug === '') {
            $infoChartBaseSlug = $defaults['info_chart_base_slug'];
        }
        $config['info_chart_base_slug'] = $infoChartBaseSlug;

        $discoveredPlugins = function_exists('cms_discover_plugin_slugs') ? cms_discover_plugin_slugs($rootPath) : [];
        $activePlugins = $config['active_plugins'] ?? [];
        if (!is_array($activePlugins)) {
            $activePlugins = [];
        }

        $activePlugins = array_values(array_unique(array_filter(array_map(static function ($plugin): string {
            return strtolower(trim((string) $plugin));
        }, $activePlugins))));

        if ($discoveredPlugins !== []) {
            $activePlugins = array_values(array_filter($activePlugins, static function (string $plugin) use ($discoveredPlugins): bool {
                return in_array($plugin, $discoveredPlugins, true);
            }));
        }

        $config['active_plugins'] = $activePlugins;

        $homepageBlocks = $config['homepage_blocks'] ?? $defaults['homepage_blocks'];
        if (!is_array($homepageBlocks)) {
            $homepageBlocks = $defaults['homepage_blocks'];
        }
        $homepageBlocks = array_values(array_unique(array_filter(array_map(static function ($block): string {
            return strtolower(trim((string) $block));
        }, $homepageBlocks))));
        if ($homepageBlocks === []) {
            $homepageBlocks = $defaults['homepage_blocks'];
        }
        $config['homepage_blocks'] = $homepageBlocks;

        $config['db_host'] = trim((string) ($config['db_host'] ?? $defaults['db_host']));
        $config['db_name'] = trim((string) ($config['db_name'] ?? $defaults['db_name']));
        $config['db_user'] = trim((string) ($config['db_user'] ?? $defaults['db_user']));
        $config['db_pass'] = (string) ($config['db_pass'] ?? $defaults['db_pass']);

        $config['admin']['username'] = trim((string) ($config['admin']['username'] ?? $defaults['admin']['username']));
        if ($config['admin']['username'] === '') {
            $config['admin']['username'] = $defaults['admin']['username'];
        }

        $passwordHash = (string) ($config['admin']['password_hash'] ?? '');
        if ($passwordHash === '') {
            $passwordHash = password_hash('admin123', PASSWORD_DEFAULT);
        }
        $config['admin']['password_hash'] = $passwordHash;

        return $config;
    }
}

if (!function_exists('cms_save_config')) {
    function cms_save_config(array $config, ?string $rootPath = null): bool
    {
        $configPath = cms_config_path($rootPath);
        $configDir = dirname($configPath);

        if (!is_dir($configDir)) {
            @mkdir($configDir, 0775, true);
        }

        $normalizedConfig = cms_normalize_config($config, $rootPath);
        $json = json_encode($normalizedConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

        if ($json === false) {
            return false;
        }

        return file_put_contents($configPath, $json, LOCK_EX) !== false;
    }
}

if (!function_exists('cms_load_config')) {
    function cms_load_config(?string $rootPath = null): array
    {
        $configPath = cms_config_path($rootPath);
        $config = cms_default_config();

        if (is_file($configPath)) {
            $decoded = json_decode((string) file_get_contents($configPath), true);
            if (is_array($decoded)) {
                $config = array_replace_recursive($config, $decoded);
            }
        }

        $normalized = cms_normalize_config($config, $rootPath);

        if (!is_file($configPath)) {
            cms_save_config($normalized, $rootPath);
        }

        return $normalized;
    }
}

if (!function_exists('cms_get_config')) {
    function cms_get_config(?string $rootPath = null): array
    {
        return cms_load_config($rootPath);
    }
}
