<?php

require_once __DIR__ . '/bootstrap.php';

ini_set('max_execution_time', 120);
set_time_limit(120);

$LANG_ES = (int) legacy_config('store.language_es', 4);
$IMG_BASE = legacy_config('store.image_base_url', 'https://example.local/image/');
$LOG_PATH = legacy_config('paths.worker_log', __DIR__ . '/logs/worker.log');

if (isset($_GET['action']) && $_GET['action'] === 'log_tail') {
    header('Content-Type: application/json; charset=utf-8');
    $limit = isset($_GET['limit']) ? max(10, min(200, (int)$_GET['limit'])) : 80;
    if (!file_exists($LOG_PATH)) {
        echo json_encode(['ok' => false, 'message' => 'Aún no hay registros.']);
    } else {
        $lines = file($LOG_PATH, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $tail = array_slice($lines, -$limit);
        echo json_encode([
            'ok' => true,
            'updated' => date('H:i:s'),
            'log' => implode("\n", $tail)
        ]);
    }
    exit;
}

if (isset($_GET['action']) && $_GET['action'] === 'show_log') {
    include('./inc/header.php');
    $logEndpoint = 'productos_bulk_update.php?action=log_tail&limit=120';
    echo "<div class='container'>
            <h3>📊 Progreso del worker</h3>
            <p>Puedes dejar esta ventana abierta para monitorear la cola en tiempo real.</p>
            <div class='row'>
              <div class='twelve columns'>
                <div class='log-panel'>
                  <div class='log-panel__header'>
                    <strong>Últimas entradas</strong>
                    <span id='log-status' class='log-panel__status'>Actualizando...</span>
                  </div>
                  <pre id='log-viewer' class='log-panel__body'>Cargando log...</pre>
                </div>
              </div>
            </div>
            <div class='row'>
              <div class='twelve columns'>
                <button onclick=\"window.location.href='productos_bulk_update.php'\" class='button last'>← Volver al listado</button>
              </div>
            </div>
          </div>
          <script>
          (function(){
            const viewer = document.getElementById('log-viewer');
            const status = document.getElementById('log-status');
            const endpoint = '$logEndpoint';
            const refresh = () => {
              fetch(endpoint + '&_=' + Date.now(), {cache:'no-store'})
                .then(r => r.json())
                .then(data => {
                  if (!data.ok) {
                    viewer.textContent = data.message || 'Sin datos disponibles.';
                    status.textContent = 'Sin registros';
                    return;
                  }
                  viewer.textContent = data.log || 'Sin registros recientes.';
                  status.textContent = 'Actualizado ' + (data.updated || '');
                  viewer.scrollTop = viewer.scrollHeight;
                })
                .catch(() => {
                  status.textContent = 'Error al actualizar';
                });
            };
            refresh();
            setInterval(refresh, 5000);
          })();
          </script>";
    include('./inc/footer.php');
    exit;
}

include('./inc/header.php');

$db = legacy_new_mysqli();
if ($db->connect_errno) die("❌ Error DB: " . $db->connect_error);

/* ============================================
   🧾 Insertar productos seleccionados a la cola
   ============================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['productos'])) {
    $productos = $_POST['productos'];
    $inserted = 0;
    foreach ($productos as $pid) {
        $pid = (int)$pid;
        $db->query("INSERT IGNORE INTO oc_product_queue (product_id) VALUES ($pid)");
        if ($db->affected_rows > 0) {
            $inserted++;
        }
    }
    $logEndpoint = 'productos_bulk_update.php?action=log_tail&limit=120';
    echo "<div class='container'>
            <h3>✅ $inserted productos añadidos a la cola.</h3>
            <p>El worker los procesará automáticamente por orden de llegada. Puedes seguir el progreso en tiempo real debajo.</p>
            <div class='row'>
              <div class='twelve columns'>
                <div class='log-panel'>
                  <div class='log-panel__header'>
                    <strong>📊 Log del worker (últimas entradas)</strong>
                    <span id='log-status' class='log-panel__status'>Actualizando...</span>
                  </div>
                  <pre id='log-viewer' class='log-panel__body'>Cargando log...</pre>
                </div>
              </div>
            </div>
            <div class='row'>
              <div class='twelve columns'>
                <button class='button button-primary' onclick=\"window.location.href='productos_bulk_update.php'\">← Volver</button>
              </div>
            </div>
          </div>
          <script>
          (function(){
            const viewer = document.getElementById('log-viewer');
            const status = document.getElementById('log-status');
            const endpoint = '$logEndpoint';
            const refresh = () => {
              fetch(endpoint + '&_=' + Date.now(), {cache: 'no-store'})
                .then(r => r.json())
                .then(data => {
                  if (!data.ok) {
                    viewer.textContent = data.message || 'Sin datos disponibles.';
                    status.textContent = 'Sin registros';
                    return;
                  }
                  viewer.textContent = data.log || 'Sin registros recientes.';
                  status.textContent = 'Actualizado ' + (data.updated || '');
                  viewer.scrollTop = viewer.scrollHeight;
                })
                .catch(() => {
                  status.textContent = 'Error al actualizar';
                });
            };
            refresh();
            setInterval(refresh, 5000);
          })();
          </script>";
    include('./inc/footer.php');
    exit;
}

/* ============================================
   📋 Listado de productos activos no procesados
   ============================================ */
$per_page = isset($_GET['per_page']) ? max(10, min(200, (int)$_GET['per_page'])) : 50;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;

$sql_total = "
SELECT COUNT(*) AS total
FROM oc_product p
WHERE p.status = 1
  AND p.product_id NOT IN (SELECT product_id FROM oc_product_queue)";
$res_total = $db->query($sql_total);
$total_rows = $res_total ? (int)$res_total->fetch_assoc()['total'] : 0;
$total_pages = max(1, (int)ceil($total_rows / $per_page));
if ($page > $total_pages) {
    $page = $total_pages;
}
$offset = ($page - 1) * $per_page;

$q = "
SELECT p.product_id, p.image, d1.name, LEFT(d1.description, 250) AS descripcion
FROM oc_product p
LEFT JOIN oc_product_description d1 
  ON p.product_id=d1.product_id AND d1.language_id=$LANG_ES
WHERE p.status = 1 
  AND p.product_id NOT IN (SELECT product_id FROM oc_product_queue)
ORDER BY p.product_id ASC
LIMIT $per_page OFFSET $offset";
$res = $db->query($q);
?>

<div class="container">
  <h3>🧾 Productos pendientes de optimización SEO</h3>
  <div class="row">
    <div class="eight columns">
      <p>Total pendientes: <strong><?php echo $total_rows; ?></strong><br>
      Página <strong><?php echo $page; ?></strong> de <strong><?php echo $total_pages; ?></strong></p>
    </div>
    <div class="four columns">
      <form method="GET" class="row u-cf">
        <div class="six columns">
          <label for="per_page">products</label>
          </div>
        <div class="six columns">
          <select class="u-full-width" name="per_page" id="per_page" onchange="this.form.submit()">
            <?php foreach ([25, 50, 100, 150, 200] as $opt): ?>
              <option value="<?php echo $opt; ?>" <?php echo $opt==$per_page?'selected':''; ?>><?php echo $opt; ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <input type="hidden" name="page" value="1">
        <noscript><div class="four columns"><button type="submit" class="button">Actualizar</button></div></noscript>
      </form>
    </div>
  </div>

  <?php if ($total_rows === 0): ?>
    <div class="row">
      <div class="twelve columns alert-box">
        <p>No hay productos pendientes de encolar.</p>
        <button type="button" class="button" onclick="window.location.href='productos_bulk_update.php?action=show_log'">
          Ver progreso del worker
        </button>
      </div>
    </div>
  <?php endif; ?>

  <form method="POST">
    <table class="u-full-width">
      <thead>
        <tr><th></th><th>ID</th><th>Imagen</th><th>Nombre</th><th>Descripción</th></tr>
      </thead>
      <tbody>
      <?php while($r=$res->fetch_assoc()){
          $img=!empty($r['image'])?$IMG_BASE.htmlspecialchars($r['image']):"https://via.placeholder.com/80x80?text=No+Image"; ?>
        <tr>
          <td><input type="checkbox" name="productos[]" value="<?php echo $r['product_id']; ?>" checked></td>
          <td><?php echo $r['product_id']; ?></td>
          <td><img src="<?php echo $img; ?>" alt=""></td>
          <td><?php echo htmlspecialchars($r['name']); ?></td>
          <td><div class="table-description"><?php echo nl2br(strip_tags($r['descripcion'])); ?></div></td>
        </tr>
      <?php } ?>
      </tbody>
    </table>
    <div class="row">
      <div class="twelve columns">
        <button type="submit" class="button button-primary">➕ Encolar seleccionados</button>
      </div>
    </div>
    <input type="hidden" name="current_page" value="<?php echo $page; ?>">
    <input type="hidden" name="current_per_page" value="<?php echo $per_page; ?>">
  </form>

  <?php
    $queryBase = function($targetPage) use ($per_page) {
        return 'productos_bulk_update.php?page=' . $targetPage . '&per_page=' . $per_page;
    };
  ?>
  <div class="row pagination-row">
    <div class="twelve columns">
      <?php if($page > 1): ?>
        <a class="button" href="<?php echo $queryBase($page-1); ?>">← Página anterior</a>
      <?php else: ?>
        <span class="button disabled">← Página anterior</span>
      <?php endif; ?>

      <span class="pagination-meta">Página <?php echo $page; ?> de <?php echo $total_pages; ?></span>

      <?php if($page < $total_pages): ?>
        <a class="button" href="<?php echo $queryBase($page+1); ?>">Página siguiente →</a>
      <?php else: ?>
        <span class="button disabled">Página siguiente →</span>
      <?php endif; ?>
    </div>
  </div>
</div>

<?php include('./inc/footer.php'); ?>
