<?php
// Exit if accessed directly to ensure security.
if (!defined('ABSPATH')) {
    exit;
}

?>
<div id="iafwzdesk-content-accounts" class="iafwzdesk-tab-content" style="display:none;">

    <span class="iafwzdesk-span-header"><?php esc_html_e('Zoho Desk Accounts', 'integrate-with-zoho-desk'); ?></span>

    <div class="iafwzdesk-help-icon-wrapper">
        <span class="iafwzdesk-help-icon">?</span>
        <div class="iafwzdesk-help-tooltip">
            <p>Connect and manage your Zoho Desk accounts from this page.</p>
        </div>
    </div>
<?php if ( $iafwzdesk_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 Zoho account, continue to the Setup tab to create integrations.', 'integrate-with-zoho-desk'),
            array( 'b' => array() )
        );
        ?>
    </p>
</div>

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

        // Delete the transient after displaying the message.
        delete_transient('iafwzdesk_account_message');
    }

    // Display the accounts table.
    $iafwzdesk_accounts_table = new IAFWZDESK_Accounts_Extend();
    $iafwzdesk_accounts_table->prepare_items(); // Prepare account table items
    $iafwzdesk_accounts_table->display();       // Display account table
    if (!$session) {
        include "other-plugins.php";
    }

    ?>
</div>

<?php

$iafwzdesk_account_count = $iafwzdesk_accountDBInstance->get_total_accounts() + 1;

// Retrieve account ID and action if present
$iafwzdesk_account_id = null;
$iafwzdesk_account_action = null;
if (isset($_GET['ac_action'], $_GET['ac_id'])) {
    // Verify the nonce if the required parameters are present.
    if (isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'iafwzdesk_edit_account_nonce')) {
        // Nonce is valid, proceed with the action.
        $iafwzdesk_account_id = intval($_GET['ac_id']);
        $iafwzdesk_account_action = sanitize_text_field(wp_unslash($_GET['ac_action']));

        // Your logic here.
    } else {
        // Handle invalid nonce.
        wp_die(
            esc_html__('Unauthorized request. Please try again.', 'integrate-with-zoho-desk')
        );
    }
}


// Get authentication data from transient
$iafwzdesk_auth_data = get_option('iafwzdesk_account_data');
if (!$iafwzdesk_account_id) {
    $iafwzdesk_account_id = $iafwzdesk_auth_data['account_id'] ?? null;
}
// Initialize default variables
$iafwzdesk_message = '';
$iafwzdesk_is_success = null;
$iafwzdesk_account_name = $iafwzdesk_data_center = '';
// Determine account details or handle error messages based on available data
if ($iafwzdesk_account_id) {
    if ($iafwzdesk_auth_data) {
        // If auth data is present, use it and delete the transient
        $iafwzdesk_is_success = false;
        $iafwzdesk_account_name = $iafwzdesk_auth_data['account_name'] ?? '';
        $iafwzdesk_data_center = $iafwzdesk_auth_data['data_center'] ?? '';
        $iafwzdesk_message = $iafwzdesk_auth_data['error_message'] ?? '';
       delete_option('iafwzdesk_account_data');

    } else {
        // Fetch account details based on account ID
        $iafwzdesk_account_details = $iafwzdesk_accountDBInstance->get_single_account_data($iafwzdesk_account_id);
        $iafwzdesk_account_name = $iafwzdesk_account_details['account_name'] ?? '';
        $iafwzdesk_data_center = $iafwzdesk_account_details['data_center'] ?? '';
    }
} elseif ($iafwzdesk_auth_data) {
    // If no account ID but auth data is present, use auth data
    $iafwzdesk_is_success = false;
    $iafwzdesk_account_name = $iafwzdesk_auth_data['account_name'] ?? '';
    $iafwzdesk_data_center = $iafwzdesk_auth_data['data_center'] ?? '';
    $iafwzdesk_message = $iafwzdesk_auth_data['error_message'] ?? '';
   delete_option('iafwzdesk_account_data');

} else {
    // Default account name if no account ID or auth data is provided
    $iafwzdesk_account_name = 'Account #' . $iafwzdesk_account_count;
}
?>

