<?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_fwcrm_form_register_menu_page');
function integrazo_fwcrm_form_register_menu_page()
{
    add_menu_page(
        __('Freshworks CRM Integration', 'crm-integration-freshworks-any-form'),  // Page title
        __('Freshsales', 'crm-integration-freshworks-any-form'),  // Menu title
        'manage_options',                               // Capability required to access this menu
        'crm-integration-freshworks-any-form',                                // Menu slug
        'integrazo_fwcrm_form_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', 'integrazo_fwcrm_form_enqueue_scripts');
function integrazo_fwcrm_form_enqueue_scripts($hook)
{
    // Only load scripts and styles on the plugin's specific admin page.
    if ($hook !== 'toplevel_page_crm-integration-freshworks-any-form') {
        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', 'premium', 'settings', 'help', 'banner', 'error-log', 'options','other-plugins'],
        'js' => ['home', 'common', 'setup-fm', 'help', 'error-log', 'review', 'options']
    ];

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

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


/**
 * Callback function to display the content of the plugin's main page.
 */
function integrazo_fwcrm_form_generate_page_content()
{
    $plugin_slug = 'crm-integration-freshworks-any-form';
    // Initialize account table and retrieve the total account count
    $integrazo_fwcrm_form_accountDBInstance = new integrazo_fwcrm_form_Account_Table();
    $integrazo_fwcrm_form_formGroupIDInstance = new integrazo_fwcrm_form_FormGroupID();
    $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
    $session = integrazo_fwcrm_form_is_valid_key();

    integrazo_license_expiry_notice();
    $tab_links = [
        'accounts' => __('Accounts', 'crm-integration-freshworks-any-form'),
        'setup'    => __('Setup', 'crm-integration-freshworks-any-form'),
        'errorlog' => __('Logs', 'crm-integration-freshworks-any-form'),
        'settings' => __('Settings', 'crm-integration-freshworks-any-form'),
    ];

    if (!$session) {
        $tab_links['premium'] = __('Go Premium', 'crm-integration-freshworks-any-form');
        $integrazo_fwcrm_form_fieldMappingDBInstance->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="integrazo_fwcrm_form-plugin-header">
            <div class="integrazo_fwcrm_form-logo-container">
            </div>
            <p><span class="integrazo_fwcrm_form-main-message">Freshworks CRM Integration</span></p>
        </div>

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

            <?php foreach ($tab_links as $tab => $label) : ?>
                <a id="integrazo_fwcrm_form-tab-<?php echo esc_attr($tab); ?>"
                    href="?page=<?php echo esc_attr($plugin_slug); ?>&tab=<?php echo esc_attr($tab); ?>"
                    class="integrazo_fwcrm_form-tab">
                    <div><?php echo esc_html($label); ?></div>
                </a>
            <?php endforeach; ?>
        </div>
        <!-- <button style="position: absolute;right: 35px;">Help Doc</button> -->
        <!-- <div class="alignleft actions" style="position: absolute;right: 50px;">
            <a href="javascript:void(0);" class="button">
                <?php esc_html_e('Help Doc', 'crm-integration-freshworks-any-form'); ?>
            </a>
        </div> -->
        <div id="integrazo_fwcrm_form-tab-content">
            <?php
            if (file_exists($tab_file)) {
                include $tab_file;
            } else {
                echo '<p>' . esc_html__('Tab content not found.', 'crm-integration-freshworks-any-form') . '</p>';
            }
            ?>
        </div>



    </div>
<?php
}
?>