<?php

namespace App\Core;

/**
 * View Engine - محرك القوالب
 * للـ MVC Pattern
 */
class View
{
    private string $viewsPath;
    private array $sharedData = [];

    public function __construct(string $viewsPath = null)
    {
        $this->viewsPath = $viewsPath ?? __DIR__ . '/../../modules';
    }

    /**
     * Render view
     */
    public function render(string $view, array $data = []): string
    {
        $data = array_merge($this->sharedData, $data);
        extract($data);

        $viewFile = $this->viewsPath . '/' . $view . '.php';
        
        if (!file_exists($viewFile)) {
            throw new \Exception("View not found: {$view}");
        }

        ob_start();
        include $viewFile;
        return ob_get_clean();
    }

    /**
     * Share data مع جميع views
     */
    public function share(string $key, $value): void
    {
        $this->sharedData[$key] = $value;
    }

    /**
     * Render JSON
     */
    public function json(array $data, int $statusCode = 200): void
    {
        http_response_code($statusCode);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    /**
     * Render with layout
     */
    public function renderWithLayout(string $view, array $data = [], string $layout = 'default'): string
    {
        $content = $this->render($view, $data);
        
        $layoutFile = $this->viewsPath . '/layouts/' . $layout . '.php';
        if (file_exists($layoutFile)) {
            $data['content'] = $content;
            return $this->render('layouts/' . $layout, $data);
        }

        return $content;
    }
}
