<?php require_once 'conexion2.php'; ?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Comprobantes Faltantes en selling_info</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
  <div class="card shadow">
    <div class="card-header bg-danger text-white">
      <h4 class="mb-0">Comprobantes en sell_logs no presentes en selling_info</h4>
    </div>
    <div class="card-body">
<?php
try {
  // Consulta de los logs que no están en selling_info
$stmt = $pdo->query("
  SELECT 
    sl.id, 
    sl.ref_invoice_id, 
    sl.type, 
    sl.amount, 
    sl.created_at, 
    sl.description,
    c.customer_name
  FROM sell_logs sl
  LEFT JOIN selling_info si 
    ON sl.ref_invoice_id = si.invoice_id 
    AND si.inv_type = 'sell'
  LEFT JOIN customers c 
    ON sl.customer_id = c.customer_id
  WHERE sl.type = 'sell'
    AND si.invoice_id IS NULL
  ORDER BY c.customer_name ASC
");




  $resultados = $stmt->fetchAll(PDO::FETCH_ASSOC);

  if (count($resultados) > 0) {
    echo '<table class="table table-bordered table-striped table-hover table-sm">';
    echo '<thead class="table-light"><tr>
        <th>ID Log</th>
        <th>Cliente</th> <!-- aquí se mostrará el nombre -->
        <th>Factura</th>
        <th>Tipo</th>
        <th>Monto</th>
        <th>Fecha</th>
        <th>Descripción</th>
      </tr></thead><tbody>';


    foreach ($resultados as $row) {
      echo "<tr>
              <td>{$row['id']}</td>
              <td>{$row['customer_name']}</td>
              <td>{$row['ref_invoice_id']}</td>
              <td>{$row['type']}</td>
              <td>{$row['amount']}</td>
              <td>{$row['created_at']}</td>
              <td>{$row['description']}</td>
            </tr>";
    }

    echo '</tbody></table>';
    echo '<p class="mt-3 text-danger fw-bold">Total de comprobantes faltantes: ' . count($resultados) . '</p>';
  } else {
    echo '<div class="alert alert-success">Todos los comprobantes están correctamente registrados en <strong>selling_info</strong>.</div>';
  }
} catch (PDOException $e) {
  echo '<div class="alert alert-danger">Error en la consulta: ' . $e->getMessage() . '</div>';
}
?>
    </div>
  </div>
</div>
</body>
</html>
