<?php
/**
 * SalonPro X - View/Template Renderer
 * Responsible for rendering views with layout support
 */

namespace core;

class View
{
    private string $viewPath = '';
    private array $data = [];
    private string $layout = 'main';
    private ?string $moduleName = null;
    private static ?string $capturedScripts = null;
    private static ?string $capturedInlineScripts = null;

    public function __construct(string $view, array $data = [], string $layout = 'main')
    {
        $this->data = $data;
        $this->layout = $layout;
        $this->resolveViewPath($view);
    }

    /**
     * Static factory to create and render a view
     */
    public static function render(string $view, array $data = [], string $layout = 'main'): void
    {
        $instance = new self($view, $data, $layout);
        $instance->display();
    }

    /**
     * Static factory - returns rendered HTML as string
     */
    public static function fetch(string $view, array $data = [], string $layout = 'main'): string
    {
        $instance = new self($view, $data, $layout);
        return $instance->getContent();
    }

    /**
     * Resolve the physical path of a view file
     * Format: ModuleName/view_name or just view_name (for modules)
     */
    private function resolveViewPath(string $view): void
    {
        if (str_contains($view, '/')) {
            $parts = explode('/', $view, 2);
            $module = ucfirst($parts[0]);
            $viewFile = $parts[1];
            $this->moduleName = $module;

            $paths = [
                PATH_MODULES . DS . $module . DS . 'Views' . DS . $viewFile . '.php',
                PATH_MODULES . DS . $module . DS . 'Views' . DS . $viewFile . DS . 'index.php',
                PATH_COMPONENTS . DS . $viewFile . '.php',
            ];
        } else {
            $paths = [
                PATH_MODULES . DS . ucfirst($view) . DS . 'Views' . DS . 'index.php',
            ];
        }

        foreach ($paths as $path) {
            if (file_exists($path)) {
                $this->viewPath = $path;
                return;
            }
        }

        throw new \RuntimeException("View not found: {$view}");
    }

    /**
     * Display the view with layout
     */
    public function display(): void
    {
        $content = $this->getContent();
        
        if ($this->layout && $this->layout !== 'none') {
            $layoutPath = PATH_LAYOUTS . DS . $this->layout . '.php';
            if (file_exists($layoutPath)) {
                extract($this->data);
                $viewContent = $content;
                if (self::$capturedScripts !== null) {
                    $scripts = self::$capturedScripts;
                }
                if (self::$capturedInlineScripts !== null) {
                    $inlineScripts = self::$capturedInlineScripts;
                }
                include $layoutPath;
                self::$capturedScripts = null;
                self::$capturedInlineScripts = null;
                return;
            }
        }
        
        echo $content;
    }

    /**
     * Get the rendered view content as string
     */
    public function getContent(): string
    {
        ob_start();
        extract($this->data);
        
        if (file_exists($this->viewPath)) {
            include $this->viewPath;
        }
        
        if (isset($scripts)) {
            self::$capturedScripts = $scripts;
        }
        if (isset($inlineScripts)) {
            self::$capturedInlineScripts = $inlineScripts;
        }
        
        return ob_get_clean();
    }

    /**
     * Render a partial view
     */
    public static function partial(string $partial, array $data = []): void
    {
        $paths = [
            PATH_PARTIALS . DS . $partial . '.php',
            PATH_COMPONENTS . DS . $partial . '.php',
        ];

        foreach ($paths as $path) {
            if (file_exists($path)) {
                extract($data);
                include $path;
                return;
            }
        }
    }

    /**
     * Include a component
     */
    public static function component(string $component, array $data = []): void
    {
        $path = PATH_COMPONENTS . DS . $component . '.php';
        if (file_exists($path)) {
            extract($data);
            include $path;
        }
    }

    /**
     * Set layout
     */
    public function setLayout(string $layout): self
    {
        $this->layout = $layout;
        return $this;
    }

    /**
     * Add data to view
     */
    public function with(string $key, mixed $value): self
    {
        $this->data[$key] = $value;
        return $this;
    }

    /**
     * Get module name
     */
    public function getModule(): ?string
    {
        return $this->moduleName;
    }
}
