<?php
// EN: If this file is called directly, abort.
// IT: Se questo file viene chiamato direttamente, interrompi.
if (! defined('ABSPATH')) exit; // Exit
/*
 * FILE: view-automatic.php | DESCRIPTION: Renders the automatic import configuration and process pages
 * FROM → admin-init.php (menu callback) | TO → pkinex_render_step1(), pkinex_render_step2(), admin-post.php (POST handlers)
 * FUNCTIONS: pkinex_render_automatic_page() - main dispatcher for steps
 *            pkinex_render_step1() - renders step 1 form
 *            pkinex_render_step2() - renders step 2 summary and import
 */

/**
 * EN: Main function to render the automatic import page.
 * EN: Shows notices for saved settings and completed import.
 * EN: Dispatches between step 1 (configuration) and step 2 (import summary).
 *
 * IT: Funzione principale che visualizza la pagina di importazione automatica.
 * IT: Mostra notifiche per impostazioni salvate e importazione completata.
 * IT: Gestisce la visualizzazione del passo 1 (configurazione) e passo 2 (riepilogo importazione).
 */
function pkinex_render_quick_import_page()
{
  // Check nonce **only if it exists** in the URL
  if (isset($_GET['_wpnonce'])) {
    check_admin_referer('pkinex_quick_import', '_wpnonce');
  }

  $step      = isset($_GET['step']) ? absint($_GET['step']) : 1;
  $saved     = isset($_GET['saved']) ? sanitize_text_field(wp_unslash($_GET['saved'])) : '';
  $imported  = isset($_GET['imported']) ? sanitize_text_field(wp_unslash($_GET['imported'])) : '';


  if ($saved === 'ok') {
    echo '<div class="notice notice-success"><p>' . esc_html__('Successfully Saved', 'pk-inexpress') . '</p></div>'; // EN
    // IT: Salvato con successo.
  }

  if ($imported === 'ok') {
    echo '<div class="notice notice-success"><p>' . esc_html__('Import completed', 'pk-inexpress') . '</p></div>'; // EN
    // IT: Importazione completata.
  }

  if ($step === 2) {
    pkinex_render_step2();
  } else {
    pkinex_render_step1();
  }
}

/**
 * EN: Step 1: displays configuration form and service selection.
 *
 * IT: Passo 1: visualizza il modulo di configurazione e la scelta del servizio.
 */
function pkinex_render_step1()
{


  $source_url = get_option('pkinex_source_url', '');
  $id_name = get_option('pkinex_id_name', '');
  $service_source = get_option('pkinex_service_source', 'real');
  $service_target = get_option('pkinex_service_target', 'houzez');
  $source_type = get_option('pkinex_source_type', 'url');


?>
  <div class="wrap">
    <h1><?php esc_html_e('Step 1: Configure Import', 'pk-inexpress'); ?></h1>
    <!--  <form method="get" action=""> -->
    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">

      <?php wp_nonce_field('pkinex_save_quick_options', 'pkinex_inexpress_nonce'); ?>
      <input type="hidden" name="action" value="pkinex_handle_save_quick_options">
      <input type="hidden" name="step" value="2">
      <input type="hidden" name="page" value="pk-inexpress">

      <table class="form-table">
        <tr>
          <th scope="row"><label for="pkinex_service_source"><?php esc_html_e('Source Service', 'pk-inexpress'); ?></label></th>
          <td>
            <select name="pkinex_service_source" id="pkinex_service_source">
              <option value="real" <?php selected($service_source, 'real'); ?>>RealSmart</option>
              <option value="miogest" <?php selected($service_source, 'miogest'); ?>>MioGest</option>
            </select>
            <p class="description">
              <?php esc_html_e('choose the name of the management system or source service from which to take the data to import', 'pk-inexpress'); ?>
            </p>
          </td>
        </tr>
        <tr>
          <th scope="row"><label for="pkinex_service_target"><?php esc_html_e('Target Service', 'pk-inexpress'); ?></label></th>
          <td>
            <select name="pkinex_service_target" id="pkinex_service_target">
              <option value="houzez" <?php selected($service_target, 'houzez'); ?>>Houzez</option>
              <option value="post" disabled>Other</option>
            </select>
            <p class="description">
              <?php esc_html_e('choose the theme or service you want to populate', 'pk-inexpress'); ?>
            </p>
          </td>
        </tr>
        <tr>
          <th scope="row"><label for="pkinex_source_type"><?php esc_html_e('Source Type', 'pk-inexpress'); ?></label></th>
          <td>
            <select name="pkinex_source_type" id="pkinex_source_type" required>
              <option value="url" <?php selected($source_type, 'url'); ?>>URL</option>
              <option value="text" disabled>File</option>
            </select>
            <p class="description">
              <?php esc_html_e('select the data format type', 'pk-inexpress'); ?>
            </p>
          </td>
        </tr>
        <tr>
          <th scope="row"><label for="pkinex_source_url"><?php esc_html_e('XML URL or Text', 'pk-inexpress'); ?></label></th>
          <td>
            <input type="text" name="pkinex_source_url" id="pkinex_source_url" value="<?php echo esc_attr($source_url); ?>" class="regular-text">
          </td>
        </tr>
        <tr>
          <th scope="row"><label for="pkinex_id_name"><?php esc_html_e('ID Field Name', 'pk-inexpress'); ?></label></th>
          <td><input type="text" name="pkinex_id_name" id="pkinex_id_name" value="<?php echo esc_attr($id_name); ?>" class="regular-text">
            <p class="description">
              <?php esc_html_e('Enter the field you want to use as the identifier for the individual item', 'pk-inexpress'); ?>
            </p>
          </td>

        </tr>
        <!-- Istruzioni sotto il form -->
        <tr>
          <td colspan="2">
            <div id="pkinex_instructions" style="background:#f9f9f9;padding:10px;margin-top:15px;">
              <?php esc_html_e('Select a source service to see instructions.', 'pk-inexpress'); ?>
            </div>
          </td>
        </tr>
      </table>
      <?php submit_button(__('Save and Go to Step 2 →', 'pk-inexpress')); ?>
    </form>
  </div>

  <!-- NOTICE PRO -->
  <div style="border-left:4px solid #0073aa; padding:10px; margin-top:30px; font-size:13px;">
    <strong><?php esc_html_e('Pro Version Available!', 'pk-inexpress'); ?></strong>
    <p style="margin:5px 0;">
      <?php esc_html_e('With the Pro version you can schedule multiple imports using WP-Cron, so everything runs fully automatically.', 'pk-inexpress'); ?>
    </p>
    <p style="margin:0; font-style:italic; color:#555;">
      <?php esc_html_e('This notice is informative only; your free version still works fully.', 'pk-inexpress'); ?>
    </p>
  </div>


<?php
}

