<?php

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


// ----------------------------------Setp1--------------------------------------------------

add_action('admin_post_integrazo_wczo_save_integration', 'integrazo_wczo_handle_save_integration_form');

function integrazo_wczo_handle_save_integration_form()
{
    // Verify nonce
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce should not be sanitized
    if (
        ! isset($_POST['integrazo_wczo_nonce']) ||
        ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['integrazo_wczo_nonce'])), 'integrazo_wczo_save_integration_action')
    ) {
        wp_die(esc_html__('Security check failed', 'integrazo-wc-zoho-integration'));
    }
    if (! current_user_can('manage_options')) {
        wp_die(esc_html__('Insufficient permissions.', 'integrazo-wc-zoho-integration'));
    }
    // Sanitize and fetch the fields
    $integration_name = sanitize_text_field(wp_unslash($_POST['integration_name'] ?? ''));
    $from_plugin      = sanitize_text_field(wp_unslash($_POST['from_plugin'] ?? ''));
    $to_product       = sanitize_text_field(wp_unslash($_POST['to_product'] ?? ''));

    // (Optional) Validate required fields
    if (empty($integration_name) || empty($from_plugin) || empty($to_product)) {
        wp_safe_redirect(admin_url('admin.php?page=integrazo-wc-zoho-integration&error=1'));
        exit;
    }
    $model = new INTEGRAZO_WCZO_Integration_Model();
    $inserted_id = $model->add_integration($integration_name, $from_plugin, $to_product);
    // Redirect back with success message
    wp_safe_redirect(admin_url('admin.php?page=integrazo-wc-zoho-integration&integration_id=' . $inserted_id . '&step=2'));

    exit;
}

add_action('admin_post_integrazo_wczo_save_only', 'integrazo_wczo_handle_save_integration_name');

function integrazo_wczo_handle_save_integration_name()
{
    // Verify nonce
    if (
        ! isset($_POST['integrazo_wczo_nonce']) ||
        ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['integrazo_wczo_nonce'])), 'integrazo_wczo_save_integration_action')
    ) {
        wp_die(esc_html__('Security check failed', 'integrazo-wc-zoho-integration'));
    }
    if (! current_user_can('manage_options')) {
        wp_die(esc_html__('Insufficient permissions.', 'integrazo-wc-zoho-integration'));
    }
    // Sanitize and fetch the fields
    $integration_name = sanitize_text_field(wp_unslash($_POST['integration_name'] ?? ''));
    $integration_id   = sanitize_text_field(wp_unslash($_POST['integration_id'] ?? ''));

    $redirect_url = admin_url('admin.php?page=integrazo-wc-zoho-integration&tab=setup&integration_id=' . urlencode($integration_id) . '&step=1');

    // Check for required fields
    if (empty($integration_name) || empty($integration_id)) {
        set_transient('integrazo_wczo_integration_error', __('Integration ID or name is missing.', 'integrazo-wc-zoho-integration'), 30);
        wp_safe_redirect($redirect_url);
        exit;
    }

    // Update integration name
    $model = new INTEGRAZO_WCZO_Integration_Model();
    $updated = $model->update_integration_name_by_id($integration_id, $integration_name);

    if ($updated) {
        set_transient('integrazo_wczo_integration_message', __('Integration name updated successfully!', 'integrazo-wc-zoho-integration'), 30);
    } else {
        set_transient('integrazo_wczo_integration_error', __('Failed to update integration name.', 'integrazo-wc-zoho-integration'), 30);
    }

    wp_safe_redirect($redirect_url);
    exit;
}



// ----------------------------------Setp3-------------------------------------------------------

// Hook the form action to WordPress
add_action('admin_post_integrazo_wczo_save_mapping', 'integrazo_wczo_save_mapping');

function integrazo_wczo_save_mapping()
{
    // Verify nonce
    if (
        ! isset($_POST['integrazo_wczo_save_mapping_nonce']) ||
        ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['integrazo_wczo_save_mapping_nonce'])), 'integrazo_wczo_save_mapping_action')
    ) {
        wp_die(esc_html__('Invalid request', 'integrazo-wc-zoho-integration'));
    }
    if (! current_user_can('manage_options')) {
        wp_die(esc_html__('Insufficient permissions.', 'integrazo-wc-zoho-integration'));
    }
    // Sanitize inputs
    $integration_id        = sanitize_text_field(wp_unslash($_POST['integration_id'] ?? ''));
    $record_action         = sanitize_text_field(wp_unslash($_POST['record_action'] ?? ''));
    $primary_key          = sanitize_text_field(wp_unslash($_POST['primary_key'] ?? ''));
    $filter_criteria      = sanitize_text_field(wp_unslash($_POST['filter_criteria'] ?? ''));
    $filter_criteria_json = sanitize_text_field(wp_unslash($_POST['filter_criteria_json'] ?? ''));
    $field_mapping_json   = sanitize_text_field(wp_unslash($_POST['final_json'] ?? ''));

    if (empty($integration_id) || empty($field_mapping_json)) {
        wp_die(esc_html__('Integration ID or mapping data is missing.', 'integrazo-wc-zoho-integration'));
    }

    $field_mapping = json_decode($field_mapping_json, true);
    if (!is_array($field_mapping)) {
        wp_die(esc_html__('Invalid mapping data format.', 'integrazo-wc-zoho-integration'));
    }

    $model = new INTEGRAZO_WCZO_Integration_Model();
    $success = $model->update_fieldmapping_data(
        $integration_id,
        $record_action,
        $primary_key,
        $filter_criteria,
        $filter_criteria_json,
        $field_mapping
    );

    if ($success) {
        set_transient('integrazo_wczo_success', __('Integration updated successfully.', 'integrazo-wc-zoho-integration'), 60);
        $redirect_url = admin_url('admin.php?page=integrazo-wc-zoho-integration&tab=setup&integration_id=' . urlencode($integration_id) . '&step=3');
        wp_safe_redirect($redirect_url);
        exit;
    } else {
        set_transient('integrazo_wczo_fail', __('Failed to update integration. Please try again.', 'integrazo-wc-zoho-integration'), 60);
        wp_die(esc_html__('Failed to update mapping data.', 'integrazo-wc-zoho-integration'));
    }
}
