<?php
declare(strict_types=1);

if (!function_exists('theme_path')) {
    function theme_path(string $path = ''): string
    {
        $basePath = defined('CMS_THEME_DIR') ? CMS_THEME_DIR : __DIR__;
        return $path === '' ? $basePath : $basePath . '/' . ltrim($path, '/');
    }
}

if (!function_exists('theme_url')) {
    function theme_url(string $path = ''): string
    {
        $theme = defined('CMS_THEME') ? CMS_THEME : basename(__DIR__);
        $baseUrl = '/content/themes/' . rawurlencode($theme);
        return $path === '' ? $baseUrl : $baseUrl . '/' . ltrim($path, '/');
    }
}

if (!function_exists('theme_file')) {
    function theme_file(string $path): string
    {
        return theme_path($path);
    }
}

if (!function_exists('theme_locate_file')) {
    function theme_locate_file(array $candidates): string
    {
        foreach ($candidates as $candidate) {
            $normalized = str_replace('\\', '/', ltrim($candidate, '/'));
            if ($normalized === '') {
                continue;
            }

            $file = theme_file($normalized);
            if (is_file($file)) {
                return $file;
            }
        }

        return '';
    }
}

if (!function_exists('theme_locate_template')) {
    function theme_locate_template(string $type, ?string $name = null): string
    {
        $type = trim($type, '/');
        $name = $name !== null ? trim($name, '/ ') : null;

        $candidates = [];
        if ($name !== null && $name !== '') {
            $candidates[] = $type . '-' . $name . '.php';
            $candidates[] = 'templates/' . $type . '-' . $name . '.php';
        }

        $candidates[] = $type . '.php';
        $candidates[] = 'templates/' . $type . '.php';

        return theme_locate_file($candidates);
    }
}

if (!function_exists('load_template')) {
    function load_template(string $templateFile, array $vars = []): void
    {
        if (!is_file($templateFile)) {
            return;
        }

        $db = $GLOBALS['db'] ?? null;
        $db1 = $GLOBALS['db1'] ?? null;
        extract($vars, EXTR_SKIP);
        require $templateFile;
    }
}

if (!function_exists('get_header')) {
    function get_header(?string $name = null, array $vars = []): void
    {
        $file = theme_locate_template('header', $name);
        if ($file === '') {
            $file = theme_file('header.php');
        }
        load_template($file, array_merge(theme_context(), $vars));
    }
}

if (!function_exists('get_footer')) {
    function get_footer(?string $name = null, array $vars = []): void
    {
        $file = theme_locate_template('footer', $name);
        if ($file === '') {
            $file = theme_file('footer.php');
        }
        load_template($file, array_merge(theme_context(), $vars));
    }
}

if (!function_exists('get_sidebar')) {
    function get_sidebar(?string $name = null, array $vars = []): void
    {
        $file = theme_locate_template('sidebar', $name);
        if ($file === '') {
            $file = theme_file('sidebar.php');
        }
        if ($file !== '') {
            load_template($file, array_merge(theme_context(), $vars));
        }
    }
}

if (!function_exists('get_template_part')) {
    function get_template_part(string $slug, ?string $name = null, array $vars = []): void
    {
        $slug = trim($slug, '/');
        $name = $name !== null ? trim($name, '/ ') : null;
        $candidates = [];

        if ($name !== null && $name !== '') {
            $candidates[] = 'template-parts/' . $slug . '-' . $name . '.php';
            $candidates[] = $slug . '-' . $name . '.php';
        }

        $candidates[] = 'template-parts/' . $slug . '.php';
        $candidates[] = $slug . '.php';

        $file = theme_locate_file($candidates);
        if ($file !== '') {
            load_template($file, array_merge(theme_context(), $vars));
        }
    }
}

if (!function_exists('theme_page_file')) {
    function theme_page_file(string $page): string
    {
        $page = strtolower(trim($page));
        $page = preg_replace('/[^a-z0-9\-]/', '', $page) ?: 'home';

        return theme_file('pages/' . $page . '.php');
    }
}

if (!function_exists('theme_page_exists')) {
    function theme_page_exists(string $page): bool
    {
        return is_file(theme_page_file($page));
    }
}

if (!function_exists('theme_style_metadata')) {
    function theme_style_metadata(): array
    {
        static $metadata = null;

        if (is_array($metadata)) {
            return $metadata;
        }

        if (function_exists('cms_parse_theme_metadata')) {
            $metadata = cms_parse_theme_metadata(defined('CMS_THEME') ? CMS_THEME : basename(__DIR__), defined('CMS_ROOT') ? CMS_ROOT : dirname(__DIR__, 3));
        } else {
            $metadata = [
                'slug' => defined('CMS_THEME') ? CMS_THEME : basename(__DIR__),
                'name' => defined('CMS_THEME') ? CMS_THEME : basename(__DIR__),
                'version' => '1.0.0',
                'author' => '',
                'description' => '',
            ];
        }

        return $metadata;
    }
}

