<?php
// EN: If this file is called directly, abort.
// IT: Se questo file viene chiamato direttamente, interrompi.
if (! defined('ABSPATH')) {
    exit; // Exit
}

/*
 * FILE: admin-init.php | DESCRIPTION: Plugin description and admin initialization flows
 * FROM → pk-inexpress main (assumed) | TO → views/allfile..., save-quick-options.php, run-quick-import.php
 * FUNCTIONS: pkinex_register_menu() - registers admin menu and submenus
 *            pkinex_handle_save_quick_options() - handles save settings POST
 *            pkinex_handle_run_quick_import() - handles run import POST
 */

/*
 * EN: Plugin description and admin init flows
 * * - EN: Activate main menu and route to admin-init
 * * - EN: Save settings on POST with pkinex_handle_save_quick_options
 * * - EN: Run import on POST pkinex_handle_run_quick_import
 * * - EN: Add menu to sidebar
 * IT: Descrizione del plugin e flussi di inizializzazione amministrativa
 * - IT: Attiva il menù principale e indirizza ad admin-init
 * - IT: Salva le impostazioni al POST con pkinex_handle_save_quick_options
 * - IT: Esegue l'importazione al POST pkinex_handle_run_quick_import
 * - IT: Aggiunge il menu alla sidebar
 */

// EN: Run the compatibility check on admin init
// IT: Esegui il controllo di compatibilità su admin_init
add_action('admin_init', 'pkinex_check_compatibility');

// EN: Register main menu and POST callbacks
// IT: Registra il menu principale e le callback per admin-post
add_action('admin_menu', 'pkinex_register_menu');

// EN: Handle save settings POST request
// IT: Gestisce la richiesta POST di salvataggio impostazioni quick
add_action('admin_post_pkinex_handle_save_quick_options', 'pkinex_handle_save_quick_options');

// EN: Handle run import POST request
// IT: Gestisce la richiesta POST di esecuzione importazione quick
add_action('admin_post_pkinex_handle_run_quick_import', 'pkinex_handle_run_quick_import');

add_action('admin_notices', 'pkinex_show_admin_notices');


// EN: Include handlers and views
// IT: Includi gestori e view
require_once PKINEX_INEXPRESS_DIR . 'admin/views/pkinex-view-dashboard.php';                          // EN: import/export views | IT: view dashboard
require_once PKINEX_INEXPRESS_DIR . 'admin/views/pkinex-view-quick-import.php';                       // EN: import/export views | IT: view import/export
require_once PKINEX_INEXPRESS_DIR . 'includes/services/pkinex-handle-save-quick-options.php';         // EN: settings save handler | IT: gestore salvataggio impostazioni
require_once PKINEX_INEXPRESS_DIR . 'includes/services/pkinex-handle-run-quick-import.php';          // EN: import data handler quick | IT: gestore importazione dati
// EN: Async import AJAX handler (start/step/cancel)
// IT: Gestore AJAX per import asincrona (start/step/cancel)
require_once PKINEX_INEXPRESS_DIR . 'includes/services/pkinex-handle-async-import.php';

/**
 * EN: Register main menu and submenus
 * IT: Registra il menu principale e i sottomenu
 */
function pkinex_register_menu()
{
    // EN: Add top-level menu page
    // IT: Aggiungi menu principale
    add_menu_page(
        __('PK InExpress', 'pk-inexpress'),        // EN: Page title | IT: Titolo pagina
        __('InExPress PK', 'pk-inexpress'),       // EN: Menu title | IT: Titolo menu
        'manage_options',                           // EN: Capability | IT: Capacità richiesta
        'pk-inexpress',                             // EN: Menu slug | IT: Slug menu principale (kept as WP.org slug)
        'pkinex_render_dashboard_page',             // EN: Callback to render main admin page | IT: Callback per visualizzare pagina admin principale
        'dashicons-database-import',                // EN: Icon | IT: Icona menu
        6                                           // EN: Position | IT: Posizione nel menu
    );

    // EN: Add submenu "Quick Import" under main menu
    // IT: Aggiungi sottomenu "Quick Import" sotto il menu principale
    add_submenu_page(
        'pk-inexpress',
        __('Quick Import', 'pk-inexpress'),
        __('Quick Import', 'pk-inexpress'),
        'manage_options',
        'pkinex-quick-import',
        'pkinex_render_quick_import_page'
    );

    // EN: NEW HOOK: Trigger an action after registering the main menu and submenus
    // IT: NUOVO HOOK: Esegui un hook dopo aver registrato il menu principale e i sottomenu
    // Allows PRO plugin to attach submenus safely
    // Permette al plugin PRO di aggiungere sottomenu senza problemi di priorità
    do_action('pkinex_menu_registered');
}


// ================================
// Enqueue admin scripts and styles for PK InExPress
// ================================

/**
 * EN: Enqueue admin assets only on plugin pages.
 * IT: Esegue enqueue degli asset admin solo sulle pagine del plugin.
 *
 * @param string $hook_suffix The current admin page hook suffix.
 */
