<?php
require_once 'conexion2.php';
$sup_id = isset($_GET['sup_id']) ? (int)$_GET['sup_id'] : 0;
if ($sup_id <= 0) die("Proveedor no válido");

$pdo = db();
$stmt = $pdo->prepare("SELECT pglobal_pesos FROM supplier_to_store WHERE sup_id = ?");
$stmt->execute([$sup_id]);
$pglobal = (float) $stmt->fetchColumn();

$stmt = $pdo->prepare("
    SELECT pi.invoice_id, pi.purchase_date, pp.payable_amount, pp.paid_amount, pp.due
    FROM purchase_info pi
    JOIN purchase_price pp ON pi.invoice_id = pp.invoice_id
    WHERE pi.sup_id = ? AND pp.due > 0
    ORDER BY pi.purchase_date ASC
");
$stmt->execute([$sup_id]);
$facturas = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Imputación de Pagos</title>
  <style>
    body { font-family: Arial; margin: 20px; }
    table { width: 100%; border-collapse: collapse; margin-top: 10px; }
    th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
    th { background-color: #f0f0f0; }
    #btnImputar { margin-top: 20px; padding: 10px 20px; font-weight: bold; }
  </style>
</head>
<body>

<h2>Pagos pendientes del proveedor #<?= $sup_id ?></h2>
<p><strong>Saldo imputable disponible:</strong> $<span id="saldoDisponible"><?= number_format($pglobal, 2) ?></span></p>

<table>
  <thead>
    <tr>
      <th>Factura</th>
      <th>Fecha</th>
      <th>Total</th>
      <th>Pagado</th>
      <th>Pendiente</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($facturas as $fact): ?>
      <tr>
        <td><?= $fact['invoice_id'] ?></td>
        <td><?= date('d/m/Y', strtotime($fact['purchase_date'])) ?></td>
        <td>$<?= number_format($fact['payable_amount'], 2) ?></td>
        <td>$<?= number_format($fact['paid_amount'], 2) ?></td>
        <td>$<?= number_format($fact['due'], 2) ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<button id="btnImputar">💰 Imputar saldo automáticamente</button>

<script>
document.getElementById('btnImputar').addEventListener('click', function() {
  if (!confirm("¿Estás seguro de imputar el saldo a las facturas pendientes?")) return;

  const formData = new URLSearchParams();
  formData.append('sup_id', '<?= $sup_id ?>');

  fetch('imputar_saldo.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: formData.toString()
  })
  .then(response => response.json())
  .then(data => {
    alert(data.message);
    if (data.status === 'success') location.reload();
  })
  .catch(err => alert("Error al imputar: " + err));
});
</script>

</body>
</html>
