<?php
/**
 * Classe Controller base
 * Localização: /app/core/Controller.php
 */

abstract class Controller
{
    protected function model(string $model)
    {
        $file = APP_PATH . "/models/{$model}.php";
        if (!file_exists($file)) {
            throw new Exception("Model {$model} não encontrado");
        }
        require_once $file;
        return new $model();
    }

    protected function view(string $view, array $data = [], string $layout = 'public'): void
    {
        extract($data);
        $viewFile = VIEWS_PATH . "/{$view}.php";

        if (!file_exists($viewFile)) {
            throw new Exception("View {$view} não encontrada");
        }

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

        // Captura o conteúdo da view
        ob_start();
        require $viewFile;
        $content = ob_get_clean();

        // Carrega o layout
        $layoutFile = VIEWS_PATH . "/layouts/{$layout}.php";
        if (file_exists($layoutFile)) {
            require $layoutFile;
        } else {
            echo $content;
        }
    }

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

    protected function redirect(string $url): void
    {
        header("Location: {$url}");
        exit;
    }

    protected function back(): void
    {
        $ref = $_SERVER['HTTP_REFERER'] ?? BASE_URL;
        $this->redirect($ref);
    }

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

    protected function requireAdmin(): void
    {
        if (empty($_SESSION['admin_id'])) {
            $this->redirect(ADMIN_URL . '/login');
        }
    }

    protected function setFlash(string $type, string $message): void
    {
        $_SESSION['flash'][$type] = $message;
    }

    protected function validateCsrf(): void
    {
        $token = $_POST[CSRF_TOKEN_NAME] ?? '';
        $session = $_SESSION[CSRF_TOKEN_NAME] ?? '';
        if (!$token || !hash_equals($session, $token)) {
            http_response_code(419);
            die('Token CSRF inválido');
        }
    }
}
