<?php
if (isset($_POST['guardar'])) {
  $id = $_POST['id'];
  $nombre = $conn->real_escape_string($_POST['nombre']);
  $cuit = $conn->real_escape_string($_POST['cuit']);
  $contacto = $conn->real_escape_string($_POST['contacto']);
  $telefono = $conn->real_escape_string($_POST['telefono']);
  $email = $conn->real_escape_string($_POST['email']);

  if ($id) {
    $stmt = $conn->prepare("UPDATE suppliers SET sup_name=?, sup_cuit=?, sup_address=?, sup_mobile=?, sup_email=? WHERE sup_id=?");
    $stmt->bind_param("sssssi", $nombre, $cuit, $contacto, $telefono, $email, $id);
    $stmt->execute();
  } else {
    $stmt = $conn->prepare("INSERT INTO suppliers (sup_name, sup_cuit, sup_address, sup_mobile, sup_email) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("sssss", $nombre, $cuit, $contacto, $telefono, $email);
    $stmt->execute();
  }
  echo "<script>location.href='prove.php';</script>";
}

$resultado = $conn->query("SELECT * FROM suppliers ORDER BY sup_name");
?>

<!-- Tabla -->
<div class="table-responsive">
  <table class="table table-bordered table-hover">
    <thead class="table-light">
      <tr>
        <th>Nombre</th>
        <th>CUIT</th>
        <th>Contacto</th>
        <th>Telefono</th>
        <th>Email</th>
        <th><strong>Saldo Total</strong></th>
        <th>Acciones</th>
		<th>Pagar</th>
      </tr>
    </thead>
    <tbody>
      <?php while ($p = $resultado->fetch_assoc()) : ?>
        <?php
          // Calcular saldo total de facturas no pagadas
          $saldo_total = 0;
          $saldo_result = $conn->query("
            SELECT SUM(monto - pagado) AS saldo
            FROM facturas
            WHERE proveedor_id = {$p['sup_id']}
          ");
          if ($saldo_result && $saldo_result->num_rows > 0) {
            $row = $saldo_result->fetch_assoc();
            $saldo_total = $row['saldo'] ?? 0;
          }
        ?>
        <tr>
          <td><?php echo $p['sup_name']; ?></td>
          <td><?php echo $p['sup_cuit']; ?></td>
          <td><?php echo $p['sup_address']; ?></td>
          <td><?php echo $p['sup_mobile']; ?></td>
          <td><?php echo $p['sup_email']; ?></td>
          <td>$<?php echo number_format($saldo_total, 2); ?></td>
          <td class="d-flex gap-1">
            <button class='btn btn-sm btn-warning' onclick='editar(<?php echo json_encode($p); ?>)'>Editar</button>
            <a href="cuenta_proveedor.php?proveedor_id=<?php echo $p['sup_id']; ?>" class="btn btn-sm btn-info">Estado</a>
          </td>
		  <td class="d-flex gap-1">
            
            >
  <button
    type="button"
    class="btn btn-sm btn-success btnAbrirPago"
    data-url="pago_popup.php?sup_id=<?php echo $p['sup_id']; ?>"
  >
    Pagar
  </button>


          </td>
        </tr>
      <?php endwhile; ?>
    </tbody>
  </table>
</div>

<!-- Scripts -->
<!-- Modal contenedor (vac�o, se rellena con AJAX) -->
<div class="modal fade" id="modalPago" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content" id="modalPagoBody">
      <!-- ac� se inyecta el contenido de pago_popup.php -->
    </div>
  </div>
</div>

<script src="assets/bootstrap/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script>
  // Abrir modal y cargar el formulario del pago
  $(document).on('click', '.btnAbrirPago', function (e) {
    e.preventDefault();
    var url = $(this).data('url');
    if (!url) return;

    $('#modalPago').modal('show');
    $('#modalPagoBody').html('<div class="p-3 text-center">Cargando�</div>');

    // Carga remota del formulario del modal
    $('#modalPagoBody').load(url, function (response, status, xhr) {
      if (status === 'error') {
        $('#modalPagoBody').html(
          '<div class="alert alert-danger m-3">No se pudo cargar el formulario (' +
          xhr.status + ' ' + xhr.statusText + ').</div>'
        );
      }
    });
  });
</script>


<script>
function editar(p) {
  document.getElementById('id').value = p.sup_id;
  document.getElementById('nombre').value = p.sup_name;
  document.getElementById('cuit').value = p.sup_cuit;
  document.getElementById('contacto').value = p.sup_address;
  document.getElementById('telefono').value = p.sup_mobile;
  document.getElementById('email').value = p.sup_email;
  document.getElementById('btn-guardar').textContent = 'Actualizar Proveedor';
  document.getElementById('btn-cancelar').classList.remove('d-none');
}

function cancelarEdicion() {
  document.getElementById('form-proveedor').reset();
  document.getElementById('id').value = '';
  document.getElementById('btn-guardar').textContent = 'Guardar Proveedor';
  document.getElementById('btn-cancelar').classList.add('d-none');
}
</script>