/**
 * FILE: view-automatic.php
 * DESCRIPTION:
 * EN: Step 2: Displays a summary of automatic import settings and allows the user to start the import.
 * IT: Passo 2: Mostra un riepilogo delle impostazioni di importazione automatica e permette di avviare l'importazione.
 */
function pkinex_render_step2()
{
  // ===============================
  // FETCH OPTIONS / Recupera le opzioni
  // ===============================
  $service_source = get_option('pkinex_service_source', ''); // EN: Source service selected / IT: Servizio sorgente selezionato
  $service_target = get_option('pkinex_service_target', ''); // EN: Target service / IT: Servizio di destinazione
  $source_type = get_option('pkinex_source_type', 'url');    // EN: Source type: URL or Text / IT: Tipo sorgente: URL o Testo
  $source_url = get_option('pkinex_source_url', '');          // EN: Saved URL option / IT: URL salvato
  $id_name = get_option('pkinex_id_name', '');                // EN: ID field name / IT: Nome campo ID


?>
  <div class="wrap">
    <h1><?php esc_html_e('Step 2: Summary and Import', 'pk-inexpress'); ?></h1>

    <!-- EN: Display summary of import settings -->
    <!-- IT: Mostra riepilogo delle impostazioni di importazione -->
    <p>

      <?php
      printf(
        /* translators: 1: service source, 2: service target, 3: source type, 4: source value, 5: ID field name */
        esc_html__('You are about to import from  %1$s  to %2$s using %3$s with value %4$s and ID field %5$s.', 'pk-inexpress'),
        esc_html($service_source),
        esc_html($service_target),
        esc_html(strtoupper($source_type)),
        esc_html($source_type === 'url' ?  $source_url : 'Data no url'),
        esc_html($id_name)
      );
      ?>
    </p>

    <!-- EN: Form to start automatic import -->
    <!-- IT: Form per avviare l'importazione automatica -->
    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
      <?php wp_nonce_field('pkinex_run_quick_import', 'pkinex_inexpress_nonce'); ?>
      <input type="hidden" name="action" value="pkinex_handle_run_quick_import">
      <input type="hidden" name="service_source" value="<?php echo esc_attr($service_source); ?>">
      <input type="hidden" name="service_target" value="<?php echo esc_attr($service_target); ?>">
      <input type="hidden" name="source_type" value="<?php echo esc_attr($source_type); ?>">
      <?php submit_button(
        __('Synchronous import is disabled. Use async import below.', 'pk-inexpress'),
        'secondary',
        'disabled-sync-import',
        false,
        array('disabled' => 'disabled', 'style' => 'opacity:0.5; cursor:not-allowed;')
      ); ?>

    </form>


    <?php
    // EN: Async import panel (beta)
    // IT: Pannello per l'import asincrono (beta)
    ?>
    <div id="pkinex-async-panel" class="pkinex-async-panel" style="margin-top: 30px;">

      <h2><?php esc_html_e('Async Import (beta)', 'pk-inexpress'); ?></h2>

      <p>
        <?php esc_html_e(
          'Async import allows you to process properties in small batches to prevent server timeouts and improve reliability.',
          'pk-inexpress'
        ); ?>
      </p>

      <p>
        <button type="button"
          class="button button-primary"
          id="pkinex-async-start-btn">
          <?php esc_html_e('Start async import', 'pk-inexpress'); ?>
        </button>

        <button type="button"
          class="button"
          id="pkinex-async-cancel-btn"
          disabled>
          <?php esc_html_e('Cancel', 'pk-inexpress'); ?>
        </button>
      </p>

      <div id="pkinex-async-status" class="pkinex-async-status" style="margin-top: 10px;">
        <p>
          <strong><?php esc_html_e('Status:', 'pk-inexpress'); ?></strong>
          <span id="pkinex-async-status-text">
            <?php esc_html_e('Idle (waiting to start)…', 'pk-inexpress'); ?>
          </span>
        </p>
        <p>
          <strong><?php esc_html_e('Progress:', 'pk-inexpress'); ?></strong>
          <span id="pkinex-async-progress">0 / 0</span>
        </p>

        <div id="pkinex-async-errors"
          class="notice notice-error"
          style="display:none; margin-top: 10px;"></div>
      </div>
    </div>

    <!-- EN: Back link to step 1 -->
    <!-- IT: Link per tornare al passo 1 -->
    <p><a href="<?php echo esc_url(add_query_arg('step', 1)); ?>">← <?php esc_html_e('Go back', 'pk-inexpress'); ?></a></p>
  </div>
<?php
}
