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

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

    <span class="iafwzcai-span-header"><?php esc_html_e('Zoho Campaigns Accounts', 'integrate-with-zoho-campaigns'); ?></span>

    <div class="iafwzcai-help-icon-wrapper">
        <span class="iafwzcai-help-icon">?</span>
        <div class="iafwzcai-help-tooltip">
            <p>Connect and manage your Zoho Campaigns accounts from this page.</p>
        </div>
    </div>
<?php if ( $iafwzcai_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-campaigns'),
            array( 'b' => array() )
        );
        ?>
    </p>
</div>

<?php endif; ?>

    <?php
    $message = get_transient('iafwzcai_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('iafwzcai_account_message');
    }

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

    ?>
</div>

<?php

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

// Retrieve account ID and action if present
$account_id = null;
$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'])), 'iafwzcai_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__('Unauthorized request. Please try again.', 'integrate-with-zoho-campaigns')
        );
    }
}

$auth_data = get_option('iafwzcai_account_data');
if (!$account_id) {
    $account_id = $auth_data['account_id'] ?? null;
}
// Initialize default variables
$message = '';
$is_success = null;
$account_name = $data_center = '';
// Determine account details or handle error messages based on available data
if ($account_id) {
    if ($auth_data) {
        // If auth data is present, use it and delete the transient
        $is_success = false;
        $account_name = $auth_data['account_name'] ?? '';
        $data_center = $auth_data['data_center'] ?? '';
        $message = $auth_data['error_message'] ?? '';
        delete_option('iafwzcai_account_data');

    } else {
        // Fetch account details based on account ID
        $account_details = $iafwzcai_accountDBInstance->get_single_account_data($account_id);
        $account_name = $account_details['account_name'] ?? '';
        $data_center = $account_details['data_center'] ?? '';
    }
} elseif ($auth_data) {
    // If no account ID but auth data is present, use auth data
    $is_success = false;
    $account_name = $auth_data['account_name'] ?? '';
    $data_center = $auth_data['data_center'] ?? '';
    $message = $auth_data['error_message'] ?? '';
    delete_option('iafwzcai_account_data');

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

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

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

    ?>
<?php endif; ?>



<!-- Popup Overlay -->
<div id="iafwzcai-auth-popupOverlay" class="iafwzcai-auth-popup-overlay">
    <div class="iafwzcai-auth-popup-content">
        <span class="iafwzcai-auth-close" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=integrate-with-zoho-campaigns&tab=accounts')); ?>'">&times;</span>
        <h3 class="iafwzcai-auth-popup-title"><?php esc_html_e('Account Setup', 'integrate-with-zoho-campaigns'); ?></h3>
        <form class="iafwzcai-auth-form" id="iafwzcai-auth-form" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post">
            <?php wp_nonce_field('iafwzcai_authenticate', 'iafwzcai_auth_nonce'); ?>
            <input type="hidden" name="action" value="iafwzcai_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="iafwzcai-auth-message" class="iafwzcai-auth-message <?php echo $is_success ? 'iafwzcai-auth-success' : 'iafwzcai-auth-error'; ?>">
                    <?php echo esc_html($message); ?>
                </div>
            <?php endif; ?>

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

            <label for="dataCenter" class="iafwzcai-auth-label"><?php esc_html_e('Data Center', 'integrate-with-zoho-campaigns'); ?><span> *</span>
                <div class="iafwzcai-help-icon-wrapper">
                    <span class="iafwzcai-help-icon">?</span>
                    <div class="iafwzcai-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="iafwzcai-auth-select iafwzcai-setup-fm-mandatory" required>
                <?php
                $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 ($data_centers as $value => $label) :
                ?>
                    <option value="<?php echo esc_attr($value); ?>" <?php selected($data_center, $value); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>

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

        </form>

    </div>
</div>