function pkinex_admin_enqueue_scripts($hook_suffix)
{

    // Robust check: use $hook_suffix and fallback to $_GET['page']
    // Load assets only on pages that belong to this plugin.
    $is_relevant_hook = (strpos($hook_suffix, 'pk-inexpress') !== false || strpos($hook_suffix, 'pkinex') !== false);
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
    $is_relevant_page = ($page !== '' && (strpos($page, 'pk-inexpress') !== false || strpos($page, 'pkinex') !== false));

    if (! $is_relevant_hook && ! $is_relevant_page) {
        return;
    }

    // ================================
    // REGISTER + ENQUEUE CSS
    // ================================
    $css_file = plugin_dir_path(__FILE__) . 'css/pkinex-inexpress-admin.css';
    $css_url  = plugin_dir_url(__FILE__) . 'css/pkinex-inexpress-admin.css';
    if (file_exists($css_file)) {
        $css_version = filemtime($css_file);
        wp_register_style('pkinex-inexpress-admin', $css_url, array(), $css_version);
        wp_enqueue_style('pkinex-inexpress-admin');
    }

    // ================================
    // REGISTER SCRIPT
    // ================================
    $js_file = plugin_dir_path(__FILE__) . 'js/pkinex-quick-import.js';
    $js_url  = plugin_dir_url(__FILE__) . 'js/pkinex-quick-import.js';
    $js_version = file_exists($js_file) ? filemtime($js_file) : '1.0.0';

        if (file_exists($js_file)) {
        wp_register_script(
            'pkinex-quick-import',
            $js_url,
            array('jquery'),
            $js_version,
            true
        );

        // EN: Actually enqueue the script so it is loaded in the page
        // IT: Effettivamente enqueue dello script per caricarlo nella pagina
        wp_enqueue_script('pkinex-quick-import');
    }


    // ================================
    // PASS PHP DATA TO JS (LOCALIZE)
    // ================================
    // Use the plugin textdomain (match WP.org slug) -> 'pk-inexpress'
    $instructions = array(
        'real'  => wp_kses(
            __(
                '<strong>Import instructions from RealSoftware Management to the Houzez theme</strong><br>
                Enter the XML URL provided in the management software, or request it from RealSoftware.<br>
                For the ID Field Name, enter<strong> "Codice"</strong> (this is the unique ID assigned by the management software to each property).',
                'pk-inexpress'
            ),
            array('strong' => array(), 'br' => array(), 'p' => array())
        ),
        'miogest' => wp_kses(
            __(
                '<strong>Import instructions from MioGest Management to the Houzez theme</strong><br>
                Enter the XML URL provided in the management software, or request it from MioGest.<br>
                For the ID Field Name, enter<strong> "Codice"</strong> (this is the unique ID assigned by the management software to each property).',
                'pk-inexpress'
            ),
            array('strong' => array(), 'br' => array(), 'p' => array())
        ),
    );

    if (wp_script_is('pkinex-quick-import', 'registered')) {
        wp_localize_script(
            'pkinex-quick-import',
            'pkinex_vars',
            array(
                // EN: Instructions text for the current source/target
                // IT: Testo delle istruzioni per sorgente/destinazione corrente
                'instructions'         => $instructions,
                'default_instruction'  => __('Select a service source to see instructions.', 'pk-inexpress'),

                // ======================================
                // EN: Async import configuration (AJAX)
                // IT: Configurazione import asincrona (AJAX)
                // ======================================

                // EN: admin-ajax.php URL for async requests
                // IT: URL di admin-ajax.php per le richieste asincrone
                'ajax_url'             => admin_url('admin-ajax.php'),

                // EN: Nonce used for async import (shared with PHP check)
                // IT: Nonce usato per l'import asincrono (condiviso col controllo PHP)
                'ajax_nonce'           => wp_create_nonce('pkinex_async_import'),

                // EN: Small pause between batches (in milliseconds) to avoid hammering the server
                // IT: Piccola pausa tra un batch e l'altro (in millisecondi) per non sovraccaricare il server
                'async_delay_ms'       => 1500,
            )
        );
    }
}
add_action('admin_enqueue_scripts', 'pkinex_admin_enqueue_scripts');


/**
 * EN: Show admin notices for the plugin
 * EN: - Success notice for temporarily saved XML
 * EN: - Error notice for any import issues
 *
 * IT: Mostra i messaggi di amministrazione del plugin
 * IT: - Messaggio di successo per XML salvato temporaneamente
 * IT: - Messaggio di errore per problemi durante l'importazione
 */
function pkinex_show_admin_notices()
{

    // EN: Only display notices on plugin pages
    // IT: Mostra le notifiche solo nelle pagine del plugin
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';

    if ($page === '' || (strpos($page, 'pkinex') === false && strpos($page, 'pk-inexpress') === false)) {
        return;
    }

    // ===========================
    // EN: Success notice for XML saved temporarily
    // IT: Messaggio di successo per XML salvato temporaneamente
    $xml_transient_key = 'pkinex_xml_text_' . get_current_user_id();
    $xml_text = get_transient($xml_transient_key);

    if ($xml_text) {
        echo '<div class="notice notice-success is-dismissible"><p>'
            . esc_html__('Raw XML text saved temporarily for import.', 'pk-inexpress')
            . '</p></div>';

        // EN: Delete transient after displaying
        // IT: Elimina il transient dopo la visualizzazione
        delete_transient($xml_transient_key);
    }

    // ===========================
    // EN: Error notice for import issues
    // IT: Messaggio di errore per problemi di importazione
    $error_transient_key = 'pkinex_quick_import_error';
    $error_message = get_transient($error_transient_key);

    if ($error_message) {
        echo '<div class="notice notice-error is-dismissible"><p>'
            . esc_html($error_message)
            . '</p></div>';

        // EN: Delete transient after displaying
        // IT: Elimina il transient dopo la visualizzazione
        delete_transient($error_transient_key);
    }
}
add_action('admin_notices', 'pkinex_show_admin_notices');
