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

/**
 * Register the plugin menu page in the WordPress admin.
 */
add_action( 'admin_menu', 'integrazo_wz_register_menu_page' );
function integrazo_wz_register_menu_page() {

    add_menu_page(
        __( 'Zoho', 'integrazo-integration-for-zoho-apps' ),
        __( 'Zoho', 'integrazo-integration-for-zoho-apps' ),
        'manage_options',
        'integrazo-integration-for-zoho-apps',
        'integrazo_wz_generate_page_content',
        'dashicons-admin-generic', // WP default settings icon
        56
    );

}

/**
 * Enqueue deactivation feedback popup assets on the plugins page only.
 */
add_action('admin_enqueue_scripts', 'integrazo_wz_enqueue_deactivate_scripts');
function integrazo_wz_enqueue_deactivate_scripts($hook)
{
    if ($hook !== 'plugins.php') {
        return;
    }

    $css_file = INTEGRAZO_WZ_PLUGIN_DIR . 'assets/css/deactivate-popup.css';
    $js_file  = INTEGRAZO_WZ_PLUGIN_DIR . 'assets/js/deactivate-popup.js';

    if (file_exists($css_file)) {
        wp_enqueue_style(
            'integrazo-wz-deactivate-popup-css',
            INTEGRAZO_WZ_PLUGIN_URL . 'assets/css/deactivate-popup.css',
            [],
            filemtime($css_file)
        );
    }

    if (file_exists($js_file)) {
        wp_enqueue_script(
            'integrazo-wz-deactivate-popup-js',
            INTEGRAZO_WZ_PLUGIN_URL . 'assets/js/deactivate-popup.js',
            [],
            filemtime($js_file),
            true
        );
        wp_localize_script('integrazo-wz-deactivate-popup-js', 'integrazo_wz_deactivate', [
            'plugin_basename' => plugin_basename(INTEGRAZO_WZ_PLUGIN_FILE),
        ]);
    }
}

/**
 * Enqueue plugin scripts and styles on the plugin's admin page.
 */
add_action('admin_enqueue_scripts', 'integrazo_wz_enqueue_scripts');
function integrazo_wz_enqueue_scripts($hook)
{
    // Only load scripts and styles on the plugin's specific admin page.
    if ($hook !== 'toplevel_page_integrazo-integration-for-zoho-apps') {
        return;
    }

    // Enqueue jQuery as a dependency.
    wp_enqueue_script('jquery');

    // Define assets for CSS and JS with cache-busting versioning.
    $assets = [
        'css' => ['admin', 'accounts',  'detailed-logs', 'filter', 'help', 'load-img', 'logs', 'premium', 'settings', 'setup', 'setup-extend', 'pro-popup'],
        'js'  => ['admin', 'custom', 'detailed-logs', 'filter', 'help', 'mapping', 'setup', 'setup-extend', 'settings', 'pro-popup']

    ];

    foreach ($assets as $type => $files) {
        foreach ($files as $file) {
            $handle = "integrazo-wz-{$file}-{$type}";
            $path   = INTEGRAZO_WZ_PLUGIN_URL . "assets/{$type}/{$file}.{$type}";

            // Check if the file exists to avoid enqueueing non-existent assets.
            $file_path = INTEGRAZO_WZ_PLUGIN_DIR . "assets/{$type}/{$file}.{$type}";
            if (! file_exists($file_path)) {
                continue;
            }

            $ver = filemtime($file_path); // Use file modification time as version.

            if ($type === 'css') {
                wp_enqueue_style($handle, $path, [], $ver);
            } else {
                wp_enqueue_script($handle, $path, ['jquery'], $ver, true);
            }
        }
    }
    wp_localize_script('integrazo-wz-setup-extend-js', 'integrazo_wz_field_mapping', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'field_mapping_nonce' => wp_create_nonce('field_mapping_nonce')
    ]);
    wp_localize_script('integrazo-wz-detailed-logs-js', 'integrazo_wz_error_log', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'error_log_nonce' => wp_create_nonce('integrazo_wz_error_log_nonce') // Nonce for security
    ]);
}

/**
 * Print (and clear) any pending success/failure admin notices.
 *
 * Shared so the Setup tab can render these inline next to the
 * "Back to Integrations" button instead of at the very top of the page.
 */
function integrazo_wz_render_pending_notices()
{
    if ($success_msg = get_transient('integrazo_wz_success')) {
        printf('<div class="notice notice-success is-dismissible"><p>%s</p></div>', wp_kses_post($success_msg));
        delete_transient('integrazo_wz_success');
    }

    if ($fail_msg = get_transient('integrazo_wz_fail')) {
        printf('<div class="notice notice-warning is-dismissible"><p>%s</p></div>', wp_kses_post($fail_msg));
        delete_transient('integrazo_wz_fail');
    }
}

/**
 * Callback function to display the content of the plugin's main page.
 */
