<?php

namespace App\Core;

require_once __DIR__ . '/Session.php';

final class Csrf
{
    private const SESSION_KEY = '_csrf_token';
    private const ERROR_KEY = '_csrf_error';
    private const DEFAULT_ERROR_MESSAGE = 'انتهت صلاحية الطلب. أعد المحاولة.';

    public static function token(): string
    {
        Session::start();
        $current = $_SESSION[self::SESSION_KEY] ?? '';
        if (!is_string($current) || $current === '') {
            $current = bin2hex(random_bytes(32));
            $_SESSION[self::SESSION_KEY] = $current;
        }
        return $current;
    }

    public static function isValid(?string $token): bool
    {
        if (!is_string($token) || $token === '') {
            return false;
        }
        return hash_equals(self::token(), $token);
    }

    public static function fail(?string $redirectUrl = null): void
    {
        Session::start();
        $_SESSION[self::ERROR_KEY] = self::DEFAULT_ERROR_MESSAGE;

        if (is_string($redirectUrl) && $redirectUrl !== '' && !headers_sent()) {
            header('Location: ' . $redirectUrl);
            exit;
        }

        http_response_code(419);
        echo self::DEFAULT_ERROR_MESSAGE;
        exit;
    }

    public static function enforce(?string $token, ?string $redirectUrl = null): void
    {
        if (self::isValid($token)) {
            return;
        }
        self::fail($redirectUrl);
    }

    public static function pullError(): ?string
    {
        Session::start();
        $message = $_SESSION[self::ERROR_KEY] ?? null;
        unset($_SESSION[self::ERROR_KEY]);
        return is_string($message) && $message !== '' ? $message : null;
    }
}
