<?php

declare(strict_types=1);

namespace App\Core;

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

    protected function json(array $payload, int $status = 200): string
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');

        return json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
    }

    protected function redirect(string $path): string
    {
        header('Location: ' . $path, true, 302);

        return '';
    }

    protected function input(): array
    {
        $contentType = $_SERVER['CONTENT_TYPE'] ?? '';

        if (str_contains($contentType, 'application/json')) {
            $body = json_decode((string) file_get_contents('php://input'), true);

            return is_array($body) ? $body : [];
        }

        return $_POST;
    }

    protected function ensureCsrf(): ?string
    {
        if (!Security::validateCsrf($this->input()['_csrf'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? null))) {
            return $this->json(['ok' => false, 'message' => 'Невалиден CSRF токен. Обновете страницата.'], 419);
        }

        return null;
    }

    protected function isAjax(): bool
    {
        return strtolower($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '') === 'xmlhttprequest'
            || str_contains($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json');
    }
}
