<?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
$iafwzdesk_setup_id = isset($_GET['setup_id']) ? intval($_GET['setup_id']) : 0;
// Fetch integration details using the sanitized setup ID
$iafwzdesk_integration_details = $IAFWZDESK_Field_MappingDBInstance->get_mapping($iafwzdesk_setup_id);
if ($iafwzdesk_integration_details) {
    $IAFWZDESK_Form_FieldsInstance = new IAFWZDESK_Form_Fields();
    try {
        //
        $iafwzdesk_integration_name = $iafwzdesk_integration_details->integration_name;
        $iafwzdesk_module_name = $iafwzdesk_integration_details->module_name;
        $iafwzdesk_record_action = $iafwzdesk_integration_details->record_action;
        $iafwzdesk_filter_criteria = $iafwzdesk_integration_details->filter_criteria;
        $iafwzdesk_field_mapping_json = $iafwzdesk_integration_details->field_mapping;
        $iafwzdesk_form_group_id = (int)$iafwzdesk_integration_details->form_group_id;
        $iafwzdesk_form_id = (string)$iafwzdesk_integration_details->form_id;

        $iafwzdesk_form_value = $iafwzdesk_form_group_id . '_' . $iafwzdesk_form_id;
        $iafwzdesk_account_id =  $iafwzdesk_integration_details->account_id;
        $iafwzdesk_form_fields = $IAFWZDESK_Form_FieldsInstance->getFormFields($iafwzdesk_form_group_id, $iafwzdesk_form_id);
        // Retrieve account details and access token
        $iafwzdesk_account_details = $iafwzdesk_accountDBInstance->get_single_account_data($iafwzdesk_account_id);
        $iafwzdesk_accessToken = IAFWZDESK_Util::getAccessToken($iafwzdesk_account_id);
        if ($iafwzdesk_account_details) {
            $iafwzdesk_instance = new IAFWZDESK_PRODUCT($iafwzdesk_account_details, $iafwzdesk_accessToken);
            $iafwzdesk_module_list = $iafwzdesk_instance->get_desk_departments();
            if (isset($iafwzdesk_module_list['error'])) {
                $iafwzdesk_error_message = $iafwzdesk_module_list['error'];
                $iafwzdesk_escaped_error_message = esc_js($iafwzdesk_error_message); // Ensure the error message is safely escaped

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

                // Add inline JavaScript for the alert and redirection
                wp_add_inline_script('iafwzdesk-module-error-handler', "
                    alert('{$iafwzdesk_escaped_error_message}');
                    window.location.href = '" . esc_url(admin_url('admin.php?page=integrate-with-zoho-desk&tab=accounts')) . "';
                ");
                return; // Ensure no further PHP code runs after the redirect
            }
            $iafwzdesk_crm_field_list = $iafwzdesk_instance->get_desk_departments_fields($iafwzdesk_module_name);
            //
            if (isset($iafwzdesk_crm_field_list['error'])) {
                $iafwzdesk_error_message = $iafwzdesk_crm_field_list['error'];
                // Escape the error message for JavaScript
                $iafwzdesk_escaped_error_message = esc_js($iafwzdesk_error_message);

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

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

                return; // Ensure no further PHP code runs after the redirect
            }
            // Assuming $iafwzdesk_crm_field_list is fetched from $iafwzdesk_instance->get_module_fields($module_api_name)
            $iafwzdesk_crm_field_list = iafwzdesk_categorizeCrmFields($iafwzdesk_crm_field_list);
        }
        // Output the script
        // Prepare the JavaScript variables
        $iafwzdesk_inline_js = "
            var setupID = " . wp_json_encode($iafwzdesk_setup_id) . ";
            var formFieldList = " . wp_json_encode($iafwzdesk_form_fields) . ";
            var crmFieldList = " . wp_json_encode($iafwzdesk_crm_field_list) . ";
            var existingFieldMapping = " . wp_json_encode($iafwzdesk_field_mapping_json) . ";
            var record_action = " . wp_json_encode($iafwzdesk_record_action) . ";
            var filterCriteria = " . wp_json_encode($iafwzdesk_filter_criteria) . ";
            jQuery(document).ready(function($) {
                $('#iafwzdesk-setup-popupOverlay').toggleClass('show');
                iafwzdesk_setExistingMapping();
            });
            ";

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

        // Add the inline JavaScript
        wp_add_inline_script('iafwzdesk-existing-mapping', $iafwzdesk_inline_js);


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

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

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

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

                            <td>
                                <select name="formName" class="iafwzdesk-setup-input" id="iafwzdesk-setup-formName" onchange="iafwzdesk_handleFormChange()">
                                    <option value=""><?php esc_html_e('Select', 'integrate-with-zoho-desk'); ?></option>
                                    <?php foreach ($iafwzdesk_form_group_list as $iafwzdesk_group_id => $iafwzdesk_group_data): ?>
                                        <optgroup label="<?php echo esc_attr($iafwzdesk_group_data['form_group_name']); ?>">
                                            <?php foreach ($iafwzdesk_group_data['forms'] as $iafwzdesk_form): ?>
                                                <option value="<?php echo esc_attr($iafwzdesk_group_id . '_' . $iafwzdesk_form['id']); ?>" <?php echo selected($iafwzdesk_form_value, $iafwzdesk_group_id . '_' . $iafwzdesk_form['id'], false); ?>>
                                                    <?php echo esc_html($iafwzdesk_form['name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>

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

                            <td>
                                <select name="accountName" class="iafwzdesk-setup-input" id="iafwzdesk-setup-accountName" onchange="iafwzdesk_handleAccountChange()">
                                    <option value=""><?php esc_html_e('Select', 'integrate-with-zoho-desk'); ?></option>
                                    <?php foreach ($iafwzdesk_account_group_list as $iafwzdesk_account): ?>
                                        <option value="<?php echo esc_attr($iafwzdesk_account['account_id']); ?>" <?php echo selected($iafwzdesk_account_id, $iafwzdesk_account['account_id'], false); ?>>
                                            <?php echo esc_html($iafwzdesk_account['account_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>

                            </td>
                        </tr>

                        <!-- Module Name -->
                        <tr class="iafwzdesk-setup-row">
                            <td class="iafwzdesk-setup-title"><?php esc_html_e('Select Department:', 'integrate-with-zoho-desk'); ?>
                                <div class="iafwzdesk-help-icon-wrapper">
                                    <span class="iafwzdesk-help-icon">?</span>
                                    <div class="iafwzdesk-help-tooltip">
                                        <span>Select the Zoho Desk department where the ticket should be created.</span>
                                    </div>
                                </div>
                            </td>

                            <td>
                                <?php
                                ?>
                                <select name="moduleName" class="iafwzdesk-setup-input" id="iafwzdesk-setup-moduleName" onchange="iafwzdesk_handleModuleChange()">
                                    <option value=""><?php esc_html_e('Select', 'integrate-with-zoho-desk'); ?></option>
                                    <?php if (!empty($iafwzdesk_module_list)) : ?>
                                        <?php foreach ($iafwzdesk_module_list as $iafwzdesk_module) : ?>
                                            <option value="<?php echo esc_attr($iafwzdesk_module['id']); ?>" <?php echo selected($iafwzdesk_module_name, $iafwzdesk_module['id'], false); ?>>
                                                <?php echo esc_html($iafwzdesk_module['name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>



                            </td>

                        </tr>

                    </table>
                </div>

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

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

                        <!-- Filter Content -->
                        <div class="iafwzdesk-setup-filter-content">
                            <div class="iafwzdesk-setup-filter-clear-all" onclick="iafwzdesk_clearAll()"><?php esc_html_e('Clear All', 'integrate-with-zoho-desk'); ?></div>
                            <div id="iafwzdesk-setup-filter-group-container" class="iafwzdesk-setup-filter-group-container">
                                <div class="iafwzdesk-setup-filter-group">
                                    <div class="iafwzdesk-setup-filter-row">
                                        <select class="iafwzdesk-setup-filter-field">
                                            <option value="" disabled selected><?php esc_html_e('Select Field', 'integrate-with-zoho-desk'); ?></option>
                                        </select>
                                        <select class="iafwzdesk-setup-filter-condition">
                                            <option value="" disabled selected><?php esc_html_e('Choose Condition', 'integrate-with-zoho-desk'); ?></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="iafwzdesk-setup-filter-value" placeholder="<?php esc_attr_e('Enter value', 'integrate-with-zoho-desk'); ?>" />
                                        <div class="iafwzdesk-setup-filter-actions">
                                            <button class="iafwzdesk-setup-filter-add-icon" onclick="iafwzdesk_addFilter(this)">+</button>
                                            <button class="iafwzdesk-setup-filter-close-icon" onclick="iafwzdesk_removeFilter(this)">×</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Filter Container -->
                    <div class="iafwzdesk-setup-note">

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

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