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

class BPLVF_Settings_API {
    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']);

        // User Voice Feedback
        add_action('wp_ajax_bplvf_toggle_resolved', [__CLASS__, 'handle_toggle_resolve']);
        add_action('wp_ajax_bplvf_delete_user_feedback', [__CLASS__, 'handle_delelte_user_feedback']);
    }

    // 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]);
    }

    // User Feedback
    public static function handle_toggle_resolve() {
        check_ajax_referer('bplvf_voice_feedback_nonce', 'nonce');
    
        $id = intval($_POST['id']);
        if (!$id) {
            wp_send_json_error();
        }
    
        $current_value = get_post_meta($id, 'isResolve', true);
        $new_value = $current_value ? 0 : 1;
        update_post_meta($id, 'isResolve', $new_value);
    
        wp_send_json_success();
    }
    
    public static function handle_delelte_user_feedback() {
        check_ajax_referer('bplvf_voice_feedback_nonce', 'nonce');
    
        $id = intval($_POST['id']);
        if (!$id) {
            wp_send_json_error();
        }
    
        $deleted = wp_delete_post($id, true);
        if ($deleted) {
            wp_send_json_success();
        } else {
            wp_send_json_error();
        }
    }

}

