<?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', 'iafwzcai_register_menu_page');
function iafwzcai_register_menu_page()
{
    add_menu_page(
        __('Zoho Campaigns', 'integrate-with-zoho-campaigns'),  // Page title
        __('Zoho Campaigns', 'integrate-with-zoho-campaigns'),  // Menu title
        'manage_options',                               // Capability required to access this menu
        'integrate-with-zoho-campaigns',                                // Menu slug
        'iafwzcai_generate_page_content',         // Function to display page content
        'dashicons-admin-generic',                      // Icon for the menu
        75                                              // Position of the menu item
    );
}

/**
 * Enqueue plugin scripts and styles on the plugin's admin page.
 */
add_action('admin_enqueue_scripts', 'iafwzcai_enqueue_scripts');
function iafwzcai_enqueue_scripts($hook)
{
    // Only load scripts and styles on the plugin's specific admin page.
    if ($hook !== 'toplevel_page_integrate-with-zoho-campaigns') {
        return;
    }

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

    // Define assets for CSS and JS with busting versioning.
    $assets = [
        'css' => ['home', 'auth', 'setup-fm', 'setup-filter', 'premium', 'settings', 'ai-settings', 'help', 'banner', 'error-log','other-plugins'],
        'js' => ['home', 'common', 'setup-fm', 'setup-custom', 'setup-filter', 'ai-settings', 'help', 'error-log']
    ];

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

            // Check if the file exists to avoid enqueueing non-existent assets.
            $file_path = IAFWZCAI_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);
            }
        }
    }

    // Localize JavaScript variables for `setup-fm.js`.
    wp_localize_script('iafwzcai-setup-fm-js', 'iafwzcai_field_mapping', [
        'ajax_url' => admin_url('admin-ajax.php'), // WordPress AJAX URL
        'field_mapping_nonce' => wp_create_nonce('field_mapping_nonce') // Nonce for security
    ]);

    // Localize JavaScript variables for `error-log.js`.
    wp_localize_script('iafwzcai-error-log-js', 'iafwzcai_error_log', [
        'ajax_url' => admin_url('admin-ajax.php'), // WordPress AJAX URL
        'error_log_nonce' => wp_create_nonce('iafwzcai_error_log_nonce') // Nonce for security
    ]);

    // Localize JavaScript variables for `error-log.js`.
    wp_localize_script('iafwzcai-ai-settings-js', 'iafwzcai_ai_settings', [
        'ajax_url' => admin_url('admin-ajax.php'), // WordPress AJAX URL
        'ai_settings_nonce' => wp_create_nonce('iafwzcai_ai_settings_nonce') // Nonce for security
    ]);
}


/**
 * Callback function to display the content of the plugin's main page.
 */
function iafwzcai_generate_page_content()
{
    $plugin_slug = 'integrate-with-zoho-campaigns';
    // Initialize account table and retrieve the total account count
    $iafwzcai_accountDBInstance  = new IAFWZCAI_Account_Table();
    $IAFWZCAI_Form_Group_IdInstance = new IAFWZCAI_Form_Group_Id();
    $IAFWZCAI_Field_MappingDBInstance = new IAFWZCAI_Field_Mapping();
    $session = iafwzcai_is_valid_key();
    iafwzcai_license_expiry_notice();
    $tab_links = [
        'accounts' => __('Accounts', 'integrate-with-zoho-campaigns'),
        'setup'    => __('Setup', 'integrate-with-zoho-campaigns'),
        'errorlog' => __('Logs', 'integrate-with-zoho-campaigns'),
        'settings' => __('Settings', 'integrate-with-zoho-campaigns'),
        'ai-settings' => __('AI Settings', 'integrate-with-zoho-campaigns'),
    ];
    if (!$session) {
        $tab_links['premium'] = __('Go Premium', 'integrate-with-zoho-campaigns');
        $IAFWZCAI_Field_MappingDBInstance->block_field_mapping();
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $current_tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'accounts';
    $tab_file = plugin_dir_path(__FILE__) . "{$current_tab}-tab.php";
?>

    <div class="wrap">
        <div class="iafwzcai-plugin-header">
            <div class="iafwzcai-logo-container">
            </div>
            <p><span class="iafwzcai-main-message"> Campaigns Integration</span></p>
        </div>

        <div id="iafwzcai-plugin-tabs">

            <?php foreach ($tab_links as $tab => $label) : ?>
                <a id="iafwzcai-tab-<?php echo esc_attr($tab); ?>"
                    href="?page=<?php echo esc_attr($plugin_slug); ?>&tab=<?php echo esc_attr($tab); ?>"
                    class="iafwzcai-tab">
                    <div><?php echo esc_html($label); ?></div>
                </a>
            <?php endforeach; ?>
        </div>
        <div id="iafwzcai-tab-content">
            <?php
            if (file_exists($tab_file)) {
                include $tab_file;
            } else {
                echo '<p>' . esc_html__('Tab content not found.', 'integrate-with-zoho-campaigns') . '</p>';
            }
            ?>
        </div>



    </div>
<?php
}
?>