<?php

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


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

add_action('admin_post_integrazo_wz_save_integration', 'integrazo_wz_handle_save_integration_form');

function integrazo_wz_handle_save_integration_form()
{
    // Verify nonce
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce should not be sanitized
    if (
        ! isset($_POST['integrazo_wz_nonce']) ||
        ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['integrazo_wz_nonce'])), 'integrazo_wz_save_integration_action')
    ) {
        wp_die(esc_html__('Security check failed', 'integrazo-integration-for-zoho-apps'));
    }
    if (! current_user_can('manage_options')) {
        wp_die(esc_html__('Insufficient permissions.', 'integrazo-integration-for-zoho-apps'));
    }
    // 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-integration-for-zoho-apps&error=1'));
        exit;
    }
    $model = new INTEGRAZO_WZ_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-integration-for-zoho-apps&integration_id=' . absint($inserted_id) . '&step=2'));

    exit;
}

add_action('admin_post_integrazo_wz_save_only', 'integrazo_wz_handle_save_integration_name');

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

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

    // Check for required fields
    if (empty($integration_name) || empty($integration_id)) {
        set_transient('integrazo_wz_integration_error', 'Integration ID or name is missing.', 30);
        wp_safe_redirect($redirect_url);
        exit;
    }

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

    if ($updated) {
        set_transient('integrazo_wz_integration_message', 'Integration name updated successfully!', 30);
    } else {
        set_transient('integrazo_wz_integration_error', 'Failed to update integration name.', 30);
    }

    wp_safe_redirect($redirect_url);
    exit;
}



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

// Hook the form action to WordPress
add_action('admin_post_integrazo_wz_save_mapping', 'integrazo_wz_save_mapping');

function integrazo_wz_save_mapping()
{
    // Verify nonce
    if (
        ! isset($_POST['integrazo_wz_save_mapping_nonce']) ||
        ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['integrazo_wz_save_mapping_nonce'])), 'integrazo_wz_save_mapping_action')
    ) {
        wp_die(esc_html__('Invalid request', 'integrazo-integration-for-zoho-apps'));
    }
    if (! current_user_can('manage_options')) {
        wp_die(esc_html__('Insufficient permissions.', 'integrazo-integration-for-zoho-apps'));
    }
    // Sanitize inputs
    $integration_id        = absint(wp_unslash($_POST['integration_id'] ?? 0));
    $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-integration-for-zoho-apps'));
    }

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

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

    if ($success) {
        $back_to_integrations_link = '<a href="' . esc_url(admin_url('admin.php?page=integrazo-integration-for-zoho-apps&tab=setup')) . '">' . esc_html__('Back to Integrations', 'integrazo-integration-for-zoho-apps') . '</a>';
        set_transient(
            'integrazo_wz_success',
            __('Integration completed successfully! It is now live and ready to process new entries.', 'integrazo-integration-for-zoho-apps') . ' ' . $back_to_integrations_link,
            60
        );
        // One-shot flag so the very next page load (this redirect) knows to collapse every
        // step instead of auto-opening Step 3 — later visits to this integration should still
        // default to Step 3 being open.
        set_transient('integrazo_wz_just_completed_' . $integration_id, 1, 10);
        $redirect_url = admin_url('admin.php?page=integrazo-integration-for-zoho-apps&tab=setup&integration_id=' . urlencode($integration_id) . '&step=3');
        wp_safe_redirect($redirect_url);
        exit;
    } else {
        set_transient('integrazo_wz_fail', __('Failed to update integration. Please try again.', 'integrazo-integration-for-zoho-apps'), 60);
        wp_die(esc_html__('Failed to update mapping data.', 'integrazo-integration-for-zoho-apps'));
    }
}
