<?php
namespace App\Core;

abstract class Controller
{
    protected function render(string $template, array $data = [], ?string $layout = 'layout/app'): void
    {
        View::render($template, $data, $layout);
    }

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

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

    protected function flashAndRedirect(string $path, string $type, string $message): void
    {
        Session::flash($type, $message);
        $this->redirect($path);
    }

    protected function requireCsrf(): bool
    {
        if (!Csrf::verify()) {
            http_response_code(419);
            echo 'Your session expired. Please go back and try again.';
            exit;
        }
        return true;
    }

    protected function notFound(): void
    {
        http_response_code(404);
        echo '<!doctype html><html><body style="font-family:sans-serif;padding:40px"><h1>404</h1><p>Not found.</p></body></html>';
        exit;
    }
}
