<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Shared admin AJAX helpers.
 *
 * Provides common nonce/capability verification and JSON payload parsing.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/admin
 */
abstract class Kitsune_AI_Platform_Admin_Ajax_Base {

    /**
     * Verify admin AJAX request.
     *
     * @param string $capability Or feature key like 'settings', 'models', etc.
     * @return bool
     */
    public function verify_admin_request($capability = 'manage_options') {
        check_ajax_referer('kitsune_ai_platform_nonce', 'nonce');

        // Check if $capability is a specific feature key for access control
        $features = array('models', 'chatbots', 'content', 'knowledge_base', 'automation', 'analytics', 'integrations', 'settings');
        if (in_array($capability, $features, true)) {
            // Include main admin class to get permissions
            if (!class_exists('Kitsune_AI_Platform_Admin')) {
                require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/class-kitsune-ai-platform-admin.php';
            }
            $admin = new Kitsune_AI_Platform_Admin('kitsune-ai-platform', '1.0.0');
            $perms = $admin->get_user_permissions();
            
            if (empty($perms[$capability])) {
                wp_send_json_error(array('message' => __('Permission denied', 'kitsune-ai-platform')));
                return false;
            }
            return true;
        }

        if (!current_user_can($capability)) {
            wp_send_json_error(array('message' => __('Permission denied', 'kitsune-ai-platform')));
            return false;
        }

        return true;
    }

    /**
     * Decode a JSON payload field from $_POST.
     *
     * Supports plain arrays, JSON strings, and unslashed form-encoded values.
     *
     * @param string $key     Payload key in $_POST.
     * @param mixed  $default Default value when payload is missing/invalid.
     * @return mixed
     */
    protected function get_post_payload($key = 'data', $default = array()) {
        $raw = isset($_POST[$key]) ? $_POST[$key] : null;

        if (is_array($raw)) {
            return map_deep(wp_unslash($raw), 'sanitize_text_field');
        }

        if (!is_string($raw) || $raw === '') {
            return $default;
        }

        $decoded = json_decode(wp_unslash($raw), true);
        return is_array($decoded) ? map_deep($decoded, 'sanitize_text_field') : $default;
    }
}
