<?php
// EN: If this file is called directly, abort.
// IT: Se questo file viene chiamato direttamente, interrompi.
if (! defined('ABSPATH')) exit; // Exit
/*
 * FILE: run-quick-import.php | DESCRIPTION: Starts import based on saved settings
 * FROM → admin-init.php (POST action) | TO → Dispatcher
 * FUNCTIONS: pk_inexpress_run_import() - starts and manages the import process
 */

/**
 * EN: Starts the import based on saved settings
 * EN: Checks user capabilities and nonce for security.
 * EN: Retrieves POST data and saved options.
 * EN: Loads the appropriate runner class and executes import.
 * EN: Redirects after completion.
 *
 * IT: Avvia l'importazione basata sulle impostazioni salvate
 * IT: Verifica capacità utente e nonce per sicurezza.
 * IT: Recupera dati POST e opzioni salvate.
 * IT: Carica la classe runner appropriata ed esegue l'importazione.
 * IT: Reindirizza al termine.
 */
function pkinex_handle_run_quick_import()
{
    // EN: Check user capabilities and verify nonce for security
    // IT: Verifica capacità utente e nonce per sicurezza
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('Unauthorized user', 'pk-inexpress'));
    }

    check_admin_referer('pkinex_run_quick_import', 'pkinex_inexpress_nonce');


    // Retrieve saved options
    $service_source = get_option('pkinex_service_source');
    $service_target = get_option('pkinex_service_target');
    $source_type    = get_option('pkinex_source_type');


    // EN: Retrieve saved options
    // IT: Recupera opzioni salvate
    $xml_url      = get_option('pkinex_source_url');
    $id_name = get_option('pkinex_id_name');

    // EN: If source type is 'file', get file feature to be added in the future
    // EN: Otherwise, use the saved XML URL option
    // IT: Se il tipo sorgente è 'filr', prende il file funzione da aggiungere in futuro
    // IT: Altrimenti usa l'URL XML salvato nelle opzioni
    if ($source_type === 'url') {
        $source_data = $xml_url;
    }

    // EN: Build the runner path based on service target
    // IT: Costruisce il percorso del runner basato sul target del servizio
    $runner_path = PKINEX_INEXPRESS_DIR . 'includes/services/' . strtolower($service_target) . '/class-pkinex-run-' . strtolower($service_source) . '-' . strtolower($service_target) . '.php';

    // EN: Check if runner file exists, otherwise terminate with error
    // IT: Controlla se il file runner esiste, altrimenti termina con errore
    if (!file_exists($runner_path)) {
        wp_die(esc_html__('Runner not found for selected target: ', 'pk-inexpress') . esc_html($runner_path)); // EN
        // IT: Runner non trovato per il target selezionato: 
    }

    // EN: Include the runner class file
    // IT: Include il file della classe runner
    require_once $runner_path;

    // EN: Instantiate the runner class and run the import
    // IT: Istanzia la classe runner ed esegue l'importazione
    try {
        $runner = new PKINEX_Dispatcher($source_data, $source_type);
        $runner->pkinex_dispatcher();
    } catch (Exception $e) {
        // Salva messaggio d'errore in transient per mostrarlo in pagina apposita
        set_transient('pkinex_xml_error', $e->getMessage(), 60);


        // Redirect to custom error page (must be registered beforehand)
        wp_safe_redirect(admin_url('admin.php?page=pk-inexpress'));
        exit;
    }

    // EN: Redirect to admin page with success parameter
    // IT: Reindirizza alla pagina admin con parametro di successo
    $redirect_url = add_query_arg(
        array(
            'page'     => 'pk-inexpress',
            'imported' => 'ok',
        ),
        admin_url('admin.php')
    );

    wp_safe_redirect($redirect_url);
    exit;
}
