<?php

namespace WPSN\Core;

defined('ABSPATH') || exit;

/**
 * Security helpers for admin_post / wp_ajax actions.
 *
 * Goal: keep the "happy path" readable and make it harder to forget
 * capability + nonce checks in new handlers.
 */
final class Security
{
    /**
     * Require a capability, otherwise die with a safe message.
     */
    public static function requireCapability(string $capability, string $message = ''): void
    {
        if ($capability === '') {
            return;
        }

        if (!current_user_can($capability)) {
            $msg = $message !== '' ? $message : __('Permission denied.', 'wp-seo-next');
            wp_die(esc_html($msg));
        }
    }

    /**
     * Verify admin-post nonce.
     *
     * @param string $action Nonce action
     * @param string $field  Request field name that carries nonce
     */
    public static function checkAdminNonce(string $action, string $field = '_wpnonce'): void
    {
        check_admin_referer($action, $field);
    }

    /**
     * Verify AJAX nonce.
     *
     * @param string $action Nonce action
     * @param string $field  Request field name that carries nonce (default: 'nonce')
     */
    public static function checkAjaxNonce(string $action, string $field = 'nonce'): void
    {
        check_ajax_referer($action, $field);
    }

    /**
     * Send a JSON error response in AJAX handlers.
     *
     * @param array<string,mixed> $data
     */
    public static function jsonError(array $data, int $status = 403): void
    {
        wp_send_json_error($data, $status);
    }

    /**
     * Send a JSON success response in AJAX handlers.
     *
     * @param array<string,mixed> $data
     */
    public static function jsonSuccess(array $data): void
    {
        wp_send_json_success($data);
    }
}
