<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
// Account Tab Content
?>
<div id="integrazo_fwcrm_form-content-accounts" class="integrazo_fwcrm_form-tab-content" style="display:none;">

    <span class="integrazo_fwcrm_form-span-header"><?php esc_html_e('Freshworks Account', 'crm-integration-freshworks-any-form'); ?></span>

    <div class="integrazo_fwcrm_form-help-icon-wrapper">
        <span class="integrazo_fwcrm_form-help-icon">?</span>
        <div class="integrazo_fwcrm_form-help-tooltip">
            <p>Connect and manage your Freshworks CRM accounts from this page.</p>
        </div>
    </div>

<?php if ( $integrazo_fwcrm_form_accountDBInstance->get_total_accounts() == 0 ) : ?>

<div class="notice notice-error">
    <p>
        <?php 
        echo wp_kses(
            __('Start by clicking <b>Add Account</b>. After connecting your Freshworks account, continue to the Setup tab to create integrations.', 'crm-integration-freshworks-any-form'),
            array( 'b' => array() )
        );
        ?>
    </p>
</div>

<?php endif; ?>

    <?php
    $message = get_transient('integrazo_fwcrm_form_account_message');
    // If there is a message, display it as an admin notice.
    if ($message) {
        echo '<div class="notice notice-success is-dismissible">
                    <p>' . esc_html($message) . '</p>
                  </div>';

        // Delete the transient after displaying the message.
        delete_transient('integrazo_fwcrm_form_account_message');
    } ?>
    <?php
    // Add a nonce field for security
    wp_nonce_field('integrazo_fwcrm_form_account_form_action', 'integrazo_fwcrm_form_account_form_action_nonce');
    ?>
    <input type="hidden" name="page" value="crm-integration-freshworks-any-form">
    <input type="hidden" name="tab" value="account">
    <?php
    // Display the accounts table.
    $accounts_table = new integrazo_fwcrm_form_Accounts();
    $accounts_table->prepare_items(); // Prepare account table items
    $accounts_table->display();       // Display account table

    if (!$session) {
        include "other-plugins.php";
    }

    ?>
    </form>
</div>

<?php

$account_count = $integrazo_fwcrm_form_accountDBInstance->get_total_accounts() + 1;

// Retrieve account ID and action if present
$account_id = null;
$account_action = null;
if (
    isset($_GET['page'], $_GET['tab'], $_GET['ac_action'], $_GET['ac_id']) &&
    $_GET['page'] === 'crm-integration-freshworks-any-form' &&
    $_GET['tab'] === 'accounts' &&
    $_GET['ac_action'] === 'edit'
) {
    // Verify the nonce if the required parameters are present.
    if (isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'integrazo_fwcrm_form_edit_account_nonce')) {

        // Nonce is valid, proceed with the action.
        $account_id = intval($_GET['ac_id']);
        $account_action = sanitize_text_field(wp_unslash($_GET['ac_action']));

        // Your logic here.
    } else {
        // Handle invalid nonce.
        wp_die(
            esc_html__('Security verification failed. Please try again.', 'crm-integration-freshworks-any-form')
        );
    }
}


// Get authentication data from transient
$auth_data = get_transient('integrazo_fwcrm_form_auth_data');

// Initialize default variables
$message = '';
$is_success = null;
$account_name = $instance_url = $api_key = '';

// Determine account details or handle error messages based on available data
if ($account_id) {
    if ($auth_data) {
        $is_success = false;
        $account_name = $auth_data['account_name'] ?? '';
        $instance_url = $auth_data['instance_url'] ?? '';
        $api_key = $auth_data['api_key'] ?? '';
        $message = $auth_data['message'] ?? '';
        delete_transient('integrazo_fwcrm_form_auth_data');
    } else {
        // Fetch account details based on account ID
        $account_details = $integrazo_fwcrm_form_accountDBInstance->get_single_account_data($account_id);
        $account_name = $account_details['account_name'] ?? '';
        $instance_url = $account_details['instance_url'] ?? '';
        $api_key = $account_details['api_key'] ?? '';
    }
} elseif ($auth_data) {
    // If no account ID but auth data is present, use auth data
    $is_success = false;
    $account_name = $auth_data['account_name'] ?? '';
    $instance_url = $auth_data['instance_url'] ?? '';
    $api_key = $auth_data['api_key'] ?? '';
    $message = $auth_data['message'] ?? '';
    delete_transient('integrazo_fwcrm_form_auth_data');
} else {
    // Default account name if no account ID or auth data is provided
    $account_name = 'Account #' . $account_count;
}
?>

<?php if ($message || $account_action): ?>
    <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery("#integrazo_fwcrm_form-auth-popupOverlay").addClass("show");
        });
    </script>
<?php endif; ?>


