<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Request;

abstract class BaseController
{
    protected function requirePage(string $page): void
    {
        if (!Auth::instance()->canSee($page)) {
            if (is_ajax()) {
                json_out(['ok' => false, 'error' => 'You cannot open this page.'], 403);
            }
            http_response_code(403);
            view('errors/403', ['title' => 'No access']);
            exit;
        }
    }

    protected function verifyCsrf(Request $request): void
    {
        if (!Csrf::verify(Csrf::fromRequest())) {
            if (is_ajax()) {
                json_out(['ok' => false, 'error' => 'Your session expired. Refresh and try again.'], 419);
            }
            flash('error', 'Your session expired. Please try again.');
            redirect($request->path());
        }
    }
}
