<?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', 'iafwzdesk_register_menu_page');
function iafwzdesk_register_menu_page()
{
    add_menu_page(
        __('Zoho Desk', 'integrate-with-zoho-desk'),  // Page title
        __('Zoho Desk', 'integrate-with-zoho-desk'),  // Menu title
        'manage_options',                               // Capability required to access this menu
        'integrate-with-zoho-desk',                                // Menu slug
        'iafwzdesk_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', 'iafwzdesk_enqueue_scripts');
function iafwzdesk_enqueue_scripts($hook)
{
    // Only load scripts and styles on the plugin's specific admin page.
    if ($hook !== 'toplevel_page_integrate-with-zoho-desk') {
        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 = "iafwzdesk-{$file}-{$type}";
            $path = IAFWZDESK_PLUGIN_URL . "assets/{$type}/{$file}.{$type}";

            // Check if the file exists to avoid enqueueing non-existent assets.
            $file_path = IAFWZDESK_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('iafwzdesk-setup-fm-js', 'iafwzdesk_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('iafwzdesk-error-log-js', 'iafwzdesk_error_log', [
        'ajax_url' => admin_url('admin-ajax.php'), // WordPress AJAX URL
        'error_log_nonce' => wp_create_nonce('iafwzdesk_error_log_nonce') // Nonce for security
    ]);

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


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

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

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

    if (file_exists($js_file)) {
        wp_enqueue_script(
            'iafwzdesk-deactivate-popup-js',
            IAFWZDESK_PLUGIN_URL . 'assets/js/deactivate-popup.js',
            [],
            filemtime($js_file),
            true
        );
        wp_localize_script('iafwzdesk-deactivate-popup-js', 'iafwzdesk_deactivate', [
            'plugin_basename' => plugin_basename(IAFWZDESK_PLUGIN_DIR . 'integrate-with-zoho-desk.php'),
        ]);
    }
}


/**
 * Callback function to display the content of the plugin's main page.
 */
function iafwzdesk_generate_page_content()
{
    $plugin_slug = 'integrate-with-zoho-desk';
    // Initialize account table and retrieve the total account count
    $iafwzdesk_accountDBInstance  = new IAFWZDESK_Account_Table();
    $IAFWZDESK_Form_Group_IdInstance = new IAFWZDESK_Form_Group_Id();
    $IAFWZDESK_Field_MappingDBInstance = new IAFWZDESK_Field_Mapping();
    $session = iafwzdesk_is_valid_key();
    iafwzdesk_license_expiry_notice();
    $tab_links = [
        'accounts' => __('Accounts', 'integrate-with-zoho-desk'),
        'setup'    => __('Setup', 'integrate-with-zoho-desk'),
        'errorlog' => __('Logs', 'integrate-with-zoho-desk'),
        'settings' => __('Settings', 'integrate-with-zoho-desk'),
    ];
    if (!$session) {
        $tab_links['premium'] = __('Go Premium', 'integrate-with-zoho-desk');
        $IAFWZDESK_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="iafwzdesk-plugin-header">
            <div class="iafwzdesk-help-wrap">
                <button class="iafwzdesk-help-btn" id="iafwzdesk-help-btn"
                        aria-expanded="false" aria-haspopup="true">
                    <span class="dashicons dashicons-editor-help" aria-hidden="true"></span>
                    <span class="iafwzdesk-help-btn-label"><?php esc_html_e('Help', 'integrate-with-zoho-desk'); ?></span>
                </button>
                <div class="iafwzdesk-help-dropdown" id="iafwzdesk-help-dropdown" role="menu" hidden>

                    <a class="iafwzdesk-help-item" href="mailto:support@integrazo.com" role="menuitem">
                        <span class="dashicons dashicons-email iafwzdesk-help-item-icon" aria-hidden="true"></span>
                        <span class="iafwzdesk-help-item-text">
                            <span class="iafwzdesk-help-item-title"><?php esc_html_e('Email support', 'integrate-with-zoho-desk'); ?></span>
                            <span class="iafwzdesk-help-item-sub">support@integrazo.com</span>
                        </span>
                        <button class="iafwzdesk-help-copy-btn" type="button" data-copy="support@integrazo.com" aria-label="<?php esc_attr_e('Copy email address', 'integrate-with-zoho-desk'); ?>">
                            <svg class="iafwzdesk-icon-copy" 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="iafwzdesk-icon-check" 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"><polyline points="20 6 9 17 4 12"></polyline></svg>
                        </button>
                    </a>

                    <a class="iafwzdesk-help-item" href="https://integrazo.com/pages/contact" target="_blank" rel="noopener noreferrer" role="menuitem">
                        <span class="dashicons dashicons-format-chat iafwzdesk-help-item-icon" aria-hidden="true"></span>
                        <span class="iafwzdesk-help-item-text">
                            <span class="iafwzdesk-help-item-title"><?php esc_html_e('Contact support', 'integrate-with-zoho-desk'); ?></span>
                            <span class="iafwzdesk-help-item-sub"><?php esc_html_e('Submit a support request', 'integrate-with-zoho-desk'); ?></span>
                        </span>
                    </a>

                    <a class="iafwzdesk-help-item" href="https://integrazo.com/pages/request-feature" target="_blank" rel="noopener noreferrer" role="menuitem">
                        <span class="dashicons dashicons-lightbulb iafwzdesk-help-item-icon" aria-hidden="true"></span>
                        <span class="iafwzdesk-help-item-text">
                            <span class="iafwzdesk-help-item-title"><?php esc_html_e('Request a feature', 'integrate-with-zoho-desk'); ?></span>
                            <span class="iafwzdesk-help-item-sub"><?php esc_html_e('Suggest an idea or improvement', 'integrate-with-zoho-desk'); ?></span>
                        </span>
                    </a>

                    <?php
                    $iafwzdesk_plugin_data = get_plugin_data(IAFWZDESK_PLUGIN_DIR . 'integrate-with-zoho-desk.php');
                    $iafwzdesk_version     = isset($iafwzdesk_plugin_data['Version']) ? $iafwzdesk_plugin_data['Version'] : '';
                    ?>
                    <?php if ($iafwzdesk_version) : ?>
                    <div class="iafwzdesk-help-version">
<?php
/* translators: %s: plugin version number */
echo esc_html(sprintf(__('Version %s', 'integrate-with-zoho-desk'), $iafwzdesk_version));
                        ?>                    </div>
                    <?php endif; ?>

                </div>
            </div>
            <div class="iafwzdesk-logo-container">
            </div>
            <p><span class="iafwzdesk-main-message">Desk Integration</span></p>

            <?php
                                        $iafwzdesk_plugin_data = get_plugin_data(IAFWZDESK_PLUGIN_DIR . 'integrate-with-zoho-desk.php');
    $iafwzdesk_version     = isset($iafwzdesk_plugin_data['Version']) ? $iafwzdesk_plugin_data['Version'] : '';
    ?>
            
        </div>

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

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



    </div>
<?php
}
?>