<?php
/* ============================
   productos_modificados.php
   ============================ */

require_once __DIR__ . '/bootstrap.php';

$LANG_ES = (int) legacy_config('store.language_es', 4);
$LANG_EN = (int) legacy_config('store.language_en', 1);
$IMG_BASE = legacy_config('store.image_base_url', 'https://example.local/image/');
$PRODUCT_BASE = legacy_config('store.product_base_url', 'https://example.local/index.php?route=product/product&product_id=');

/* ---- Conexión BD ---- */
$db = legacy_new_mysqli();
if ($db->connect_errno) {
    header('Content-Type: text/plain; charset=utf-8');
    http_response_code(500);
    echo "DB Error: " . $db->connect_error;
    exit;
}

/* ---- AJAX ---- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json; charset=utf-8');

    // Toggle individual
    if (isset($_POST['pid']) && isset($_POST['toggle'])) {
        $pid   = (int)$_POST['pid'];
        $state = (int)($_POST['toggle'] ? 1 : 0);
        $ok = $db->query("UPDATE oc_product_queue SET needs_verify=$state WHERE product_id=$pid");
        echo json_encode(['ok'=>$ok, 'state'=>$state]);
        exit;
    }

    // Auto-marcar faltantes
    if (isset($_POST['autoMark'])) {
        $ok = $db->query("UPDATE oc_product_queue 
                          SET needs_verify=1
                          WHERE processed=1 AND 
                                (product_id IN (
                                  SELECT p.product_id FROM oc_product p
                                  LEFT JOIN oc_product_description d1 ON p.product_id=d1.product_id AND d1.language_id=$LANG_ES
                                  LEFT JOIN oc_product_description d2 ON p.product_id=d2.product_id AND d2.language_id=$LANG_EN
                                  WHERE (d1.description IS NULL OR d1.description='') 
                                     OR (d2.description IS NULL OR d2.description='')
                                ))");
        echo json_encode(['ok'=>$ok]);
        exit;
    }

    // 🔁 Reprocesar Needs Verify
    if (isset($_POST['reprocessNeeds'])) {
        $ok = $db->query("UPDATE oc_product_queue 
                          SET processed=0, log=NULL 
                          WHERE needs_verify=1");
        echo json_encode(['ok'=>$ok]);
        exit;
    }
}

/* ---- Vista ---- */
include('./inc/header.php'); // aquí ya se incluye custom.css

/* ---- Paginación ---- */
$per_page = 50;
$page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $per_page;

$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$filter_missing = isset($_GET['missing']) ? (int)$_GET['missing'] : 0;

$conditions = ["q.processed=1"];
if ($search !== '') {
    $safe = $db->real_escape_string($search);
    $conditions[] = "(d1.name LIKE '%$safe%' OR d2.name LIKE '%$safe%')";
}
if ($filter_missing) {
    $conditions[] = "(
        (d1.description IS NULL OR d1.description='') 
        OR (d2.description IS NULL OR d2.description='')
        OR (d1.meta_description IS NULL OR d1.meta_description='')
        OR (d2.meta_description IS NULL OR d2.meta_description='')
    )";
}
$where = implode(' AND ', $conditions);

