<?php

namespace App\Core;

/**
 * ITSWEBER CMS – View / Template Engine
 *
 * Renders PHP templates with theme fallback support.
 */
class View
{
    private string $themesPath;
    private string $activeTheme;
    private string $basePath;
    private array $sharedData = [];

    public function __construct(string $themesPath, string $activeTheme, string $basePath)
    {
        $this->themesPath = rtrim($themesPath, '/');
        $this->activeTheme = $activeTheme;
        $this->basePath = $basePath;
    }

    /**
     * Render a theme template.
     */
    public function render(string $template, array $data = []): string
    {
        $file = $this->resolveTemplate($template);
        if (!$file) {
            throw new \RuntimeException("Template '{$template}' not found.");
        }
        return $this->renderFile($file, array_merge($this->sharedData, $data));
    }

    /**
     * Render an admin view.
     */
    public function renderAdmin(string $view, array $data = []): string
    {
        $file = $this->basePath . '/admin/views/' . $view . '.php';
        if (!file_exists($file)) {
            throw new \RuntimeException("Admin view '{$view}' not found.");
        }
        return $this->renderFile($file, array_merge($this->sharedData, $data));
    }

    /**
     * Render an installer view.
     */
    public function renderInstaller(string $view, array $data = []): string
    {
        $file = $this->basePath . '/installer/views/' . $view . '.php';
        if (!file_exists($file)) {
            throw new \RuntimeException("Installer view '{$view}' not found.");
        }
        return $this->renderFile($file, array_merge($this->sharedData, $data));
    }

    /**
     * Share data with all views.
     */
    public function share(string $key, mixed $value): void
    {
        $this->sharedData[$key] = $value;
    }

    /**
     * Resolve template path with fallback: active theme → default theme.
     */
    private function resolveTemplate(string $template): ?string
    {
        // Try active theme
        $path = $this->themesPath . '/' . $this->activeTheme . '/templates/' . $template . '.php';
        if (file_exists($path)) {
            return $path;
        }

        // Fallback to default theme
        if ($this->activeTheme !== 'default') {
            $path = $this->themesPath . '/default/templates/' . $template . '.php';
            if (file_exists($path)) {
                return $path;
            }
        }

        return null;
    }

    /**
     * Render a PHP file with extracted data.
     */
    private function renderFile(string $file, array $data): string
    {
        extract($data, EXTR_SKIP);
        ob_start();
        include $file;
        return ob_get_clean();
    }

    /**
     * Get the active theme name.
     */
    public function activeTheme(): string
    {
        return $this->activeTheme;
    }

    /**
     * Set the active theme.
     */
    public function setActiveTheme(string $theme): void
    {
        $this->activeTheme = $theme;
    }

    /**
     * Get the URL path to a theme asset with cache-busting version string.
     */
    public function themeAsset(string $path): string
    {
        $url = '/themes/' . $this->activeTheme . '/assets/' . ltrim($path, '/');

        // Append CMS version for cache busting after theme/CMS updates
        $version = function_exists('cms_version') ? cms_version() : '1.0.0';
        return $url . '?v=' . urlencode($version);
    }
}
