<?php

use App\Core\Csrf;

/**
 * csrf_field() — Render a Hidden CSRF Input Field
 *
 * Outputs an HTML hidden input containing the current session CSRF token.
 * Must be called inside HTML form tags on every state-changing (POST) form.
 *
 * Usage (in view files):
 *   <form method="POST" action="/app/couple/guests/add">
 *       <?= csrf_field() ?>
 *       <input type="text" name="name">
 *       <button type="submit">Save</button>
 *   </form>
 *
 * Output:
 *   <input type="hidden" name="_csrf" value="a3f9...64char...hex">
 *
 * The field name '_csrf' matches Csrf::FORM_FIELD (single source of truth).
 * The token is read from the session via Csrf::getToken() — no new token
 * is generated if one already exists for this session.
 *
 * The output is NOT double-encoded — htmlspecialchars() is applied once to
 * ensure the token value is safe for HTML attribute embedding.
 *
 * @package Inveetaire
 * @ref     DBP v1.0 Ch.6, ADR-005, INIT-010
 */
if (!function_exists('csrf_field')) {

    /**
     * Return an HTML hidden input containing the current CSRF token.
     *
     * @return string  HTML: <input type="hidden" name="_csrf" value="…">
     */
    function csrf_field(): string
    {
        $token = Csrf::getToken();
        $name  = htmlspecialchars(Csrf::FORM_FIELD, ENT_QUOTES, 'UTF-8');
        $value = htmlspecialchars($token,           ENT_QUOTES, 'UTF-8');

        return '<input type="hidden" name="' . $name . '" value="' . $value . '">';
    }

}
