<?php

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

// Always load the integration model.
$integrazo_wz_model = new INTEGRAZO_WZ_Integration_Model();

// Get total integration count
$integrazo_wz_integration_count = $integrazo_wz_model->get_total_integrations_count();

// If no integrations, show initial setup page
$integrazo_wz_nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
$action = isset($_GET['action']) ? sanitize_key(wp_unslash($_GET['action'])) : '';

if ($action === 'addnew' && !empty($integrazo_wz_nonce) && !wp_verify_nonce($integrazo_wz_nonce, 'integrazo_wz_setup_add')) {
    wp_die(esc_html__('Security check failed. Please reload the page and try again.', 'integrazo-integration-for-zoho-apps'));
}

if (! current_user_can('manage_options')) {
    wp_die(esc_html__('Insufficient permissions.', 'integrazo-integration-for-zoho-apps'));
}

// Free plan supports only 1 integration.
if ($action === 'addnew' && ! integrazo_wz_session() && $integrazo_wz_integration_count >= 1) {
    set_transient(
        'integrazo_wz_fail',
        sprintf(
            /* translators: %s: upgrade URL */
            __('Free plan supports only 1 integration. <a href="%s" target="_blank">Upgrade to Pro</a> for unlimited integrations.', 'integrazo-integration-for-zoho-apps'),
            esc_url('https://integrazo.com/products/integration-for-zoho-apps')
        ),
        30
    );
    wp_safe_redirect(admin_url('admin.php?page=integrazo-integration-for-zoho-apps&tab=setup'));
    exit;
}

if (
    $integrazo_wz_integration_count > 0 &&
    !isset($_GET['integration_id']) &&
    (!isset($_GET['action']) || $_GET['action'] !== 'addnew')
) {
    // Notices are shown inside includes/extend/setup.php, right after the "Integrations" heading.
    require_once INTEGRAZO_WZ_PLUGIN_DIR . 'includes/extend/setup.php';
} else {

    // Show back button if there is at least one integration
    if ($integrazo_wz_integration_count > 0) {
        echo '<div style="margin:12px 0 18px;"><a href="admin.php?page=integrazo-integration-for-zoho-apps&tab=setup" style="display:inline-flex;align-items:center;gap:5px;font-size:13px;font-weight:500;color:#2271b1;text-decoration:none;padding:5px 12px;border:1px solid #c3c4c7;border-radius:4px;background:#fff;" onmouseover="this.style.background=\'#f0f6fc\'" onmouseout="this.style.background=\'#fff\'">&#8592; ' . esc_html__('Back to Integrations', 'integrazo-integration-for-zoho-apps') . '</a></div>';
        // Show notices right below the button.
        integrazo_wz_render_pending_notices();
    } else {
        // No button yet (first-ever integration) — show notices at the top of the content.
        integrazo_wz_render_pending_notices();
    }
    // Load integration options utility

    $integrazo_wz_account_instance = new INTEGRAZO_WZ_Account_Model();
    $integrazo_wz_account_count    = $integrazo_wz_account_instance->get_total_accounts_count();

    // Initialize variables
    $integrazo_wz_integration_details = null;
    $integrazo_wz_account_details     = null;
    $integrazo_wz_account_id          = null;
    $integrazo_wz_account_name        = null;
    $integrazo_wz_integration_id      = null;
    $integrazo_wz_from_plugin         = null;
    $integrazo_wz_to_product          = null;
    $integrazo_wz_integration_name    = null;
    $integrazo_wz_field_mapping  = null;

    // Check if we are editing an existing integration
    if (
        isset($_GET['integration_id']) &&
        isset($_GET['page']) &&
        sanitize_text_field(wp_unslash($_GET['page'])) === 'integrazo-integration-for-zoho-apps'
    ) {

        $integrazo_wz_integration_id      = intval($_GET['integration_id']);
        $integrazo_wz_integration_details = $integrazo_wz_model->get_integration_by_id($integrazo_wz_integration_id);

        if (!empty($integrazo_wz_integration_details)) {
            $integrazo_wz_from_plugin      = $integrazo_wz_integration_details['from_plugin'] ?? '';
            $integrazo_wz_to_product       = $integrazo_wz_integration_details['to_product'] ?? '';
            $integrazo_wz_account_id       = $integrazo_wz_integration_details['account_id'] ?? null;
            $integrazo_wz_integration_name = $integrazo_wz_integration_details['integration_name'] ?? '';
            $integrazo_wz_field_mapping =  $integrazo_wz_integration_details['field_mapping'] ?? 1;
            if (!empty($integrazo_wz_account_id)) {
                $integrazo_wz_account_details = $integrazo_wz_account_instance->get_account_by_id($integrazo_wz_account_id);
                $integrazo_wz_account_name    = $integrazo_wz_account_details['account_name'] ?? '';
            }
        }
    }

    // Compute the real current step from what's actually saved, so the accordion
    // header badges/icons and the section that auto-opens reflect true progress
    // instead of only trusting the raw ?step= URL param.
    $integrazo_wz_current_step = 1;
    if (! empty($integrazo_wz_account_id)) {
        $integrazo_wz_current_step = (! empty($integrazo_wz_field_mapping) && $integrazo_wz_field_mapping != 1) ? 4 : 3;
    } elseif (! empty($integrazo_wz_from_plugin) && ! empty($integrazo_wz_to_product)) {
        $integrazo_wz_current_step = 2;
    }

    // The section to auto-open on load. current_step >= 4 means the integration is fully
    // configured. Right after clicking "Save Mapping" (one-shot flag set by that redirect),
    // leave every section collapsed. Any other time (reload, clicking Edit from the list,
    // etc.) default to reopening Step 3 (Map Fields) since that's the one most likely to be
    // reviewed/edited again.
    $integrazo_wz_just_completed_mapping = ! empty($integrazo_wz_integration_id) && get_transient('integrazo_wz_just_completed_' . $integrazo_wz_integration_id);
    if ($integrazo_wz_just_completed_mapping) {
        delete_transient('integrazo_wz_just_completed_' . $integrazo_wz_integration_id);
    }
    $integrazo_wz_open_step = ($integrazo_wz_current_step >= 4 && ! $integrazo_wz_just_completed_mapping) ? 3 : $integrazo_wz_current_step;

    wp_localize_script('integrazo-wz-setup-js', 'integrazo_wz_setup', [
        'current_step' => (int) $integrazo_wz_open_step,
    ]);

    // Include setup steps
    require_once INTEGRAZO_WZ_PLUGIN_DIR . 'includes/page/setup-1.php';
    require_once INTEGRAZO_WZ_PLUGIN_DIR . 'includes/page/setup-2.php';
    require_once INTEGRAZO_WZ_PLUGIN_DIR . 'includes/page/setup-3.php';
    //

}
