<?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', 'iafwzc_register_menu_page');
function iafwzc_register_menu_page()
{
    add_menu_page(
        __('Zoho', 'integrate-any-form-with-zoho-crm'),  // Page title
        __('Zoho', 'integrate-any-form-with-zoho-crm'),  // Menu title
        'manage_options',                               // Capability required to access this menu
        'integrate-any-form-with-zoho-crm',                                // Menu slug
        'iafwzc_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', 'iafwzc_enqueue_scripts');
function iafwzc_enqueue_scripts($hook)
{
    // Only load scripts and styles on the plugin's specific admin page.
    if ($hook !== 'toplevel_page_integrate-any-form-with-zoho-crm') {
        return;
    }

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

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

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

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

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

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

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

    if (file_exists($js_file)) {
        wp_enqueue_script(
            'iafwzc-deactivate-popup-js',
            IAFWZC_PLUGIN_URL . 'assets/js/deactivate-popup.js',
            [],
            filemtime($js_file),
            true
        );
        wp_localize_script('iafwzc-deactivate-popup-js', 'iafwzc_deactivate', [
            'plugin_basename' => plugin_basename(IAFWZC_PLUGIN_FILE),
        ]);
    }
}

/**
 * Callback function to display the content of the plugin's main page.
 */
function iafwzc_generate_page_content()
{
    $plugin_slug = 'integrate-any-form-with-zoho-crm';
    // Initialize account table and retrieve the total account count
    $iafwzc_accountDBInstance  = new IAFWZC_Account_Table();
    $IAFWZC_Form_Group_IdInstance = new IAFWZC_Form_Group_Id();
    $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();
    $iafwzc_session = iafwzc_is_valid_key();
    iafwzc_license_expiry_notice();
    $tab_links = [
        'accounts' => __('Accounts', 'integrate-any-form-with-zoho-crm'),
        'setup'    => __('Setup', 'integrate-any-form-with-zoho-crm'),
        'errorlog' => __('Logs', 'integrate-any-form-with-zoho-crm'),
        'settings' => __('Settings', 'integrate-any-form-with-zoho-crm'),
    ];
    if (!$iafwzc_session) {
        $tab_links['premium'] = __('Go Premium', 'integrate-any-form-with-zoho-crm');
        $IAFWZC_Field_MappingDBInstance->block_field_mapping();
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $raw_tab     = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'accounts';
    $allowed_tabs = ['accounts', 'setup', 'errorlog', 'settings', 'premium'];
    $current_tab  = in_array($raw_tab, $allowed_tabs, true) ? $raw_tab : 'accounts';
    $tab_file = plugin_dir_path(__FILE__) . "{$current_tab}-tab.php";
    ?>

    <div class="wrap">
        <div class="iafwzc-plugin-header">
            <div class="iafwzc-help-wrap">
                <button class="iafwzc-help-btn" id="iafwzc-help-btn"
                    aria-expanded="false" aria-haspopup="true">
                    <svg class="iafwzc-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="iafwzc-help-btn-label"><?php esc_html_e('Help', 'integrate-any-form-with-zoho-crm'); ?></span>
                </button>
                <div class="iafwzc-help-dropdown" id="iafwzc-help-dropdown" role="menu" hidden>
                    <a class="iafwzc-help-item"
                        href="<?php echo esc_url('mailto:support@integrazo.com'); ?>"
                        role="menuitem">
                        <span class="dashicons dashicons-email iafwzc-help-item-icon" aria-hidden="true"></span>
                        <span class="iafwzc-help-item-text">
                            <span class="iafwzc-help-item-title"><?php esc_html_e('Email support', 'integrate-any-form-with-zoho-crm'); ?></span>
                            <span class="iafwzc-help-item-sub"><?php esc_html_e('support@integrazo.com', 'integrate-any-form-with-zoho-crm'); ?></span>
                        </span>
                        <button class="iafwzc-help-copy-btn"
                            type="button"
                            data-copy="<?php echo esc_attr('support@integrazo.com'); ?>"
                            aria-label="<?php esc_attr_e('Copy email address', 'integrate-any-form-with-zoho-crm'); ?>"
                            title="<?php esc_attr_e('Copy', 'integrate-any-form-with-zoho-crm'); ?>">
                            <svg class="iafwzc-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="iafwzc-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="iafwzc-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 iafwzc-help-item-icon" aria-hidden="true"></span>
                        <span class="iafwzc-help-item-text">
                            <span class="iafwzc-help-item-title"><?php esc_html_e('Contact support', 'integrate-any-form-with-zoho-crm'); ?></span>
                            <span class="iafwzc-help-item-sub"><?php esc_html_e('Submit a support request', 'integrate-any-form-with-zoho-crm'); ?></span>
                        </span>
                    </a>
                    <a class="iafwzc-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 iafwzc-help-item-icon" aria-hidden="true"></span>
                        <span class="iafwzc-help-item-text">
                            <span class="iafwzc-help-item-title"><?php esc_html_e('Request a feature', 'integrate-any-form-with-zoho-crm'); ?></span>
                            <span class="iafwzc-help-item-sub"><?php esc_html_e('Suggest an idea or improvement', 'integrate-any-form-with-zoho-crm'); ?></span>
                        </span>
                    </a>
                    <div class="iafwzc-help-version">
                        <?php printf(
                            /* translators: %s: plugin version number */
                            esc_html__('Version %s', 'integrate-any-form-with-zoho-crm'),
                            esc_html(IAFWZC_VERSION)
                        ); ?>
                    </div>
                </div>
            </div>
            <p><span class="iafwzc-main-message">Zoho CRM &amp; Bigin Integration</span></p>
        </div>

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

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



    </div>
<?php
}
?>