<?php
// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

// Handle the AJAX request to update integration status.
add_action('wp_ajax_integrazo_wczo_integration_status', 'integrazo_wczo_update_integration_status');

function integrazo_wczo_update_integration_status()
{
    // Verify nonce for security
    if (
        !isset($_POST['security']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'field_mapping_nonce')
    ) {
        wp_send_json_error(['message' => esc_html__('Security check failed.', 'integrazo-wc-zoho-integration')]);
    }
    if (! current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Insufficient permissions.', 'integrazo-wc-zoho-integration')]);
    }
    // Sanitize and validate inputs
    $integration_id = isset($_POST['integration_id']) ? (int) $_POST['integration_id'] : 0;
    $integration_status = isset($_POST['integration_status']) ? (int) $_POST['integration_status'] : 3;

    if ($integration_id <= 0 || !in_array($integration_status, [2, 3], true)) {
        wp_send_json_error(['message' => 'Invalid request data']);
    }

    // Update integration status
    $model = new INTEGRAZO_WCZO_Integration_Model();
    $updated = $model->update_integration_status($integration_id, $integration_status);

    if ($updated) {
        wp_send_json_success(['message' => 'Integration status updated successfully']);
    } else {
        wp_send_json_error(['message' => 'Failed to update integration status']);
    }

    wp_die();
}
