<?php

class CSRF
{
    public function generate()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $token = bin2hex(random_bytes(32));
        $_SESSION[CSRF_TOKEN_NAME] = $token;
        return $token;
    }

    public function verify($token)
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        if (!is_string($token) || empty($token) || empty($_SESSION[CSRF_TOKEN_NAME])) {
            return false;
        }

        $valid = hash_equals($_SESSION[CSRF_TOKEN_NAME], $token);
        if ($valid) {
            unset($_SESSION[CSRF_TOKEN_NAME]);
        }
        return $valid;
    }

    public function field()
    {
        $token = $this->getToken();
        return '<input type="hidden" name="' . CSRF_TOKEN_NAME . '" value="' . htmlspecialchars($token, ENT_QUOTES, 'UTF-8') . '">';
    }

    public function getToken()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        if (empty($_SESSION[CSRF_TOKEN_NAME])) {
            return $this->generate();
        }

        return $_SESSION[CSRF_TOKEN_NAME];
    }
}
