<?php
// admin/pago_popup.php
include __DIR__ . '/conexion3.php';

if (!isset($_GET['sup_id'])) {
  die('<div class="alert alert-danger m-3">Proveedor no especificado.</div>');
}
$sup_id = (int)$_GET['sup_id'];

// Cajas disponibles (con saldo) – si no querés filtrar por saldo, quitá el HAVING
$sql = "
  SELECT ba.id, ba.account_name,
         (ba.initial_balance + bast.deposit + bast.transfer_from_other - bast.withdraw - bast.transfer_to_other) AS balance
  FROM bank_accounts ba
  JOIN bank_account_to_store bast ON bast.account_id = ba.id
  WHERE bast.store_id = 1 AND bast.status = 1
  ORDER BY ba.account_name
";
$acc_rs = $conn->query($sql);

// Facturas con saldo
// Facturas con saldo + moneda (ARS/USD) desde factura_price
$fact_rs = $conn->query("
  SELECT f.id,
         f.numero_factura,
         f.tipo_doc,
         (f.monto - f.pagado) AS saldo,
         COALESCE(fp.moneda,'ARS') AS moneda
  FROM facturas f
  LEFT JOIN factura_price fp ON fp.factura_id = f.id
  WHERE f.proveedor_id = $sup_id
    AND (f.monto - f.pagado) > 0
  ORDER BY f.id DESC
");

?>
<div class="modal-header">
  <h4 class="modal-title">Pago a Proveedor #<?php echo $sup_id; ?></h4>
  <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
    <span aria-hidden="true">&times;</span>
  </button>
</div>

<form method="POST" action="procesar_pago_proveedor.php" id="formPagoProveedor">
  <div class="modal-body">
    <input type="hidden" name="sup_id" value="<?php echo $sup_id; ?>">

    <div class="form-group">
      <label>Fecha</label>
      <input type="date" name="fecha" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
    </div>

    <div class="form-group">
      <label>Forma de pago</label>
      <select name="forma_pago" id="forma_pago" class="form-control" required>
        <option value="efectivo">Efectivo</option>
        <option value="transferencia">Transferencia</option>
        <option value="cheque">Cheque</option>
      </select>
      <small id="ayudaImporte" class="form-text text-muted"></small>
    </div>

    <div class="form-group">
      <label>Caja / Cuenta</label>
      <select name="account_id" id="account_id" class="form-control" required>
        <option value="">-- Seleccionar --</option>
        <?php if ($acc_rs && $acc_rs->num_rows): ?>
          <?php while ($a = $acc_rs->fetch_assoc()):
            $bid = (int)$a['id'];
            $bname = $a['account_name'];
            $bal = (float)$a['balance'];
          ?>
            <option value="<?php echo $bid; ?>">
              <?php echo htmlspecialchars($bname).' (Saldo: $'.number_format($bal,2).')'; ?>
            </option>
          <?php endwhile; ?>
        <?php endif; ?>
      </select>
      <small id="ayudaCaja" class="form-text text-muted"></small>
    </div>

    <div class="form-group">
      <label>Factura (opcional)</label>
      <select name="factura_id" class="form-control">
        <option value="">-- Sin imputar --</option>
        <?php if ($fact_rs && $fact_rs->num_rows): ?>
  <?php while ($f = $fact_rs->fetch_assoc()):
    $moneda = $f['moneda'];                 // 'ARS' o 'USD'
    $simbolo = ($moneda === 'USD') ? 'U$D ' : '$';
    $tipo_doc = htmlspecialchars($f['tipo_doc']);
    $nro      = htmlspecialchars($f['numero_factura']);
    $saldo    = (float)$f['saldo'];
    $label    = "{$tipo_doc} {$nro} ({$moneda}) - Saldo: {$simbolo}" . number_format($saldo, 2);
  ?>
    <option value="<?php echo (int)$f['id']; ?>" data-moneda="<?php echo $moneda; ?>">
      <?php echo $label; ?>
    </option>
  <?php endwhile; ?>
<?php endif; ?>

      </select>
    </div>

    <div class="form-group">
      <label>Cotización dólar (ARS → USD)</label>
      <input type="number" step="0.0001" min="0" name="cotizacion" id="cotizacion" class="form-control" placeholder="Ej. 1000.00" required>
      <small class="form-text text-muted">Se usa para registrar el asiento en USD.</small>
    </div>

    <div id="wrapImporteARS" class="form-group">
      <label>Importe (ARS)</label>
      <input type="number" step="0.01" min="0.01" name="importe_ars" id="importe_ars" class="form-control" placeholder="0.00">
    </div>

    <!-- ===== Sección Cheques (se muestra solo si forma_pago = cheque) ===== -->
    <div id="seccion_cheques" style="display:none;">
      <hr>
      <div class="form-group">
        <label>Cheques disponibles en la caja (status = 'in')</label>
        <div class="table-responsive">
          <table class="table table-bordered table-striped" id="tblChequesDisponibles">
            <thead class="thead-light">
              <tr>
                <th>Sel</th>
                <th>N° Cheque</th>
                <th>Emisión</th>
                <th>Cobro</th>
                <th>Importe</th>
                <th>CUIT</th>
              </tr>
            </thead>
            <tbody>
              <!-- filas por AJAX -->
            </tbody>
          </table>
        </div>
        <div id="msgCheques" class="text-muted small"></div>
      </div>

      <input type="hidden" name="selected_cheques[]" value="" id="dummy_selected_cheques" />
      <div id="cheques_hidden_container"></div>
    </div>
    <!-- ===== Fin Sección Cheques ===== -->

    <div class="form-group">
      <label>Nota (opcional)</label>
      <input type="text" name="nota" class="form-control" placeholder="Comentario interno">
    </div>
  </div>

  <div class="modal-footer">
    <button type="submit" class="btn btn-primary">Registrar Pago</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
  </div>
</form>

<script>
(function(){
  var formaPago   = document.getElementById('forma_pago');
  var seccionCh   = document.getElementById('seccion_cheques');
  var importeARS  = document.getElementById('importe_ars');
  var ayudaImp    = document.getElementById('ayudaImporte');
  var ayudaCaja   = document.getElementById('ayudaCaja');
  var accountSel  = document.getElementById('account_id');

  var tblBody     = document.querySelector('#tblChequesDisponibles tbody');
  var msgCheques  = document.getElementById('msgCheques');
  var hiddenWrap  = document.getElementById('cheques_hidden_container');

  function toggleChequeSection() {
    var esCheque = (formaPago.value === 'cheque');
    seccionCh.style.display = esCheque ? 'block' : 'none';
    if (esCheque) {
      if (ayudaImp) ayudaImp.textContent = 'El importe se calcula automáticamente según los cheques seleccionados.';
      if (importeARS) { importeARS.value = ''; importeARS.readOnly = true; }
      cargarCheques();
    } else {
      if (ayudaImp) ayudaImp.textContent = '';
      if (importeARS) { importeARS.readOnly = false; }
      if (tblBody) tblBody.innerHTML = '';
      if (hiddenWrap) hiddenWrap.innerHTML = '';
      if (msgCheques) msgCheques.textContent = '';
    }
  }

  function cargarCheques() {
    if (formaPago.value !== 'cheque') return;
    var acc = accountSel ? accountSel.value : '';
    if (!acc) {
      if (tblBody) tblBody.innerHTML = '';
      if (msgCheques) msgCheques.textContent = 'Seleccioná primero una caja.';
      return;
    }

    // Pedimos cheques status=in de la caja
    $.getJSON('get_cheques.php', { account_id: acc, status: 'in' }, function(resp) {
      if (!resp || !resp.ok) {
        tblBody.innerHTML = '';
        msgCheques.textContent = resp && resp.msg ? resp.msg : 'No se pudieron cargar cheques.';
        return;
      }
      var list = resp.data || [];
      if (!list.length) {
        tblBody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">Sin cheques disponibles en esta caja.</td></tr>';
        msgCheques.textContent = '';
        return;
      }
      msgCheques.textContent = '';
      renderCheques(list);
    }).fail(function(xhr){
      tblBody.innerHTML = '';
      msgCheques.textContent = 'Error (' + xhr.status + ' ' + xhr.statusText + ')';
    });
  }

  function renderCheques(list) {
    tblBody.innerHTML = '';
    hiddenWrap.innerHTML = '';
    var suma = 0;
    list.forEach(function(ch) {
      var tr = document.createElement('tr');
      tr.innerHTML =
        '<td class="text-center"><input type="checkbox" class="chkCheque" value="'+ch.cheque_id+'"></td>' +
        '<td>'+(ch.numero || '')+'</td>' +
        '<td>'+(ch.fecha || '')+'</td>' +
        '<td>'+(ch.fecha_pago || '')+'</td>' +
        '<td>'+parseFloat(ch.importe || 0).toFixed(2)+'</td>' +
        '<td>'+(ch.cuit || '')+'</td>';
      tr.querySelector('.chkCheque').addEventListener('change', function() {
        if (this.checked) {
          var hid = document.createElement('input');
          hid.type = 'hidden';
          hid.name = 'selected_cheques[]';
          hid.value = this.value;
          hid.dataset.linked = 'cheq_'+this.value;
          hiddenWrap.appendChild(hid);
        } else {
          var h = hiddenWrap.querySelector('input[name="selected_cheques[]"][value="'+this.value+'"]');
          if (h) h.remove();
        }
        recalcImporte();
      });
      tblBody.appendChild(tr);
    });
  }

  function recalcImporte() {
    if (formaPago.value !== 'cheque') return;
    var total = 0;
    $('#tblChequesDisponibles .chkCheque:checked').each(function(){
      var row = $(this).closest('tr');
      var imp = parseFloat(row.find('td:nth-child(5)').text());
      if (!isNaN(imp)) total += imp;
    });
    if (importeARS) importeARS.value = total ? total.toFixed(2) : '';
  }

  if (formaPago) {
    formaPago.addEventListener('change', toggleChequeSection);
  }
  if (accountSel) {
    accountSel.addEventListener('change', function(){
      if (formaPago.value === 'cheque') cargarCheques();
    });
  }

  // Estado inicial
  toggleChequeSection();
})();
</script>
