<?php
// Exit if accessed directly to ensure security.
if (!defined('ABSPATH')) {
    exit;
}
// Sanitize and validate the setup ID from the GET request
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$setup_id = isset($_GET['setup_id']) ? intval($_GET['setup_id']) : 0;
// Fetch integration details using the sanitized setup ID
$integration_details = $IAFWZCAI_Field_MappingDBInstance->get_mapping($setup_id);
if ($integration_details) {
    $IAFWZCAI_Form_FieldsInstance = new IAFWZCAI_Form_Fields();
    try {
        //
        $integration_name = $integration_details->integration_name;
        $module_name = $integration_details->module_name;
        $record_action = $integration_details->record_action;
        $filter_criteria = $integration_details->filter_criteria;
        $field_mapping_json = $integration_details->field_mapping;
        $form_group_id = (int)$integration_details->form_group_id;
        $form_id = (string)$integration_details->form_id;

        $form_value = $form_group_id . '_' . $form_id;
        $account_id =  $integration_details->account_id;
        $form_fields = $IAFWZCAI_Form_FieldsInstance->getFormFields($form_group_id, $form_id);
        // Retrieve account details and access token
        $account_details = $iafwzcai_accountDBInstance->get_single_account_data($account_id);
        $accessToken = IAFWZCAI_Util::getAccessToken($account_id);
        if ($account_details) {
            $instance = new IAFWZCAI_PRODUCT($account_details, $accessToken);
            $module_list = $instance->get_campaign_lists();
            if (isset($module_list['error'])) {
                $error_message = $module_list['error'];
                $escaped_error_message = esc_js($error_message); // Ensure the error message is safely escaped

                // Register a dummy script handle to attach the inline script
                wp_register_script('iafwzcai-module-error-handler', false, [], '1.0', true);
                wp_enqueue_script('iafwzcai-module-error-handler');

                // Add inline JavaScript for the alert and redirection
                wp_add_inline_script('iafwzcai-module-error-handler', "
                    alert('{$escaped_error_message}');
                    window.location.href = '" . esc_url(admin_url('admin.php?page=integrate-with-zoho-campaigns&tab=accounts')) . "';
                ");
                return; // Ensure no further PHP code runs after the redirect
            }
            $crm_field_list = $instance->get_all_fields();
            //
            if (isset($crm_field_list['error'])) {
                $error_message = $crm_field_list['error'];
                // Escape the error message for JavaScript
                $escaped_error_message = esc_js($error_message);

                // Register a dummy script handle
                wp_register_script('iafwzcai-field-error-handler', false, [], '1.0', true);
                wp_enqueue_script('iafwzcai-field-error-handler');

                // Add the inline JavaScript for alert and redirect
                wp_add_inline_script('iafwzcai-field-error-handler', "
                        alert('{$escaped_error_message}');
                        window.location.href = '" . esc_url(admin_url('admin.php?page=integrate-with-zoho-campaigns&tab=setup')) . "';
                    ");

                return; // Ensure no further PHP code runs after the redirect
            }
            // Assuming $crm_field_list is fetched from $instance->get_module_fields($module_api_name)
            $crm_field_list = iafwzcai_categorizeCrmFields($crm_field_list);
        }
        // Output the script
        // Prepare the JavaScript variables
        $inline_js = "
            var setupID = " . wp_json_encode($setup_id) . ";
            var formFieldList = " . wp_json_encode($form_fields) . ";
            var crmFieldList = " . wp_json_encode($crm_field_list) . ";
            var existingFieldMapping = " . wp_json_encode($field_mapping_json) . ";
            var record_action = " . wp_json_encode($record_action) . ";
            var filterCriteria = " . wp_json_encode($filter_criteria) . ";
            jQuery(document).ready(function($) {
                $('#iafwzcai-setup-popupOverlay').toggleClass('show');
                iafwzcai_setExistingMapping();
            });
            ";

        // Register a dummy script handle to attach the inline script
        wp_register_script('iafwzcai-existing-mapping', false, ['jquery'], '1.0', true);
        wp_enqueue_script('iafwzcai-existing-mapping');

        // Add the inline JavaScript
        wp_add_inline_script('iafwzcai-existing-mapping', $inline_js);


?>
        <!-- Setup Popup Overlay -->
        <div id="iafwzcai-setup-popupOverlay" class="iafwzcai-setup-popup-overlay">
            <div class="iafwzcai-setup-popup-content">
                <!-- Close Button -->
                <span class="iafwzcai-setup-close" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=integrate-with-zoho-campaigns&tab=setup')); ?>'">&times;</span>

                <h3 class="iafwzcai-setup-popup-title">
                    <?php esc_html_e('Edit Integration', 'integrate-with-zoho-campaigns'); ?>
                </h3>

                <div class="iafwzcai-setup-menu">
                    <table class="iafwzcai-setup-table">
                        <!-- Integration Name -->
                        <tr class="iafwzcai-setup-row">
                            <td class="iafwzcai-setup-title"><?php esc_html_e('Integration Name:', 'integrate-with-zoho-campaigns'); ?>
                                <div class="iafwzcai-help-icon-wrapper">
                                    <span class="iafwzcai-help-icon">?</span>
                                    <div class="iafwzcai-help-tooltip">
                                        <p>A unique name to identify this integration.</p>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <input type="text" class="iafwzcai-setup-input" id="iafwzcai-setup-integrationName" placeholder="Enter integration name" value="<?php echo esc_attr($integration_name); ?>">
                            </td>
                        </tr>

                        <!-- Form Name -->
                        <tr class="iafwzcai-setup-row">
                            <td class="iafwzcai-setup-title"><?php esc_html_e('Select Form:', 'integrate-with-zoho-campaigns'); ?>
                                <div class="iafwzcai-help-icon-wrapper">
                                    <span class="iafwzcai-help-icon">?</span>
                                    <div class="iafwzcai-help-tooltip">
                                        <span>Select a form to integrate with Zoho Campaigns for data syncing.</span>
                                    </div>
                                </div>
                            </td>

                            <td>
                                <select name="formName" class="iafwzcai-setup-input" id="iafwzcai-setup-formName" onchange="iafwzcai_handleFormChange()">
                                    <option value=""><?php esc_html_e('Select', 'integrate-with-zoho-campaigns'); ?></option>
                                    <?php foreach ($form_group_list as $group_id => $group_data): ?>
                                        <optgroup label="<?php echo esc_attr($group_data['form_group_name']); ?>">
                                            <?php foreach ($group_data['forms'] as $form): ?>
                                                <option value="<?php echo esc_attr($group_id . '_' . $form['id']); ?>" <?php echo selected($form_value, $group_id . '_' . $form['id'], false); ?>>
                                                    <?php echo esc_html($form['name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>

                        <!-- Account Name -->
                        <tr class="iafwzcai-setup-row">
                            <td class="iafwzcai-setup-title"><?php esc_html_e('Select Account:', 'integrate-with-zoho-campaigns'); ?>
                                <div class="iafwzcai-help-icon-wrapper">
                                    <span class="iafwzcai-help-icon">?</span>
                                    <div class="iafwzcai-help-tooltip">
                                        <span>
                                            Select the Zoho account to push data.</span>
                                    </div>
                                </div>
                            </td>

                            <td>
                                <select name="accountName" class="iafwzcai-setup-input" id="iafwzcai-setup-accountName" onchange="iafwzcai_handleAccountChange()">
                                    <option value=""><?php esc_html_e('Select', 'integrate-with-zoho-campaigns'); ?></option>
                                    <?php foreach ($account_group_list as $account): ?>
                                        <option value="<?php echo esc_attr($account['account_id']); ?>" <?php echo selected($account_id, $account['account_id'], false); ?>>
                                            <?php echo esc_html($account['account_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>

                            </td>
                        </tr>

                        <!-- Module Name -->
                        <tr class="iafwzcai-setup-row">
                            <td class="iafwzcai-setup-title"><?php esc_html_e('Select List:', 'integrate-with-zoho-campaigns'); ?>
                                <div class="iafwzcai-help-icon-wrapper">
                                    <span class="iafwzcai-help-icon">?</span>
                                    <div class="iafwzcai-help-tooltip">
                                        <span>Choose the list in Zoho Campaigns to store the submitted data.</span>
                                    </div>
                                </div>
                            </td>

                            <td>

                                <select name="moduleName" class="iafwzcai-setup-input" id="iafwzcai-setup-moduleName" onchange="iafwzcai_handleModuleChange()">
                                    <option value=""><?php esc_html_e('Select', 'integrate-with-zoho-campaigns'); ?></option>
                                    <?php if (!empty($module_list)) : ?>
                                        <?php foreach ($module_list as $module) : ?>
                                            <option value="<?php echo esc_attr($module['listkey']); ?>" <?php echo selected($module_name, $module['listkey'], false); ?>>
                                                <?php echo esc_html($module['listname']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>


                            </td>

                        </tr>

                    </table>
                </div>

                <!-- Alert Text -->
                <div class="iafwzcai-setup-loading-text" style="display:none;">
                    <p></p>
                </div>
                <div id="iafwzcai-setup-fieldMapping-area">
                    <!-- Field Mapping -->
                    <div id="iafwzcai-setup-fieldMapping" style="margin-top:30px;" class="iafwzcai-setup-menu">
                        <table id="iafwzcai-setup-fieldMapping-table" class="iafwzcai-setup-table">
                            <thead>
                                <tr>
                                    <th class="iafwzcai-setup-th" width="43%"><?php esc_html_e('Select Form Fields', 'integrate-with-zoho-campaigns'); ?>
                                        <div class="iafwzcai-help-icon-wrapper">
                                            <span class="iafwzcai-help-icon">?</span>
                                            <div class="iafwzcai-help-tooltip">
                                                <span>Select the form field to map with Zoho Campaigns fields.</span>
                                            </div>
                                        </div>
                                    </th>
                                    <th class="iafwzcai-setup-th" width="43%"><?php esc_html_e('Select Campaigns Fields', 'integrate-with-zoho-campaigns'); ?>
                                        <div class="iafwzcai-help-icon-wrapper">
                                            <span class="iafwzcai-help-icon">?</span>
                                            <div class="iafwzcai-help-tooltip">
                                                <span>Choose the Zoho Campaigns field to map with the selected form field.</span>
                                            </div>
                                        </div>
                                    </th>
                                    <th class="iafwzcai-setup-th" style="border: none; background: none;"></th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>

                    <!-- Filter Container -->
                    <div class="iafwzcai-setup-filter-container">
                        <!-- Filter Header -->
                        <div class="iafwzcai-setup-filter-header" onclick="iafwzcai_toggleFilterArea()">
                            <p class="iafwzcai-setup-note-heading">Filter Criteria</p>
                            <span id="iafwzcai-setup-filter-arrow" class="iafwzcai-setup-filter-header-arrow">▼</span>
                        </div>

                        <!-- Filter Content -->
                        <div class="iafwzcai-setup-filter-content">
                            <div class="iafwzcai-setup-filter-clear-all" onclick="iafwzcai_clearAll()">Clear All</div>
                            <div id="iafwzcai-setup-filter-group-container" class="iafwzcai-setup-filter-group-container">
                                <div class="iafwzcai-setup-filter-group">
                                    <div class="iafwzcai-setup-filter-row">
                                        <select class="iafwzcai-setup-filter-field">
                                            <option value="" disabled selected>Select Field</option>
                                        </select>
                                        <select class="iafwzcai-setup-filter-condition">
                                            <option value="" disabled selected>Choose Condition</option>
                                            <option value="contains">Contains</option>
                                            <option value="not_contains">Does Not Contain</option>
                                            <option value="equals">Equals</option>
                                            <option value="not_equals">Does Not Equal</option>
                                            <option value="starts_with">Starts With</option>
                                            <option value="ends_with">Ends With</option>
                                            <option value="greater_than">Greater Than</option>
                                            <option value="less_than">Less Than</option>
                                            <option value="is_empty">Is Empty</option>
                                            <option value="is_not_empty">Is Not Empty</option>
                                        </select>
                                        <input type="text" class="iafwzcai-setup-filter-value" placeholder="Enter value" />
                                        <div class="iafwzcai-setup-filter-actions">
                                            <button class="iafwzcai-setup-filter-add-icon" onclick="iafwzcai_addFilter(this)">+</button>
                                            <button class="iafwzcai-setup-filter-close-icon" onclick="iafwzcai_removeFilter(this)">×</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Filter Container -->
                    <div class="iafwzcai-setup-note">
                        <p><strong>Note:</strong> If <em>Double Opt-in</em> is enabled, Zoho Campaigns will send a confirmation email to the user. The contact will be added to the list only after they confirm. To add contacts directly without confirmation, disable <em>Double Opt-in</em> under <strong>Settings &gt; General &gt; Manage Opt-in</strong>.</p>

                    </div>
                    <!-- Submit Button -->
                    <div class="iafwzcai-auth-button-container" id="iafwzcai-setup-button">
                        <button type="submit" class="iafwzcai-auth-button" onclick="iafwzcai_handleButtonClick(this)">
                            <?php esc_html_e('Save Mapping', 'integrate-with-zoho-campaigns'); ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>

<?php
    } catch (Throwable $e) {
    }
}
?>