<?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 Manual</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>Imputación manual - proveedor #<?= $sup_id ?></h2>
<p><strong>Saldo imputable disponible:</strong> $<span id="saldoDisponible"><?= number_format($pglobal, 2) ?></span></p>

<form id="formManualImputar">
  <table>
    <thead>
      <tr>
        <th></th>
        <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><input type="checkbox" name="facturas[]" value="<?= $fact['invoice_id'] ?>"></td>
        <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>

  <label for="montoManual"><strong>Monto a imputar manualmente:</strong></label>
  <input type="number" id="montoManual" name="monto_manual" min="0" max="<?= $pglobal ?>" step="0.01" required>
  <br><br>
  <button type="submit">✅ Imputar manual</button>
</form>

<script>
document.getElementById('formManualImputar').addEventListener('submit', function(e) {
  e.preventDefault();

  const form = e.target;
  const facturas = [...form.querySelectorAll('input[name="facturas[]"]:checked')].map(cb => cb.value);
  const monto = parseFloat(document.getElementById('montoManual').value);

  if (facturas.length === 0) {
    alert("Debes seleccionar al menos una factura.");
    return;
  }

  if (isNaN(monto) || monto <= 0) {
    alert("Debes ingresar un monto válido a imputar.");
    return;
  }

  const formData = new URLSearchParams();
  formData.append('sup_id', '<?= $sup_id ?>');
  formData.append('monto_manual', monto);
  facturas.forEach(id => formData.append('facturas[]', id));

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

</body>
</html>
