<?php

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

/**
 * FILE: class-pk-inex-dispatcher.php
 * FROM → Called from:
 *          - quick cron (Pro)
 *          - run-quick-import.php
 * TO →   - services/{target}/class-pk-inex-run-{source}-{target}.php
 *         (example: services/houzez/class-pk-inex-run-real-houzez.php)
 *
 * FUNCTION:
 * EN: Central dispatcher class to launch the correct runner class for import,
 *     loading settings from saved options and passing source data accordingly.
 * IT: Classe dispatcher centrale per avviare il runner corretto per l'importazione,
 *     caricando le impostazioni salvate e passando i dati sorgente.
 */
class PKINEX_Dispatcher
{
    /**
     * @var mixed $source_data Can be XML string, URL or SimpleXMLElement (depends on source_type)
     */
    protected $source_data;

    /**
     * @var string $source_type Defines if source_data is 'url', 'text', etc.
     */
    protected $source_type;

    /**
     * Constructor
     * 
     * @param mixed $source_data  XML string, URL or text source
     * @param string $source_type Source type ('url', 'text', etc.)
     */
    public function __construct($source_data, $source_type)
    {
        $this->source_data = $source_data; // In run-quick-import already indicates if URL or text or future file
        $this->source_type = $source_type;
    
    }

    /**
     * EN: Runs the correct runner based on saved plugin options.
     * IT: Esegue il runner corretto in base alle opzioni salvate del plugin.
     */
    public function pkinex_dispatcher()
    {
        // =========================
        // 1. RETRIEVE SETTINGS
        // =========================
        // EN: Get plugin settings from WordPress options.
        // IT: Recupera le impostazioni del plugin dalle opzioni di WordPress.
        $id_name       = get_option('pkinex_id_name');          // ID field name
        $service_source  = get_option('pkinex_service_source');   // e.g., "real"
        $service_target  = get_option('pkinex_service_target');   // e.g., "houzez"

        // EN: If any essential option is missing, abort.
        // IT: Se manca un'opzione essenziale, interrompe l'esecuzione.
        if (empty($id_name) || empty($service_source) || empty($service_target)) {
            wp_die(
                esc_html__('Missing import configuration. Please check your plugin settings.', 'pk-inexpress')
            );
        }

        // =========================
        // 2. DETERMINE RUNNER FILE AND CLASS
        // =========================
        // EN: Build the path for the correct target runner.
        // IT: Costruisce il percorso per il runner corretto in base al target.
        $runner_file  = PKINEX_INEXPRESS_DIR . 'includes/services/' . strtolower($service_target)
            . '/class-pkinex-run-' . strtolower($service_source) . '-' . strtolower($service_target) . '.php';

        // EN: Construct the runner class name as PKINEX_Runner + capitalized source + capitalized target
        // IT: Costruisce il nome della classe runner come PKINEX_Runner + source e target con iniziale maiuscola
        $runner_class = 'PKINEX_Runner' . ucfirst($service_source) . ucfirst($service_target);

        // EN: Check if the runner file exists before requiring it.
        // IT: Verifica se il file del runner esiste prima di includerlo.
        if (!file_exists($runner_file)) {
           
            wp_die(
                sprintf(
                     /* translators: %s: Full path of the missing runner file */
                    esc_html__('Runner file not found: %s', 'pk-inexpress'),
                    esc_html($runner_file)
                )
            );
        }
        require_once $runner_file;

        // EN: Check if the class exists before instantiating.
        // IT: Verifica se la classe esiste prima di istanziarla.
        if (!class_exists($runner_class)) {
            
            wp_die(
                sprintf(
                    /* translators: %s: class of the missing runner file */
                    esc_html__('Runner class not found: %s', 'pk-inexpress'),
                    esc_html($runner_class)
                )
            );
        }

        // =========================
        // 3. RUN IMPORT
        // =========================
        // EN: Create runner instance with loaded data and execute import.
        // IT: Crea l’istanza del runner con i dati caricati ed esegue l’importazione.
        $runner = new $runner_class($this->source_data, $id_name, $this->source_type);

        // EN: We assume each runner class has a method named `pkinex_runner_{source}_{target}`.
        // IT: Si presume che ogni runner abbia un metodo chiamato `pkinex_runner_{source}_{target}`.
        $runner_method = 'pkinex_runner_' . strtolower($service_source) . '_' . strtolower($service_target);

        if (method_exists($runner, $runner_method)) {
            $runner->$runner_method();
        } 
    }
}