<!-- Popup Overlay -->
<div id="integrazo_fwcrm_form-auth-popupOverlay" class="integrazo_fwcrm_form-auth-popup-overlay">
    <div class="integrazo_fwcrm_form-auth-popup-content">
        <span class="integrazo_fwcrm_form-auth-close" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=crm-integration-freshworks-any-form&tab=accounts')); ?>'">&times;</span>
        <h3 class="integrazo_fwcrm_form-auth-popup-title"><?php esc_html_e('Account Setup', 'crm-integration-freshworks-any-form'); ?></h3>
        <form class="integrazo_fwcrm_form-auth-form" id="integrazo_fwcrm_form-auth-form" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post">
            <?php wp_nonce_field('integrazo_fwcrm_form_account_authenticate', 'integrazo_fwcrm_form_account_authenticate_nonce'); ?>
            <input type="hidden" name="action" value="integrazo_fwcrm_form_account_authenticate">
            <?php if ($account_id) : ?>
                <input type="hidden" name="account_id" value="<?php echo esc_attr($account_id); ?>">
            <?php endif; ?>
            <?php if ($message) : ?>
                <div id="integrazo_fwcrm_form-auth-message" class="integrazo_fwcrm_form-auth-message <?php echo $is_success ? 'integrazo_fwcrm_form-auth-success' : 'integrazo_fwcrm_form-auth-error'; ?>">
                    <?php echo esc_html($message); ?>
                </div>
            <?php endif; ?>

            <label for="account_name" class="integrazo_fwcrm_form-auth-label"><?php esc_html_e('Account Name', 'crm-integration-freshworks-any-form'); ?><span> *</span>
                <div class="integrazo_fwcrm_form-help-icon-wrapper">
                    <span class="integrazo_fwcrm_form-help-icon">?</span>
                    <div class="integrazo_fwcrm_form-help-tooltip">
                        <div class="page-title" style="text-decoration: underline;">Account Name</div>
                        <p>A unique name to identify this account.</p>
                    </div>
                </div>
            </label>
            <input type="text" value="<?php echo esc_attr($account_name); ?>" id="account_name" name="account_name" class="integrazo_fwcrm_form-auth-input integrazo_fwcrm_form-setup-fm-mandatory" placeholder="<?php esc_attr_e('Enter account name', 'crm-integration-freshworks-any-form'); ?>" required>

            <label for="instance_url" class="integrazo_fwcrm_form-auth-label"><?php esc_html_e('Instance URL', 'crm-integration-freshworks-any-form'); ?><span> *</span>
                <div class="integrazo_fwcrm_form-help-icon-wrapper">
                    <span class="integrazo_fwcrm_form-help-icon">?</span>
                    <div class="integrazo_fwcrm_form-help-tooltip">
                        <div class="page-title" style="text-decoration: underline;">Instance URL</div>
                        <p>If you're unsure of your Freshworks CRM instance URL, log in to your Freshworks account. You can find the URL in your browser's address bar, typically formatted as https://yourcompanyname.myfreshworks.com. Replace 'yourcompanyname' with your specific instance name.</p>
                    </div>
                </div>
            </label>
            <input type="text" value="<?php echo esc_attr($instance_url); ?>" id="instance_url" name="instance_url" class="integrazo_fwcrm_form-auth-input integrazo_fwcrm_form-setup-fm-mandatory" placeholder="<?php esc_attr_e('Enter your account instance URL', 'crm-integration-freshworks-any-form'); ?>" required>


            <label for="api_key" class="integrazo_fwcrm_form-auth-label"><?php esc_html_e('API Key', 'crm-integration-freshworks-any-form'); ?><span> *</span>
                <div class="integrazo_fwcrm_form-help-icon-wrapper">
                    <span class="integrazo_fwcrm_form-help-icon">?</span>
                    <div class="integrazo_fwcrm_form-help-tooltip">
                        <div class="page-title" style="text-decoration: underline;">API Key</div>
                        <p>Enter your Freshworks CRM API key to enable integration. You can generate or locate your API key by logging into your Freshworks account, navigating to the API settings under your profile or account settings, and copying the key provided.</p>
                    </div>
                </div>
            </label>
            <input type="text" value="<?php echo esc_attr($api_key); ?>" id="api_key" name="api_key" class="integrazo_fwcrm_form-auth-input integrazo_fwcrm_form-setup-fm-mandatory" placeholder="<?php esc_attr_e('Enter your account API key', 'crm-integration-freshworks-any-form'); ?>" required>


            <div class="integrazo_fwcrm_form-auth-button-container">
                <button type="submit" class="integrazo_fwcrm_form-auth-button" name="<?php echo $account_id ? 'save_reauth' : 'save_auth'; ?>">
                    <?php echo $account_id ? esc_html__('Save & Re-auth', 'crm-integration-freshworks-any-form') : esc_html__('Authenticate', 'crm-integration-freshworks-any-form'); ?>
                </button>
            </div>

        </form>
    </div>
</div>