<?php

abstract class Controller
{
    protected function view(string $view, array $data = [], ?string $layout = 'layouts.app'): void
    {
        extract($data);
        $viewFile = APP_PATH . '/views/' . str_replace('.', '/', $view) . '.php';
        if (!file_exists($viewFile)) {
            die("View not found: {$view}");
        }

        if ($layout === null) {
            require $viewFile;
            return;
        }

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

        $layoutFile = APP_PATH . '/views/' . str_replace('.', '/', $layout) . '.php';
        require $layoutFile;
    }

    protected function json(array $data, int $statusCode = 200): void
    {
        http_response_code($statusCode);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }

    protected function redirect(string $path): void
    {
        header('Location: ' . Router::url($path));
        exit;
    }

    protected function input(string $key, $default = null)
    {
        return $_POST[$key] ?? $_GET[$key] ?? $default;
    }

    protected function verifyCsrf(): void
    {
        $token = $_POST['_rms_token'] ?? '';
        if (!hash_equals($_SESSION['_rms_token'] ?? '', $token)) {
            http_response_code(419);
            die('Invalid or expired form submission. Please refresh and try again.');
        }
    }

    protected function csrfField(): string
    {
        if (empty($_SESSION['_rms_token'])) {
            $_SESSION['_rms_token'] = bin2hex(random_bytes(32));
        }
        return '<input type="hidden" name="_rms_token" value="' . $_SESSION['_rms_token'] . '">';
    }
}
