<?php
/**
 * Base Controller
 */

abstract class Controller {
    /**
     * Render a view within a layout
     */
    protected function render(string $viewPath, array $data = [], string $layout = 'main'): void {
        // Extract data variables for the view
        extract($data);

        // Capture view content
        $viewFile = __DIR__ . '/../../views/' . $viewPath . '.php';
        if (!file_exists($viewFile)) {
            throw new Exception("View file not found: {$viewPath}");
        }

        ob_start();
        require $viewFile;
        $content = ob_get_clean();

        // If no layout requested, output view directly
        if ($layout === 'none' || empty($layout)) {
            echo $content;
            return;
        }

        // Render within layout
        $layoutFile = __DIR__ . '/../../views/layouts/' . $layout . '.php';
        if (!file_exists($layoutFile)) {
            throw new Exception("Layout file not found: {$layout}");
        }

        require $layoutFile;
    }

    /**
     * Return JSON response
     */
    protected 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);
        exit;
    }

    /**
     * Redirect to path
     */
    protected function redirect(string $path): void {
        Url::redirect($path);
    }
}
