<?php

declare(strict_types=1);

namespace Instinctor\Core\Session;

/**
 * WordPress session/CSRF driver.
 *
 * Thin wrapper over wp_create_nonce, wp_verify_nonce, check_ajax_referer.
 * Zero behavior change for WP installs.
 */

if (!defined('ABSPATH')) exit;
class WordPressDriver implements DriverInterface
{
    public function token(string $action): string
    {
        return wp_create_nonce($action);
    }

    public function verify(string $token, string $action): bool
    {
        // phpcs:ignore PluginCheck.Security.VerifyNonce -- thin boolean accessor: the return value IS the check, handed to callers who guard on it (wp_verify_nonce() is used inside if() conditions). check_admin_referer()/check() die() on failure, which is the separate check() method below; verify() must stay non-fatal.
        return (bool) wp_verify_nonce($token, $action);
    }

    public function check(string $action, string $field = 'nonce', bool $die = true): bool
    {
        // Cast to string — PHP 8.x deprecation guard when field is null/missing
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce retrieved for wp_verify_nonce
        $_REQUEST[$field] = sanitize_text_field(wp_unslash((string)($_REQUEST[$field] ?? '')));
        if (isset($_POST[$field])) $_POST[$field] = sanitize_text_field(wp_unslash((string)$_POST[$field]));
        $result = check_ajax_referer($action, $field, $die);
        return $result !== false;
    }
}
