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

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

function integrazo_wczo_check_edit_account_url()
{
    if (
        isset($_GET['page'], $_GET['tab'], $_GET['subtab'], $_GET['action'], $_GET['edit_ac_id']) &&
        $_GET['page'] === 'integrazo-wc-zoho-integration' &&
        $_GET['tab'] === 'settings' &&
        $_GET['subtab'] === 'accounts' &&
        $_GET['action'] === 'integrazo_wczo_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)) {
            if (! current_user_can('manage_options')) {
                wp_die(esc_html__('Insufficient permissions.', 'integrazo-wc-zoho-integration'));
            }
            add_action('admin_notices', function () use ($edit_ac_id) {
                integrazo_wczo_render_account_popup_html($edit_ac_id);
            });
        } else {
            add_action('admin_notices', function () {
                echo '<div class="notice notice-error"><p>' . esc_html__('Security check failed.', 'integrazo-wc-zoho-integration') . '</p></div>';
            });
        }
    }
}

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

    $account_instance = new INTEGRAZO_WCZO_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_WCZO_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-wczo-accounts-auth-popupOverlay" class="integrazo-wczo-accounts-auth-popup-overlay show">
        <div class="integrazo-wczo-accounts-auth-popup-content">
            <span class="integrazo-wczo-accounts-close" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=integrazo-wc-zoho-integration&tab=settings&subtab=accounts')); ?>'">&times;</span>
            <h3 class="integrazo-wczo-accounts-auth-popup-title"><?php esc_html_e('Account Setup', 'integrazo-wc-zoho-integration'); ?></h3>
            <form class="integrazo-wczo-accounts-auth-form" id="integrazo-wczo-accounts-auth-form" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post">
                <?php wp_nonce_field('integrazo_wczo_auth_update_action', 'integrazo_wczo_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-wczo-accounts-auth-label"><?php esc_html_e('Account Name', 'integrazo-wc-zoho-integration'); ?><span> *</span>
                    <div class="integrazo-wczo-helpicon-help-icon-wrapper">
                        <span class="integrazo-wczo-helpicon-help-icon">?</span>
                        <div class="integrazo-wczo-helpicon-help-tooltip">
                            <p><?php esc_html_e('A unique name to identify this account.', 'integrazo-wc-zoho-integration'); ?></p>
                        </div>
                    </div>
                </label>

                <input type="text" value="<?php echo esc_attr($account_name); ?>" id="accountName" name="integrazo_wczo_account_name" class="integrazo-wczo-accounts-auth-input integrazo-wczo-accounts-setup-fm-mandatory" placeholder="<?php esc_attr_e('Enter your account name', 'integrazo-wc-zoho-integration'); ?>" required>

                <!-- Dynamic Fields -->
                <?php foreach ($fields as $name => $field) : ?>
                    <label for="<?php echo esc_attr($name); ?>" class="integrazo-wczo-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-wczo-helpicon-help-icon-wrapper" style="margin-left: 5px;">
                                <span class="integrazo-wczo-helpicon-help-icon">?</span>
                                <div class="integrazo-wczo-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-wczo-accounts-auth-select integrazo-wczo-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-wczo-accounts-auth-input" />
                    <?php endif; ?>
                <?php endforeach; ?>

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