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


if(!class_exists('BPLVF_Ajax_Controller')) {

    class BPLVF_Ajax_Controller {
        const GLOBAL_KEY = 'global_voice_feedback';

        public static function init() {
            add_action('wp_ajax_bplvf_save_global', [__CLASS__, 'handle_save_global']);
            add_action('wp_ajax_bplvf_get_global', [__CLASS__, 'handle_get_global']);
        }

        // Save or Update Global
        public static function handle_save_global() {
            check_ajax_referer('bplvf_nonce', 'nonce');
            $settings = json_decode(stripslashes($_POST['settings'] ?? '[]'), true);
            if (!is_array($settings)) {
                wp_send_json_error(['message' => 'Invalid data']);
            }
            update_option(self::GLOBAL_KEY, $settings);
            wp_send_json_success(['message' => 'Global settings saved']);
        }
        
        // Get Global
        public static function handle_get_global() {
            check_ajax_referer('bplvf_nonce', 'nonce');
            $settings = get_option('global_voice_feedback', []);
            wp_send_json_success(['settings' => $settings]);
        }
    }
}