if (!function_exists('theme_context')) {
    function theme_context(): array
    {
        $context = $GLOBALS['theme_context'] ?? [];
        return is_array($context) ? $context : [];
    }
}

if (!function_exists('theme_data')) {
    function theme_data(?string $key = null, mixed $default = null): mixed
    {
        $context = theme_context();
        if ($key === null) {
            return $context;
        }

        return $context[$key] ?? $default;
    }
}

if (!function_exists('theme_site_url')) {
    function theme_site_url(): string
    {
        $configured = function_exists('cms_db_setting') ? trim((string) cms_db_setting('site_url', '')) : '';
        if ($configured !== '') {
            return rtrim($configured, '/');
        }

        $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || ((int) ($_SERVER['SERVER_PORT'] ?? 0) === 443)
            || ((int) ($_SERVER['SERVER_PORT'] ?? 0) === 446);
        $scheme = $https ? 'https' : 'http';
        $host = trim((string) ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost'));

        return $scheme . '://' . $host;
    }
}

if (!function_exists('theme_request_path')) {
    function theme_request_path(): string
    {
        $requestUri = (string) (theme_data('request_uri', $_SERVER['REQUEST_URI'] ?? '/'));
        $path = (string) (parse_url($requestUri, PHP_URL_PATH) ?: '/');

        return $path === '' ? '/' : $path;
    }
}

if (!function_exists('theme_canonical_url')) {
    function theme_canonical_url(): string
    {
        $baseUrl = theme_site_url();
        $path = theme_request_path();
        $pageSlug = strtolower(trim((string) theme_data('page', 'home')));

        if ($pageSlug === 'home' || $path === '/' || $path === '') {
            return $baseUrl . '/';
        }

        if ($pageSlug !== '' && $pageSlug !== '404' && preg_match('#^/pages/#i', $path)) {
            return $baseUrl . '/' . trim($pageSlug, '/') . '/';
        }

        return $baseUrl . '/' . trim($path, '/') . '/';
    }
}

if (!function_exists('theme_schema_markup')) {
    function theme_normalize_schema_node(array $node, string $defaultType, string $canonicalUrl, string $title, string $description): array
    {
        if (!isset($node['@context']) || trim((string) $node['@context']) === '') {
            $node['@context'] = 'https://schema.org';
        }

        if (!isset($node['@type']) || trim((string) $node['@type']) === '') {
            $node['@type'] = $defaultType;
        }

        if (!isset($node['url']) || trim((string) $node['url']) === '') {
            $node['url'] = $canonicalUrl;
        }

        if (!isset($node['name']) || trim((string) $node['name']) === '') {
            $node['name'] = $title;
        }

        if (!isset($node['description']) || trim((string) $node['description']) === '') {
            $node['description'] = $description;
        }

        return $node;
    }
}

if (!function_exists('theme_default_home_schema')) {
    function theme_default_home_schema(string $canonicalUrl, string $title, string $description): array
    {
        return [
            '@context' => 'https://schema.org',
            '@graph' => [
                [
                    '@type' => 'WebSite',
                    '@id' => $canonicalUrl . '#website',
                    'url' => $canonicalUrl,
                    'name' => $title,
                    'description' => $description,
                    'inLanguage' => 'en',
                ],
                [
                    '@type' => 'Organization',
                    '@id' => $canonicalUrl . '#organization',
                    'url' => $canonicalUrl,
                    'name' => $title,
                    'description' => $description,
                ],
            ],
        ];
    }
}

if (!function_exists('theme_schema_markup')) {
    function theme_schema_markup(): string
    {
        $customSchema = trim((string) theme_data('schema_json', ''));
        $canonicalUrl = theme_canonical_url();
        $title = trim((string) theme_data('meta_title', ''));
        if ($title === '') {
            $title = trim((string) theme_data('title', ''));
        }
        if ($title === '') {
            $title = defined('CMS_SITE_TITLE') ? CMS_SITE_TITLE : 'Website';
        }

        $description = trim((string) theme_data('meta_description', ''));
        if ($description === '') {
            $description = 'Get todays Satta Matka live updates and Kalyan Matka results.';
        }

        if ($customSchema !== '') {
            $decoded = json_decode($customSchema, true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                if (isset($decoded['@graph']) && is_array($decoded['@graph'])) {
                    foreach ($decoded['@graph'] as $index => $node) {
                        if (is_array($node)) {
                            $decoded['@graph'][$index] = theme_normalize_schema_node(
                                $node,
                                theme_data('template_type') === 'home' ? 'WebSite' : 'WebPage',
                                $canonicalUrl,
                                $title,
                                $description
                            );
                        }
                    }
                    if (!isset($decoded['@context']) || trim((string) $decoded['@context']) === '') {
                        $decoded['@context'] = 'https://schema.org';
                    }
                } else {
                    $decoded = theme_normalize_schema_node(
                        $decoded,
                        theme_data('template_type') === 'home' ? 'WebSite' : 'WebPage',
                        $canonicalUrl,
                        $title,
                        $description
                    );
                }

                return (string) json_encode($decoded, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
            }
        }

        if (theme_data('template_type') === 'home') {
            return (string) json_encode(
                theme_default_home_schema($canonicalUrl, $title, $description),
                JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT
            );
        }

        return (string) json_encode([
            '@context' => 'https://schema.org',
            '@type' => 'WebPage',
            'url' => $canonicalUrl,
            'name' => $title,
            'description' => $description,
            'inLanguage' => 'en',
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }
}

if (!function_exists('theme_capture_hook_output')) {
    function theme_capture_hook_output(string $hook, string $page, array $data): string
    {
        if (!function_exists('do_action')) {
            return '';
        }

        ob_start();
        do_action($hook, $page, $data);
        return (string) ob_get_clean();
    }
}

if (!function_exists('theme_before_render_output')) {
    function theme_before_render_output(): string
    {
        return (string) (($GLOBALS['theme_render_hooks']['before_render'] ?? ''));
    }
}

if (!function_exists('theme_after_render_output')) {
    function theme_after_render_output(): string
    {
        return (string) (($GLOBALS['theme_render_hooks']['after_render'] ?? ''));
    }
}

if (!function_exists('enqueue_style')) {
    function enqueue_style(string $handle, string $src, array $deps = [], ?string $version = null, string $media = 'all'): void
    {
        $GLOBALS['theme_assets']['styles'][$handle] = [
            'handle' => $handle,
            'src' => $src,
            'deps' => $deps,
            'version' => $version,
            'media' => $media,
        ];
    }
}

if (!function_exists('enqueue_script')) {
    function enqueue_script(string $handle, string $src, array $deps = [], ?string $version = null, bool $inFooter = true): void
    {
        $GLOBALS['theme_assets']['scripts'][$handle] = [
            'handle' => $handle,
            'src' => $src,
            'deps' => $deps,
            'version' => $version,
            'in_footer' => $inFooter,
        ];
    }
}

if (!function_exists('theme_render_styles')) {
    function theme_render_styles(): string
    {
        $styles = $GLOBALS['theme_assets']['styles'] ?? [];
        if (!is_array($styles) || $styles === []) {
            return '';
        }

        $html = [];
        foreach ($styles as $style) {
            $src = (string) ($style['src'] ?? '');
            if ($src === '') {
                continue;
            }

            $version = $style['version'] ?? null;
            $url = $version !== null && $version !== '' ? $src . (str_contains($src, '?') ? '&' : '?') . 'ver=' . rawurlencode((string) $version) : $src;
            $html[] = '<link rel="stylesheet" id="' . htmlspecialchars((string) $style['handle'], ENT_QUOTES, 'UTF-8') . '-css" href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" media="' . htmlspecialchars((string) ($style['media'] ?? 'all'), ENT_QUOTES, 'UTF-8') . '">';
        }

        return implode("\n", $html);
    }
}

if (!function_exists('theme_render_scripts')) {
    function theme_render_scripts(bool $footer = true): string
    {
        $scripts = $GLOBALS['theme_assets']['scripts'] ?? [];
        if (!is_array($scripts) || $scripts === []) {
            return '';
        }

        $html = [];
        foreach ($scripts as $script) {
            $inFooter = (bool) ($script['in_footer'] ?? true);
            if ($inFooter !== $footer) {
                continue;
            }

            $src = (string) ($script['src'] ?? '');
            if ($src === '') {
                continue;
            }

            $version = $script['version'] ?? null;
            $url = $version !== null && $version !== '' ? $src . (str_contains($src, '?') ? '&' : '?') . 'ver=' . rawurlencode((string) $version) : $src;
            $html[] = '<script id="' . htmlspecialchars((string) $script['handle'], ENT_QUOTES, 'UTF-8') . '-js" src="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></script>';
        }

        return implode("\n", $html);
    }
}

if (!function_exists('wp_head')) {
    function wp_head(): void
    {
        if (function_exists('do_action')) {
            do_action('wp_head');
        }
        echo theme_render_styles();
        $headScripts = theme_render_scripts(false);
        if ($headScripts !== '') {
            echo "\n" . $headScripts;
        }
    }
}

if (!function_exists('wp_footer')) {
    function wp_footer(): void
    {
        if (function_exists('do_action')) {
            do_action('wp_footer');
        }
        $footerScripts = theme_render_scripts(true);
        if ($footerScripts !== '') {
            echo "\n" . $footerScripts;
        }
    }
}

if (!function_exists('theme_resolve_template')) {
    function theme_resolve_template(string $contextType, string $page, array $data): string
    {
        $page = strtolower(trim($page));
        $page = preg_replace('/[^a-z0-9\-]/', '', $page) ?: 'home';

        $candidates = match ($contextType) {
            'home' => ['templates/home.php', 'home.php', 'index.php'],
            'single' => ['templates/single.php', 'single.php', 'index.php'],
            'archive' => ['templates/archive.php', 'archive.php', 'index.php'],
            '404' => ['templates/404.php', '404.php', 'index.php'],
            default => [
                'templates/page-' . $page . '.php',
                'page-' . $page . '.php',
                'templates/page.php',
                'page.php',
                'index.php',
            ],
        };

        return theme_locate_file($candidates);
    }
}

if (!function_exists('theme_enqueue_defaults')) {
    function theme_enqueue_defaults(): void
    {
        $meta = theme_style_metadata();
        $version = (string) ($meta['version'] ?? '1.0.0');

        if (is_file(theme_file('style.css'))) {
            enqueue_style('theme-style', theme_url('style.css'), [], $version);
        }

        if (is_file(theme_file('assets/css/theme.css'))) {
            enqueue_style('theme-assets', theme_url('assets/css/theme.css'), ['theme-style'], $version);
        }

        if (is_file(theme_file('assets/js/theme.js'))) {
            enqueue_script('theme-app', theme_url('assets/js/theme.js'), [], $version, true);
        }
    }
}

if (!function_exists('render')) {
    function render(string $page, array $data = []): void
    {
        $page = strtolower(trim($page));
        $page = preg_replace('/[^a-z0-9\-]/', '', $page) ?: 'home';

        if (function_exists('apply_filters')) {
            $page = apply_filters('render_page', $page, $data);
            $data = apply_filters('render_data', $data, $page);
        }

        $legacyPageFile = theme_page_file($page);
        $dbPage = null;
        $contextType = $page === 'home' ? 'home' : 'page';

        if ($page !== 'home' && !is_file($legacyPageFile) && function_exists('cms_get_page_by_slug')) {
            $dbPage = cms_get_page_by_slug($page);
        }

        if ($page === '404') {
            http_response_code(404);
            $contextType = '404';
        } elseif ($page !== 'home' && !is_file($legacyPageFile) && !is_array($dbPage)) {
            http_response_code(404);
            $page = '404';
            $contextType = '404';
            $legacyPageFile = theme_page_file('404');
        } elseif ($page !== 'home' && is_array($dbPage)) {
            $data['db_page'] = $dbPage;
            $data['title'] = $dbPage['title'] ?? $page;
            $data['content'] = $dbPage['content'] ?? '';
            $data['header_content'] = $dbPage['header_content'] ?? '';
            $data['footer_content'] = $dbPage['footer_content'] ?? '';
            $data['hidden_blocks_json'] = $dbPage['hidden_blocks_json'] ?? '';
            $data['meta_title'] = $dbPage['meta_title'] ?? '';
            $data['meta_description'] = $dbPage['meta_description'] ?? '';
            $data['schema_json'] = $dbPage['schema_json'] ?? '';
        }

        $data['page'] = $page;
        $data['template_type'] = $contextType;
        $data['legacy_page_file'] = $legacyPageFile;
        $data['theme_meta'] = theme_style_metadata();
        $data['before_render_output'] = theme_capture_hook_output('before_render', $page, $data);
        $data['after_render_output'] = theme_capture_hook_output('after_render', $page, $data);

        $templateFile = theme_resolve_template($contextType, $page, $data);
        if ($templateFile === '') {
            http_response_code(500);
            exit('Theme template missing');
        }

        $GLOBALS['theme_page'] = $page;
        $GLOBALS['theme_data'] = $data;
        $GLOBALS['theme_context'] = $data;
        $GLOBALS['theme_render_hooks'] = [
            'before_render' => $data['before_render_output'],
            'after_render' => $data['after_render_output'],
        ];

        $db = $GLOBALS['db'] ?? null;
        $db1 = $GLOBALS['db1'] ?? null;
        extract($data, EXTR_SKIP);

        ob_start();
        require $templateFile;
        $output = (string) ob_get_clean();

        if (!empty($GLOBALS['loaded_plugins'])) {
            $pluginComment = "\n<!-- Plugin Loaded -->";
            if (stripos($output, '</body>') !== false) {
                $output = preg_replace('/<\/body>/i', $pluginComment . "\n</body>", $output, 1) ?? ($output . $pluginComment);
            } else {
                $output .= $pluginComment;
            }
        }

        if (function_exists('apply_filters')) {
            $output = apply_filters('render_output', $output, $page, $data);
        }

        echo $output;
    }
}

theme_enqueue_defaults();
