<?php
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 = $integrazo_fwcrm_form_fieldMappingDBInstance->get_mapping($setup_id);

if ($integration_details) {
    $integrazo_fwcrm_form_formFieldsInstance = new integrazo_fwcrm_form_FormFields();
    try {
        //
        $integration_name = $integration_details->integration_name;
        $module_name = $integration_details->module_name;
        $record_action = $integration_details->record_action;
        $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 = $integrazo_fwcrm_form_formFieldsInstance->getFormFields($form_group_id, $form_id);
        // Retrieve account details and access token
        $account_details = $integrazo_fwcrm_form_accountDBInstance->get_single_account_data($account_id);

        if ($account_details) {
            $instance = new integrazo_fwcrm_form_API($account_details["instance_url"], $account_details["api_key"]);
            $crm_field_list = $instance->get_module_fields($module_name);
            //
            if (isset($crm_field_list['error'])) {
                $error_message = $crm_field_list['error'];
                // Escape the error message for JavaScript
                $escaped_error_message = addslashes($error_message);
                // Output the JavaScript alert and redirect
                echo '<script type="text/javascript">
                alert("' . esc_js($escaped_error_message) . '");
                window.location.href = "admin.php?page=crm-integration-freshworks-any-form&tab=setup";
            </script>';
                exit; // 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 = integrazo_fwcrm_form_categorizeCrmFields($crm_field_list);
        }
        // Output the script

        echo '<script type="text/javascript">
        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) . ';
        jQuery(document).ready(function($) {
            $("#integrazo_fwcrm_form-setup-popupOverlay").toggleClass("show");
           setExistingMapping();
        });
    </script>';




?>
        <!-- Setup Popup Overlay -->
        <div id="integrazo_fwcrm_form-setup-popupOverlay" class="integrazo_fwcrm_form-setup-popup-overlay">
            <div class="integrazo_fwcrm_form-setup-popup-content">
                <!-- Close Button -->
                <span class="integrazo_fwcrm_form-setup-close" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=crm-integration-freshworks-any-form&tab=setup')); ?>'">&times;</span>

                <h3 class="integrazo_fwcrm_form-setup-popup-title">
                    <?php esc_html_e('Edit Integration', 'crm-integration-freshworks-any-form'); ?>
                </h3>

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

                        <!-- Form Name -->
                        <tr class="integrazo_fwcrm_form-setup-row">
                            <td class="integrazo_fwcrm_form-setup-title"><?php esc_html_e('Select Form:', 'crm-integration-freshworks-any-form'); ?>
                                <div class="integrazo_fwcrm_form-help-icon-wrapper">
                                    <span class="integrazo_fwcrm_form-help-icon">?</span>
                                    <div class="integrazo_fwcrm_form-help-tooltip">
                                        <span>Select a form to integrate with Freshworks CRM for data syncing.</span>
                                    </div>
                                </div>
                            </td>

                            <td>
                                <select name="formName" class="integrazo_fwcrm_form-setup-input" id="integrazo_fwcrm_form-setup-formName" onchange="integrazo_fwcrm_form_handleFormChange()">
                                    <option value=""><?php esc_html_e('Select', 'crm-integration-freshworks-any-form'); ?></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="integrazo_fwcrm_form-setup-row">
                            <td class="integrazo_fwcrm_form-setup-title"><?php esc_html_e('Select Account:', 'crm-integration-freshworks-any-form'); ?>
                                <div class="integrazo_fwcrm_form-help-icon-wrapper">
                                    <span class="integrazo_fwcrm_form-help-icon">?</span>
                                    <div class="integrazo_fwcrm_form-help-tooltip">
                                        <span>
                                            Select the Freshworks CRM account to push data.</span>
                                    </div>
                                </div>
                            </td>

                            <td>
                                <select name="accountName" class="integrazo_fwcrm_form-setup-input" id="integrazo_fwcrm_form-setup-accountName" onchange="integrazo_fwcrm_form_handleAccountChange()">
                                    <option value=""><?php esc_html_e('Select', 'crm-integration-freshworks-any-form'); ?></option>
                                    <?php
                                    // Iterate through the account list and add options
                                    foreach ($account_group_list as $account): ?>
                                        <option value="<?php echo esc_attr($account['account_id']); ?>" <?php echo selected($account['account_id'], $account_id, false); ?>>
                                            <?php echo esc_html($account['account_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>


                            </td>
                        </tr>

                        <!-- Module Name -->
                        <tr class="integrazo_fwcrm_form-setup-row">
                            <td class="integrazo_fwcrm_form-setup-title"><?php esc_html_e('Select Module:', 'crm-integration-freshworks-any-form'); ?>
                                <div class="integrazo_fwcrm_form-help-icon-wrapper">
                                    <span class="integrazo_fwcrm_form-help-icon">?</span>
                                    <div class="integrazo_fwcrm_form-help-tooltip">
                                        <span>Choose the module in Freshworks CRM to store the submitted data.</span>
                                    </div>
                                </div>
                            </td>

                            <td>
                                <select name="moduleName" class="integrazo_fwcrm_form-setup-input" id="integrazo_fwcrm_form-setup-moduleName" onchange="integrazo_fwcrm_form_handleModuleChange()">
                                    <option value=""><?php esc_html_e('Select', 'crm-integration-freshworks-any-form'); ?></option>
                                    <option value="contacts" <?php echo selected('contacts', $module_name, false); ?>><?php esc_html_e('Leads', 'crm-integration-freshworks-any-form'); ?></option>
                                    <option value="sales_accounts" <?php echo selected('sales_accounts', $module_name, false); ?>><?php esc_html_e('Accounts', 'crm-integration-freshworks-any-form'); ?></option>
                                </select>


                            </td>
                        </tr>

                    </table>
                </div>

                <!-- Alert Text -->
                <div class="integrazo_fwcrm_form-setup-loading-text" style="display:none;">
                    <p></p>

                </div>
                <div id="integrazo_fwcrm_form-setup-fieldMapping-area">
                    <!-- Field Mapping -->
                    <div id="integrazo_fwcrm_form-setup-fieldMapping" style="margin-top:30px;" class="integrazo_fwcrm_form-setup-menu">
                        <table id="integrazo_fwcrm_form-setup-fieldMapping-table" class="integrazo_fwcrm_form-setup-table">
                            <thead>
                                <tr>
                                    <th class="integrazo_fwcrm_form-setup-th" width="43%"><?php esc_html_e('Select Form Fields', 'crm-integration-freshworks-any-form'); ?>
                                        <div class="integrazo_fwcrm_form-help-icon-wrapper">
                                            <span class="integrazo_fwcrm_form-help-icon">?</span>
                                            <div class="integrazo_fwcrm_form-help-tooltip">
                                                <span>Select the form field to map with Freshworks CRM fields.</span>
                                            </div>
                                        </div>
                                    </th>
                                    <th class="integrazo_fwcrm_form-setup-th" width="43%"><?php esc_html_e('Select CRM Fields', 'crm-integration-freshworks-any-form'); ?>
                                        <div class="integrazo_fwcrm_form-help-icon-wrapper">
                                            <span class="integrazo_fwcrm_form-help-icon">?</span>
                                            <div class="integrazo_fwcrm_form-help-tooltip">
                                                <span>Choose the Freshworks CRM field to map with the selected form field.</span>
                                            </div>
                                        </div>
                                    </th>
                                    <th class="integrazo_fwcrm_form-setup-th" style="border: none; background: none;"></th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>

                    <!-- Action -->
                    <div class="integrazo_fwcrm_form-setup-action-container">
                        <div class="integrazo_fwcrm_form-setup-action-popup-container">
                            <div style="padding-left: 22px; padding-top: 20px;">
                                <div>
                                    <p class="integrazo_fwcrm_form-setup-action-heading"><?php esc_html_e('Choose an action for CRM records:', 'crm-integration-freshworks-any-form'); ?></p>
                                    <div class="integrazo_fwcrm_form-help-icon-wrapper">
                                        <span class="integrazo_fwcrm_form-help-icon">?</span>
                                        <div class="integrazo_fwcrm_form-help-tooltip">
                                            <span>Choose how to process form submissions in Freshworks CRM, such as creating new records or updating existing ones.</span>
                                        </div>
                                    </div>
                                </div>
                                <div style="padding: 9px;">
                                    <label class="integrazo_fwcrm_form-setup-action-label">
                                        <input type="radio" name="crm_action" value="add_ignore_existing">
                                        <?php esc_html_e('Always add as a new record, ignoring existing records', 'crm-integration-freshworks-any-form'); ?>
                                    </label>
                                    <label class="integrazo_fwcrm_form-setup-action-label">
                                        <input type="radio" name="crm_action" value="add_or_update">
                                        <?php esc_html_e('Add if record is not existing, or update if it already exists', 'crm-integration-freshworks-any-form'); ?>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>



                    <!-- Submit Button -->
                    <div class="integrazo_fwcrm_form-auth-button-container" id="integrazo_fwcrm_form-setup-button" style="margin-top: 40px;">
                        <button type="submit" class="integrazo_fwcrm_form-auth-button" onclick="integrazo_fwcrm_form_handleButtonClick(this)">
                            <?php esc_html_e('Save Mapping', 'crm-integration-freshworks-any-form'); ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>

<?php
    } catch (Throwable $e) {
        // Display the error in a div
    }
}
?>