<?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 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'],
        'js'  => ['admin', 'custom', 'detailed-logs', 'filter', 'help', 'mapping', 'setup', 'setup-extend', 'settings']

    ];

    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
    ]);
}

/**
 * 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');
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $current_tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'setup';

    $tab_file = INTEGRAZO_WZ_PLUGIN_DIR . "../integrazo-integration-for-zoho-apps/includes/page/{$current_tab}.php";
    //
    // ✅ SHOW ADMIN NOTICES if any transient exists
    if ($success_msg = get_transient('integrazo_wz_success')) {
        printf('<div class="notice notice-success is-dismissible"><p>%s</p></div>', esc_html($success_msg));
        delete_transient('integrazo_wz_success');
    }

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

?>

    <div class="wrap">
        <div class="integrazo-wz-plugin-header">
            <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
}
?>