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


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

    <span class="iafwzc-span-header"><?php esc_html_e('Zoho Accounts', 'integrate-any-form-with-zoho-crm'); ?></span>

    <div class="iafwzc-help-icon-wrapper">
        <span class="iafwzc-help-icon">?</span>
        <div class="iafwzc-help-tooltip">
            <p>Connect and manage your Zoho CRM and Zoho Bigin accounts from this page.</p>
        </div>
    </div>
<?php if ( $iafwzc_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-any-form-with-zoho-crm'),
            array( 'b' => array() )
        );
        ?>
    </p>
</div>

<?php endif; ?>



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

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

    // Display the accounts table.
    $iafwzc_accounts_table = new IAFWZC_Accounts_Extend();
    $iafwzc_accounts_table->prepare_items(); // Prepare account table items
    $iafwzc_accounts_table->display();       // Display account table
    $iafwzc_session = $iafwzc_session ?? false;
    if (!$iafwzc_session) {
         include "other-plugins.php";
    }
    ?>
</div>

<?php

$iafwzc_account_count = $iafwzc_accountDBInstance->get_total_accounts() + 1;

// Retrieve account ID and action if present
$iafwzc_account_id = null;
$iafwzc_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'])), 'edit_account_nonce')) {

        // Nonce is valid, proceed with the action.
        $iafwzc_account_id = intval($_GET['ac_id']);
        $iafwzc_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-any-form-with-zoho-crm')
        );
    }
}


// Get authentication data from option
$iafwzc_auth_data = get_option('iafwzc_account_data', []);

if (!$iafwzc_account_id) {
    $iafwzc_account_id = $iafwzc_auth_data['account_id'] ?? null;
}
// Initialize default variables
$iafwzc_message = '';
$iafwzc_is_success = null;
$iafwzc_account_name = $iafwzc_service_name = $iafwzc_data_center = '';
// Determine account details or handle error messages based on available data
if ($iafwzc_account_id) {
    if ($iafwzc_auth_data) {
        // If auth data is present, use it and delete the transient
        $iafwzc_is_success = false;
        $iafwzc_account_name = $iafwzc_auth_data['account_name'] ?? '';
        $iafwzc_service_name = $iafwzc_auth_data['service_name'] ?? '';
        $iafwzc_data_center = $iafwzc_auth_data['data_center'] ?? '';
        $iafwzc_message = $iafwzc_auth_data['error_message'] ?? '';
        delete_option('iafwzc_account_data');
    } else {
        // Fetch account details based on account ID
        $iafwzc_account_details = $iafwzc_accountDBInstance->get_single_account_data($iafwzc_account_id);
        $iafwzc_account_name = $iafwzc_account_details['account_name'] ?? '';
        $iafwzc_service_name = $iafwzc_account_details['service_name'] ?? '';
        $iafwzc_data_center = $iafwzc_account_details['data_center'] ?? '';
    }
} elseif ($iafwzc_auth_data) {
    // If no account ID but auth data is present, use auth data
    $iafwzc_is_success = false;
    $iafwzc_account_name = $iafwzc_auth_data['account_name'] ?? '';
    $iafwzc_service_name = $iafwzc_auth_data['service_name'] ?? '';
    $iafwzc_data_center = $iafwzc_auth_data['data_center'] ?? '';
    $iafwzc_message = $iafwzc_auth_data['error_message'] ?? '';
    delete_option('iafwzc_account_data');
} else {
    // Default account name if no account ID or auth data is provided
    $iafwzc_account_name = 'Account #' . $iafwzc_account_count;
}

$iafwzc_account_name = sanitize_text_field($iafwzc_account_name);
$iafwzc_service_name = sanitize_text_field($iafwzc_service_name);
$iafwzc_data_center  = sanitize_text_field($iafwzc_data_center);

?>

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

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

    ?>
<?php endif; ?>



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

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

            <label for="service" class="iafwzc-auth-label"><?php esc_html_e('Service', 'integrate-any-form-with-zoho-crm'); ?><span> *</span>
                <div class="iafwzc-help-icon-wrapper">
                    <span class="iafwzc-help-icon">?</span>
                    <div class="iafwzc-help-tooltip">
                        <div class="page-title" style="text-decoration: underline;">Zoho Service</div>
                        <p>Select the Zoho service (Zoho CRM or Zoho Bigin) for integration.</p>
                    </div>
                </div>
            </label>
            <select id="service" name="service" class="iafwzc-auth-select iafwzc-setup-fm-mandatory" required>
                <?php if ($iafwzc_account_id) : ?>
                    <option value="<?php echo esc_attr($iafwzc_service_name); ?>" selected>
                        <?php echo ($iafwzc_service_name === 'zoho_crm') ? esc_html__('Zoho CRM', 'integrate-any-form-with-zoho-crm') : esc_html__('Zoho Bigin', 'integrate-any-form-with-zoho-crm'); ?>
                    </option>
                <?php else : ?>
                    <option value="zoho_crm" <?php selected($iafwzc_service_name, 'zoho_crm'); ?>><?php esc_html_e('Zoho CRM', 'integrate-any-form-with-zoho-crm'); ?></option>
                    <option value="zoho_bigin" <?php selected($iafwzc_service_name, 'zoho_bigin'); ?>><?php esc_html_e('Zoho Bigin', 'integrate-any-form-with-zoho-crm'); ?></option>
                <?php endif; ?>
            </select>

            <label for="dataCenter" class="iafwzc-auth-label"><?php esc_html_e('Data Center', 'integrate-any-form-with-zoho-crm'); ?><span> *</span>
                <div class="iafwzc-help-icon-wrapper">
                    <span class="iafwzc-help-icon">?</span>
                    <div class="iafwzc-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="iafwzc-auth-select iafwzc-setup-fm-mandatory" required>
                <?php
                $iafwzc_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 ($iafwzc_data_centers as $iafwzc_value => $iafwzc_label) :
                ?>
                    <option value="<?php echo esc_attr($iafwzc_value); ?>" <?php selected($iafwzc_data_center, $iafwzc_value); ?>>
                        <?php echo esc_html($iafwzc_label); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <div class="iafwzc-auth-button-container">
                <button type="submit" class="iafwzc-auth-button" name="<?php echo esc_attr($iafwzc_account_id ? 'save_reauth' : 'save_auth'); ?>">
                    <?php echo $iafwzc_account_id ? esc_html__('Save & Re-auth', 'integrate-any-form-with-zoho-crm') : esc_html__('Authenticate', 'integrate-any-form-with-zoho-crm'); ?>
                </button>
            </div>

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