<?php

namespace AIPSTX;

if (!defined('ABSPATH'))
    exit;

if (!class_exists('\\AIPSTX\\AIPSTX_AjaxHandler')) {
    class AIPSTX_AjaxHandler {
        
        private static $api_namespace = 'aipstx/v1';

        public function __construct() {
            add_action('rest_api_init', array($this, 'register_rest_routes'));
        }

        public static function localizeScripts($handle) {
            // Only localize the basic AJAX URL for all users
            wp_localize_script(
                $handle,
                'aipstxAjax',
                array(
                    'ajax_url' => admin_url('admin-ajax.php')
                )
            );

            // Add REST API configuration via inline script for authorized users
            if (current_user_can('edit_posts') || current_user_can('manage_options')) {
                $rest_config = sprintf(
                    'window.aipstxRest = {url: "%s", nonce: "%s"};',
                    esc_url_raw(rest_url(self::$api_namespace)),
                    wp_create_nonce('wp_rest')
                );
                wp_add_inline_script($handle, $rest_config, 'before');
            }
        }

        public function register_rest_routes() {
            register_rest_route(
                self::$api_namespace,
                '/get-nonce',
                array(
                    'methods' => 'POST',
                    'callback' => array($this, 'get_nonce'),
                    'permission_callback' => array($this, 'verify_user_permissions')
                )
            );
        }

        public function get_nonce(\WP_REST_Request $request) {
            if (!$this->verify_user_permissions()) {
                return new \WP_Error(
                    'rest_forbidden',
                    'You do not have permissions to access this endpoint.',
                    array('status' => 403)
                );
            }

            return rest_ensure_response(array(
                'nonce' => wp_create_nonce('aipstx_nonce')
            ));
        }

        /**
         * Verify if the current user has proper permissions
         *
         * @return bool
         */
        public static function verify_user_permissions() {
            return current_user_can('edit_posts') || current_user_can('manage_options');
        }

        /**
         * Verify nonce and user permissions
         *
         * @param string $nonce The nonce to verify
         * @return bool
         */
        public static function verify_request($nonce) {
            if (!self::verify_user_permissions()) {
                return false;
            }

            return wp_verify_nonce($nonce, 'aipstx_nonce');
        }
    }

    // Initialize the class
    new AIPSTX_AjaxHandler();
}
