<?php
if (!defined('ABSPATH')) {
    exit;
}

// ✅ Hook to run only after WordPress has loaded all functions
add_action('admin_init', 'integrazo_wz_check_edit_account_url');

function integrazo_wz_check_edit_account_url()
{
    if (
        isset($_GET['page'], $_GET['tab'], $_GET['subtab'], $_GET['action'], $_GET['edit_ac_id']) &&
        $_GET['page'] === 'integrazo-integration-for-zoho-apps' &&
        $_GET['tab'] === 'settings' &&
        $_GET['subtab'] === 'accounts' &&
        $_GET['action'] === 'integrazo_wz_edit_account'
    ) {
        $edit_ac_id = intval($_GET['edit_ac_id']);

        if (isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'edit_account_' . $edit_ac_id)) {
            add_action('admin_notices', function () use ($edit_ac_id) {
                integrazo_wz_render_account_popup_html($edit_ac_id);
            });
        } else {
            add_action('admin_notices', function () {
                echo '<div class="notice notice-error"><p>Security check failed.</p></div>';
            });
        }
    }
}

// ✅ Your popup form rendering function
function integrazo_wz_render_account_popup_html($account_id)
{
    if (!defined('ABSPATH') || $account_id <= 0) {
        return;
    }

    $account_instance = new INTEGRAZO_WZ_Account_Model();
    $account_data     = $account_instance->get_account_by_id($account_id);

    if (empty($account_data) || !is_array($account_data)) {
        return;
    }

    $to_product   = $account_data['product_name'];
    $input_data   = maybe_unserialize($account_data['input_data']);
    $account_name = $account_data['account_name'];

    $service_config = INTEGRAZO_WZ_Auth_Fields::get_fields_by_service($to_product);
    $fields         = isset($service_config['fields']) ? $service_config['fields'] : [];
    $common_note    = isset($service_config['common_note']) ? $service_config['common_note'] : '';
?>
    <div id="integrazo-wz-accounts-auth-popupOverlay" class="integrazo-wz-accounts-auth-popup-overlay show">
        <div class="integrazo-wz-accounts-auth-popup-content">
            <span class="integrazo-wz-accounts-close" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=integrazo-integration-for-zoho-apps&tab=settings&subtab=accounts')); ?>'">&times;</span>
            <h3 class="integrazo-wz-accounts-auth-popup-title"><?php esc_html_e('Account Setup', 'integrazo-integration-for-zoho-apps'); ?></h3>
            <form class="integrazo-wz-accounts-auth-form" id="integrazo-wz-accounts-auth-form" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post">
                <?php wp_nonce_field('integrazo_wz_auth_update_action', 'integrazo_wz_auth_update_nonce'); ?>
                <input type="hidden" name="action" value="<?php echo esc_attr($service_config['update_action']); ?>">
                <input type="hidden" name="account_id" value="<?php echo esc_attr($account_id); ?>">

                <label for="accountName" class="integrazo-wz-accounts-auth-label"><?php esc_html_e('Account Name', 'integrazo-integration-for-zoho-apps'); ?><span> *</span>
                    <div class="integrazo-wz-helpicon-help-icon-wrapper">
                        <span class="integrazo-wz-helpicon-help-icon">?</span>
                        <div class="integrazo-wz-helpicon-help-tooltip">
                            <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="integrazo_wz_account_name" class="integrazo-wz-accounts-auth-input integrazo-wz-accounts-setup-fm-mandatory" placeholder="<?php esc_attr_e('Enter your account name', 'integrazo-integration-for-zoho-apps'); ?>" required>

                <!-- Dynamic Fields -->
                <?php foreach ($fields as $name => $field) : ?>
                    <label for="<?php echo esc_attr($name); ?>" class="integrazo-wz-accounts-auth-label" style="display: block; margin-bottom: 5px;">
                        <?php echo esc_html($field['label']); ?><span> *</span>
                        <?php if (!empty($field['help'])) : ?>
                            <span class="integrazo-wz-helpicon-help-icon-wrapper" style="margin-left: 5px;">
                                <span class="integrazo-wz-helpicon-help-icon">?</span>
                                <div class="integrazo-wz-helpicon-help-tooltip"><?php echo esc_html($field['help']); ?></div>
                            </span>
                        <?php endif; ?>
                    </label>

                    <?php $value = isset($input_data[$name]) ? $input_data[$name] : ''; ?>

                    <?php if ($field['type'] === 'select') : ?>
                        <select name="<?php echo esc_attr($name); ?>" class="integrazo-wz-accounts-auth-select integrazo-wz-accounts-setup-fm-mandatory" required>
                            <?php foreach ($field['options'] as $key => $label) : ?>
                                <option value="<?php echo esc_attr($key); ?>" <?php selected($key, $value); ?>>
                                    <?php echo esc_html($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    <?php else : ?>
                        <input type="<?php echo esc_attr($field['type']); ?>" name="<?php echo esc_attr($name); ?>" value="<?php echo esc_attr($value); ?>" class="integrazo-wz-accounts-auth-input" />
                    <?php endif; ?>
                <?php endforeach; ?>

                <div class="integrazo-wz-accounts-auth-button-container">
                    <button type="submit" class="integrazo-wz-accounts-auth-button">
                        <?php esc_html_e('Save & Re-auth', 'integrazo-integration-for-zoho-apps'); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
<?php
}