$res_total = $db->query("SELECT COUNT(*) AS t
FROM oc_product_queue q
JOIN oc_product p ON q.product_id=p.product_id
LEFT JOIN oc_product_description d1 ON p.product_id=d1.product_id AND d1.language_id=$LANG_ES
LEFT JOIN oc_product_description d2 ON p.product_id=d2.product_id AND d2.language_id=$LANG_EN
WHERE $where");
$total = $res_total ? (int)$res_total->fetch_assoc()['t'] : 0;
$total_pages = max(1, ceil($total / $per_page));

$sql = "
SELECT p.product_id,p.image,
       d1.description AS descripcion_es,
       d2.description AS descripcion_en,
       d1.name AS nombre_es,
       d2.name AS nombre_en,
       q.processed_at,q.needs_verify
FROM oc_product_queue q
JOIN oc_product p ON q.product_id=p.product_id
LEFT JOIN oc_product_description d1 ON p.product_id=d1.product_id AND d1.language_id=$LANG_ES
LEFT JOIN oc_product_description d2 ON p.product_id=d2.product_id AND d2.language_id=$LANG_EN
WHERE $where
ORDER BY q.processed_at DESC
LIMIT $per_page OFFSET $offset";
$res = $db->query($sql);
?>

<div class="container">
  <h3>🧾 Productos modificados</h3>
  <p>Total: <b><?php echo $total; ?></b> — Página <b><?php echo $page; ?></b> de <b><?php echo $total_pages; ?></b></p>

 <form method="GET">
  <div class="row" style="margin-bottom: 0;">
    <div class="nine columns">
      <input type="text"
             id="search-name"
             name="q"
             value="<?php echo htmlspecialchars($search); ?>"
             placeholder="Filtrar por nombre..."
             class="u-full-width">
    </div>
    <div class="three columns">
      <label for="missing" class="u-pull-right" style="margin-top:8px;">
        <input type="checkbox"
               id="missing"
               name="missing"
               value="1"
               <?php echo $filter_missing ? 'checked' : ''; ?>>
        Missing
      </label>
    </div>
  </div>

  <div class="row">
    <div class="six columns">
      <button type="submit" class="button button-primary u-full-width">Aplicar</button>
    </div>
    <div class="six columns">
      <a href="productos_modificados.php" class="button u-full-width">Limpiar</a>
    </div>
  </div>
</form>


  <div class="row toolbar">
    <div class="six columns">
      <button class="button u-full-width" onclick="autoMark()" type="button">⚙️ Auto-marcar faltantes</button>
    </div>
    <div class="six columns">
      <button class="button u-full-width" onclick="reprocessNeeds()" type="button">🔁 Reprocesar Needs Verify</button>
    </div>
  </div>

  <table class="u-full-width">
    <tr><th>Imagen</th><th>Descripciones</th></tr>
    <?php while($r=$res->fetch_assoc()):
      $img = !empty($r['image']) ? $IMG_BASE.htmlspecialchars($r['image']) : "https://via.placeholder.com/160";
      $url = $PRODUCT_BASE.$r['product_id'];
      $fecha = $r['processed_at']?date('d/m/Y H:i',strtotime($r['processed_at'])):'-';
      $has_en = !empty(trim($r['descripcion_en']));
      $has_es = !empty(trim($r['descripcion_es']));
      $flag_html = $r['needs_verify']
        ? '<span class="badge warn">⚠️ Needs verify</span>'
        : '<span class="badge ok">✔ Verified</span>';
      $btn_text = $r['needs_verify'] ? '✅ Mark OK' : '⚠️ Mark Needs Verify';
      $btn_cls  = $r['needs_verify'] ? 'toggle-btn active' : 'toggle-btn';
    ?>
    <tr>
      <td rowspan="2" style="text-align:center;width:180px;">
        <a href="<?php echo $url;?>" target="_blank"><img src="<?php echo $img;?>" alt=""></a>
        <div class="idbox">
          ID <?php echo $r['product_id'];?><br>
          <small><?php echo htmlspecialchars($r['nombre_es'] ?: $r['nombre_en'] ?: ''); ?></small><br>
          <small><?php echo $fecha;?></small><br>
          <div id="flag-<?php echo $r['product_id'];?>"><?php echo $flag_html;?></div>
          <button class="<?php echo $btn_cls;?>" id="btn-<?php echo $r['product_id'];?>"
                  onclick="toggleVerify(<?php echo $r['product_id'];?>)">
            <?php echo $btn_text;?>
          </button>
        </div>
      </td>
      <td>
        <div class="lang-title">🇬🇧 English
          <span class="badge <?php echo $has_en?'ok':'miss';?>"><?php echo $has_en?'OK':'Missing';?></span>
        </div>
        <div class="lang-section"><?php echo $has_en?$r['descripcion_en']:'<i>No data</i>';?></div>
      </td>
    </tr>
    <tr>
      <td>
        <div class="lang-title">🇪🇸 Español
          <span class="badge <?php echo $has_es?'ok':'miss';?>"><?php echo $has_es?'OK':'Missing';?></span>
        </div>
        <div class="lang-section"><?php echo $has_es?$r['descripcion_es']:'<i>No data</i>';?></div>
      </td>
    </tr>
    <?php endwhile;?>
  </table>

  <?php
    $queryBase = function($targetPage) use ($search, $filter_missing) {
        $params = ['page'=>$targetPage];
        if ($search !== '') $params['q'] = $search;
        if ($filter_missing) $params['missing'] = 1;
        return 'productos_modificados.php?' . http_build_query($params);
    };
  ?>
  <div class="pagination">
    <?php if($page>1):?>
      <a href="<?php echo $queryBase($page-1);?>">← Prev</a>
    <?php else:?>
      <a class="disabled">← Prev</a>
    <?php endif;?>
    <span>Página <?php echo $page;?> de <?php echo $total_pages;?></span>
    <?php if($page<$total_pages):?>
      <a href="<?php echo $queryBase($page+1);?>">Next →</a>
    <?php else:?>
      <a class="disabled">Next →</a>
    <?php endif;?>
  </div>
</div>

<script>
function toggleVerify(pid){
  const btn  = document.getElementById('btn-'+pid);
  const flag = document.getElementById('flag-'+pid);
  const active = btn.classList.contains('active');
  const next = active ? 0 : 1;
  const params = new URLSearchParams({pid:pid, toggle:next});
  fetch(window.location.pathname+window.location.search,{
    method:'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body:params.toString()
  }).then(r=>r.json()).then(j=>{
    if(!j.ok){alert('Error al actualizar');return;}
    if(j.state===1){
      btn.classList.add('active');
      btn.textContent='✅ Mark OK';
      flag.innerHTML='<span class="badge warn">⚠️ Needs verify</span>';
    }else{
      btn.classList.remove('active');
      btn.textContent='⚠️ Mark Needs Verify';
      flag.innerHTML='<span class="badge ok">✔ Verified</span>';
    }
  });
}

function autoMark(){
  if(!confirm('¿Marcar automáticamente como "Need verification" todos los productos con descripciones faltantes?'))return;
  fetch('',{
    method:'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body:'autoMark=1'
  }).then(r=>r.json()).then(j=>{
    if(j.ok){alert('Productos con descripciones faltantes marcados como Need Verify.');location.reload();}
    else alert('Error al marcar.');
  });
}

function reprocessNeeds(){
  if(!confirm('¿Reprocesar todos los productos marcados como "Needs Verify"?'))return;
  fetch('',{
    method:'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body:'reprocessNeeds=1'
  })
  .then(r=>r.json())
  .then(j=>{
    if(j.ok){
      alert('Los productos "Needs Verify" han sido marcados como pendientes para reprocesar. El worker los regenerará.');
      location.reload();
    } else alert('Error al actualizar.');
  })
  .catch(()=>alert('Error de red.'));
}
</script>

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

