<?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_wczo_register_menu_page' );
function integrazo_wczo_register_menu_page() {

    add_menu_page(
        __( 'Zoho', 'integrazo-wc-zoho-integration' ),
        __( 'Zoho', 'integrazo-wc-zoho-integration' ),
        'manage_options',
        'integrazo-wc-zoho-integration',
        'integrazo_wczo_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_wczo_enqueue_scripts');
function integrazo_wczo_enqueue_scripts($hook)
{
    // Only load scripts and styles on the plugin's specific admin page.
    if ($hook !== 'toplevel_page_integrazo-wc-zoho-integration') {
        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-wczo-{$file}-{$type}";
            $path   = INTEGRAZO_WCZO_PLUGIN_URL . "assets/{$type}/{$file}.{$type}";

            // Check if the file exists to avoid enqueueing non-existent assets.
            $file_path = INTEGRAZO_WCZO_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-wczo-setup-extend-js', 'integrazo_wczo_field_mapping', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'field_mapping_nonce' => wp_create_nonce('field_mapping_nonce')
    ]);
    wp_localize_script('integrazo-wczo-detailed-logs-js', 'integrazo_wczo_error_log', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'error_log_nonce' => wp_create_nonce('integrazo_wczo_error_log_nonce') // Nonce for security
    ]);
}

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

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

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

    if (file_exists($js_file)) {
        wp_enqueue_script(
            'integrazo-wczo-deactivate-popup-js',
            INTEGRAZO_WCZO_PLUGIN_URL . 'assets/js/deactivate-popup.js',
            [],
            filemtime($js_file),
            true
        );
        wp_localize_script('integrazo-wczo-deactivate-popup-js', 'integrazo_wczo_deactivate', [
            'plugin_basename' => plugin_basename(INTEGRAZO_WCZO_PLUGIN_FILE),
        ]);
    }
}

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

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

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

?>

    <div class="wrap">
        <div class="integrazo-wczo-plugin-header">
<?php if (!$session) : ?>
<button class="integrazo-wczo-trial-btn" onclick="integrazoWczoShowProPopup()">⏱ <?php esc_html_e( 'Try Pro', 'integrazo-wc-zoho-integration' ); ?></button>
<?php endif; ?>            <div class="integrazo-wczo-logo-container">
            </div>
            <p><span class="integrazo-wczo-main-message">WooCommerce to Zoho Apps</span></p>
        </div>

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

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