<?php if ($iafwzdesk_message || $iafwzdesk_account_action): ?>
    <?php
    // Register a dummy script handle
    wp_register_script('iafwzdesk-auth-popup', false, ['jquery'], '1.0', true);
    wp_enqueue_script('iafwzdesk-auth-popup');

    // Add inline JavaScript to show the popup
    wp_add_inline_script('iafwzdesk-auth-popup', "
            jQuery(document).ready(function() {
                jQuery('#iafwzdesk-auth-popupOverlay').addClass('show');
            });
        ");

    ?>
<?php endif; ?>



<!-- Popup Overlay -->
<div id="iafwzdesk-auth-popupOverlay" class="iafwzdesk-auth-popup-overlay">
    <div class="iafwzdesk-auth-popup-content">
        <span class="iafwzdesk-auth-close" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=integrate-with-zoho-desk&tab=accounts')); ?>'">&times;</span>
        <h3 class="iafwzdesk-auth-popup-title"><?php esc_html_e('Account Setup', 'integrate-with-zoho-desk'); ?></h3>
        <form class="iafwzdesk-auth-form" id="iafwzdesk-auth-form" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post">
            <?php wp_nonce_field('iafwzdesk_authenticate', 'iafwzdesk_auth_nonce'); ?>
            <input type="hidden" name="action" value="iafwzdesk_authenticate">
            <?php if ($iafwzdesk_account_id) : ?>
                <input type="hidden" name="account_id" value="<?php echo esc_attr($iafwzdesk_account_id); ?>">
            <?php endif; ?>
            <?php if ($iafwzdesk_message) : ?>
                <div id="iafwzdesk-auth-message" class="iafwzdesk-auth-message <?php echo esc_attr($iafwzdesk_is_success ? 'iafwzdesk-auth-success' : 'iafwzdesk-auth-error'); ?>">
                    <?php echo esc_html($iafwzdesk_message); ?>
                </div>
            <?php endif; ?>

            <label for="accountName" class="iafwzdesk-auth-label"><?php esc_html_e('Account Name', 'integrate-with-zoho-desk'); ?><span> *</span>
                <div class="iafwzdesk-help-icon-wrapper">
                    <span class="iafwzdesk-help-icon">?</span>
                    <div class="iafwzdesk-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($iafwzdesk_account_name); ?>" id="accountName" name="accountName" class="iafwzdesk-auth-input iafwzdesk-setup-fm-mandatory" placeholder="<?php esc_attr_e('Enter your account name', 'integrate-with-zoho-desk'); ?>" required>

            <label for="dataCenter" class="iafwzdesk-auth-label"><?php esc_html_e('Data Center', 'integrate-with-zoho-desk'); ?><span> *</span>
                <div class="iafwzdesk-help-icon-wrapper">
                    <span class="iafwzdesk-help-icon">?</span>
                    <div class="iafwzdesk-help-tooltip">
                        <div class="page-title" style="text-decoration: underline;">Data Center</div>
                        <p>Choose the Zoho data center based on your account's location (e.g., US, EU, IN).</p>
                    </div>
                </div>
            </label>
            <select id="dataCenter" name="dataCenter" class="iafwzdesk-auth-select iafwzdesk-setup-fm-mandatory" required>
                <?php
                $iafwzdesk_data_centers = [
                    'com' => 'zoho.com',
                    'in' => 'zoho.in',
                    'eu' => 'zoho.eu',
                    'uk' => 'zoho.uk',
                    'jp' => 'zoho.jp',
                    'ca' => 'zohocloud.ca',
                    'sa' => 'zoho.sa',
                    'com.cn' => 'zoho.com.cn',
                    'com.au' => 'zoho.com.au',
                ];
                foreach ($iafwzdesk_data_centers as $iafwzdesk_value => $iafwzdesk_label) :
                ?>
                    <option value="<?php echo esc_attr($iafwzdesk_value); ?>" <?php selected($iafwzdesk_data_center, $iafwzdesk_value); ?>>
                        <?php echo esc_html($iafwzdesk_label); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <div class="iafwzdesk-auth-button-container">
                <button type="submit" class="iafwzdesk-auth-button" name="<?php echo $iafwzdesk_account_id ? 'save_reauth' : 'save_auth'; ?>">
                    <?php echo $iafwzdesk_account_id ? esc_html__('Save & Re-auth', 'integrate-with-zoho-desk') : esc_html__('Authenticate', 'integrate-with-zoho-desk'); ?>
                </button>
            </div>

        </form>

    </div>
</div>