function integrazo_wz_generate_page_content()
{
    $plugin_slug = "integrazo-integration-for-zoho-apps";
    $tab_links = [
        'setup'      => __('Setup', 'integrazo-integration-for-zoho-apps'),
        'logs'   => __('Logs', 'integrazo-integration-for-zoho-apps'),
        'settings'   => __('Settings', 'integrazo-integration-for-zoho-apps'),
    ];
    $session = integrazo_wz_session();
    if (!$session) {
        $tab_links['premium'] = __('Go Premium', 'integrazo-integration-for-zoho-apps');
    }
    $allowed_tabs = ['setup', 'logs', 'settings', 'premium'];
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $current_tab_input = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'setup';
    $current_tab = in_array($current_tab_input, $allowed_tabs, true) ? $current_tab_input : 'setup';

    $tab_file = INTEGRAZO_WZ_PLUGIN_DIR . "includes/page/{$current_tab}.php";

    // ✅ SHOW ADMIN NOTICES if any transient exists.
    // The Setup tab renders these itself, inline next to "Back to Integrations".
    // The Logs tab renders these itself, right below the "Logs" heading.
    if (!in_array($current_tab, ['setup', 'logs'], true)) {
        integrazo_wz_render_pending_notices();
    }

?>

    <div class="wrap">
        <div class="integrazo-wz-plugin-header">
<?php if (!$session) : ?>
<button class="integrazo-wz-trial-btn" onclick="integrazoWzShowProPopup()">⏱ <?php esc_html_e( 'Try Pro', 'integrazo-integration-for-zoho-apps' ); ?></button>
<?php endif; ?>            <div class="integrazo-wz-help-wrap">
                <button class="integrazo-wz-help-btn" id="integrazo-wz-help-btn"
                    aria-expanded="false" aria-haspopup="true">
                    <svg class="integrazo-wz-help-btn-icon" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="12" cy="12" r="10"/>
                        <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>
                        <circle cx="12" cy="17" r=".5" fill="currentColor"/>
                    </svg>
                    <span class="integrazo-wz-help-btn-label"><?php esc_html_e('Help', 'integrazo-integration-for-zoho-apps'); ?></span>
                </button>
                <div class="integrazo-wz-help-dropdown" id="integrazo-wz-help-dropdown" role="menu" hidden>
                    <a class="integrazo-wz-help-item"
                        href="<?php echo esc_url('mailto:support@integrazo.com'); ?>"
                        role="menuitem">
                        <span class="dashicons dashicons-email integrazo-wz-help-item-icon" aria-hidden="true"></span>
                        <span class="integrazo-wz-help-item-text">
                            <span class="integrazo-wz-help-item-title"><?php esc_html_e('Email support', 'integrazo-integration-for-zoho-apps'); ?></span>
                            <span class="integrazo-wz-help-item-sub"><?php esc_html_e('support@integrazo.com', 'integrazo-integration-for-zoho-apps'); ?></span>
                        </span>
                        <button class="integrazo-wz-help-copy-btn"
                            type="button"
                            data-copy="<?php echo esc_attr('support@integrazo.com'); ?>"
                            aria-label="<?php esc_attr_e('Copy email address', 'integrazo-integration-for-zoho-apps'); ?>"
                            title="<?php esc_attr_e('Copy', 'integrazo-integration-for-zoho-apps'); ?>">
                            <svg class="integrazo-wz-copy-icon" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                                <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                            </svg>
                            <svg class="integrazo-wz-check-icon" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="20 6 9 17 4 12"></polyline>
                            </svg>
                        </button>
                    </a>
                    <a class="integrazo-wz-help-item"
                        href="<?php echo esc_url('https://integrazo.com/pages/contact'); ?>"
                        target="_blank" rel="noopener noreferrer"
                        role="menuitem">
                        <span class="dashicons dashicons-format-chat integrazo-wz-help-item-icon" aria-hidden="true"></span>
                        <span class="integrazo-wz-help-item-text">
                            <span class="integrazo-wz-help-item-title"><?php esc_html_e('Contact support', 'integrazo-integration-for-zoho-apps'); ?></span>
                            <span class="integrazo-wz-help-item-sub"><?php esc_html_e('Submit a support request', 'integrazo-integration-for-zoho-apps'); ?></span>
                        </span>
                    </a>
                    <a class="integrazo-wz-help-item"
                        href="<?php echo esc_url('https://integrazo.com/pages/request-feature'); ?>"
                        target="_blank" rel="noopener noreferrer"
                        role="menuitem">
                        <span class="dashicons dashicons-lightbulb integrazo-wz-help-item-icon" aria-hidden="true"></span>
                        <span class="integrazo-wz-help-item-text">
                            <span class="integrazo-wz-help-item-title"><?php esc_html_e('Request a feature', 'integrazo-integration-for-zoho-apps'); ?></span>
                            <span class="integrazo-wz-help-item-sub"><?php esc_html_e('Suggest an idea or improvement', 'integrazo-integration-for-zoho-apps'); ?></span>
                        </span>
                    </a>
                    <div class="integrazo-wz-help-version">
                        <?php printf(
                            /* translators: %s: plugin version number */
                            esc_html__('Version %s', 'integrazo-integration-for-zoho-apps'),
                            esc_html(INTEGRAZO_WZ_PLUGIN_VERSION)
                        ); ?>
                    </div>
                </div>
            </div>
            <div class="integrazo-wz-logo-container">
            </div>
            <p><span class="integrazo-wz-main-message">Integration for Zoho Apps</span></p>
        </div>

        <div id="integrazo-wz-plugin-tabs">
            <?php foreach ($tab_links as $tab => $label) : ?>
                <a id="integrazo-wz-tab-<?php echo esc_attr($tab); ?>"
                    href="?page=<?php echo esc_attr($plugin_slug); ?>&tab=<?php echo esc_attr($tab); ?>"
                    class="integrazo-wz-tab">
                    <div><?php echo esc_html($label); ?></div>
                </a>
            <?php endforeach; ?>
        </div>

        <div id="integrazo-wz-tab-content">
            <?php
            if (file_exists($tab_file)) {
                include $tab_file;
                integrazo_wz_maybe_cleanup_logs();
            } else {
                echo '<p>' . esc_html__('Tab content not found.', 'integrazo-integration-for-zoho-apps') . '</p>';
            }
            ?>
        </div>
    </div>
<?php
}
?>