<?php
function capital_detail_state(int $id): array{
 $r=rows("SELECT d.*,c.cliente_id,c.monto monto_documento,c.id capital_id,c.fecha,c.tasa,c.periodicidad,m.codigo,m.nombre moneda,m.simbolo,m.decimales FROM capital_detalles d JOIN capitales c ON c.id=d.capital_id JOIN monedas m ON m.id=c.moneda_id WHERE d.id=$id")[0]??[];
 if(!$r)return [];$r['interes_pendiente']=max(0,(float)$r['interes']-(float)$r['cobrado_interes']);$r['capital_pendiente']=max(0,(float)$r['capital']-(float)$r['cobrado_capital']);$r['saldo']=$r['interes_pendiente']+$r['capital_pendiente'];return $r;
}
function capital_balance(string $where='1=1'): float{
 $total=0;foreach(rows("SELECT d.id FROM capital_detalles d JOIN capitales c ON c.id=d.capital_id WHERE c.estado<>'Anulado' AND $where") as $r)$total+=(float)capital_detail_state((int)$r['id'])['saldo'];return $total;
}
function capital_due_date(string $first,int $months,int $index): string{
 $base=new DateTime($first);if($index===0)return $base->format('Y-m-d');$day=(int)$base->format('d');$target=new DateTime($base->format('Y-m-01'));$target->modify('+'.($months*$index).' months');$last=(int)$target->format('t');$target->setDate((int)$target->format('Y'),(int)$target->format('m'),min($day,$last));return $target->format('Y-m-d');
}

if($p==='carga_capital'){
 require_permission('carga_capital');
 if($_SERVER['REQUEST_METHOD']==='POST'){check_csrf();$fecha=poststr('fecha');$cliente=(int)($_POST['cliente_id']??0);$origen=(int)($_POST['origen_capital_id']??0);$moneda=(int)($_POST['moneda_id']??1);$monto=postfloat('monto');$tasa=postfloat('tasa');$cantidad=max(1,(int)($_POST['cantidad_cuotas']??1));$periodicidad=poststr('periodicidad');$primero=poststr('primer_vencimiento');$obs=poststr('observaciones');if(!$fecha||!$cliente||!$origen||!$moneda||$monto<=0||$tasa<0||!$primero)throw new RuntimeException('Complete todos los datos obligatorios.');$months=['Mensual'=>1,'Bimestral'=>2,'Semestral'=>6,'Anual'=>12,'Al vencimiento'=>0];if(!isset($months[$periodicidad]))throw new RuntimeException('Periodicidad inválida.');if($periodicidad==='Al vencimiento')$cantidad=1;$schedule=[];$previous=$fecha;$totalInterest=0;for($i=0;$i<$cantidad;$i++){$due=capital_due_date($primero,$months[$periodicidad],$i);$days=max(0,(int)(new DateTime($previous))->diff(new DateTime($due))->format('%r%a'));$interest=round($monto*$days*$tasa/loan_divisor(),2);$capital=$i===$cantidad-1?$monto:0;$schedule[]=[$i+1,$due,$days,$interest,$capital];$totalInterest+=$interest;$previous=$due;}$cn=db();$cn->begin_transaction();try{$st=$cn->prepare("INSERT INTO capitales(fecha,cliente_id,origen_capital_id,moneda_id,monto,tasa,cantidad_cuotas,periodicidad,primer_vencimiento,total_interes,total_capital,observaciones,creado_por) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");$uid=(int)user()['id'];$st->bind_param('siiiddissddsi',$fecha,$cliente,$origen,$moneda,$monto,$tasa,$cantidad,$periodicidad,$primero,$totalInterest,$monto,$obs,$uid);$st->execute();$capitalId=$st->insert_id;$dt=$cn->prepare("INSERT INTO capital_detalles(capital_id,numero_cuota,vencimiento,plazo_dias,interes,capital) VALUES(?,?,?,?,?,?)");foreach($schedule as [$number,$due,$days,$interest,$capital]){$dt->bind_param('iisidd',$capitalId,$number,$due,$days,$interest,$capital);$dt->execute();}$cn->commit();audit('CREAR','capitales',$capitalId);flash('success','Capital y calendario guardados correctamente.');redirect("app.php?p=carga_capital&view=$capitalId");}catch(Throwable $e){$cn->rollback();throw $e;}}
 $view=(int)($_GET['view']??0);page_start('Carga Capital');if($view):$cap=rows("SELECT c.*,CONCAT(cl.nombres,' ',cl.apellidos) cliente,o.nombre origen,m.codigo,m.nombre moneda,m.simbolo,m.decimales FROM capitales c JOIN clientes cl ON cl.id=c.cliente_id JOIN origenes_capital o ON o.id=c.origen_capital_id JOIN monedas m ON m.id=c.moneda_id WHERE c.id=$view")[0]??null;if($cap):?>
 <div class="d-flex justify-content-between mb-3"><h2>Capital #<?=$view?></h2><a class="btn btn-primary no-print" href="?p=carga_capital">Nueva carga</a></div><div class="card mb-4"><div class="card-body row g-3"><div class="col-md-4"><b>Cliente</b><br><?=e($cap['cliente'])?></div><div class="col-md-2"><b>Moneda</b><br><?=e($cap['moneda'])?></div><div class="col-md-2"><b>Origen</b><br><?=e($cap['origen'])?></div><div class="col-md-2"><b>Monto</b><br><?=money_currency((float)$cap['monto'],$cap)?></div><div class="col-md-2"><b>Tasa</b><br><?=e($cap['tasa'])?>%</div></div></div><div class="card"><table class="table mb-0"><thead><tr><th>Cuota</th><th>Vencimiento</th><th>Días</th><th>Interés</th><th>Capital</th><th>Total</th></tr></thead><tbody><?php foreach(rows("SELECT * FROM capital_detalles WHERE capital_id=$view ORDER BY numero_cuota") as $d):?><tr><td><?=$d['numero_cuota']?></td><td><?=e($d['vencimiento'])?></td><td><?=$d['plazo_dias']?></td><td><?=money_currency((float)$d['interes'],$cap)?></td><td><?=money_currency((float)$d['capital'],$cap)?></td><td class="fw-bold"><?=money_currency((float)$d['interes']+(float)$d['capital'],$cap)?></td></tr><?php endforeach;?></tbody></table></div><?php endif;else:?>
 <h2>Carga Capital</h2><form method="post" id="capitalForm"><input type="hidden" name="csrf" value="<?=csrf()?>"><div class="card"><div class="card-body"><div class="row g-3"><div class="col-md-3"><label class="form-label required">Fecha</label><input type="date" class="form-control" name="fecha" value="<?=date('Y-m-d')?>" required></div><div class="col-md-5 autocomplete"><label class="form-label required">Cliente</label><input class="form-control lookup" placeholder="Buscar cliente"><input type="hidden" name="cliente_id"><div class="autocomplete-results"></div></div><div class="col-md-4"><label class="form-label required">Origen del Capital</label><select class="form-select" name="origen_capital_id" required><?php select_opts('origenes_capital');?></select></div><div class="col-md-3"><label class="form-label required">Moneda</label><select class="form-select" name="moneda_id" id="capitalMoneda" required><?php foreach(rows("SELECT * FROM monedas WHERE activo=1 ORDER BY orden") as $m):?><option value="<?=$m['id']?>" data-codigo="<?=e($m['codigo'])?>"><?=e($m['nombre'])?></option><?php endforeach;?></select></div><div class="col-md-3"><label class="form-label required">Monto</label><input type="text" inputmode="decimal" maxlength="16" id="capitalMontoVisible" class="form-control" required><input type="hidden" name="monto" id="capitalMonto"></div><div class="col-md-2"><label class="form-label required">Tasa a pagar %</label><input type="number" step="0.0001" min="0" class="form-control" name="tasa" value="24" required></div><div class="col-md-2"><label class="form-label required">Cantidad de cuotas</label><input type="number" min="1" max="600" class="form-control" name="cantidad_cuotas" value="1" required></div><div class="col-md-3"><label class="form-label required">Periodicidad de intereses</label><select class="form-select" name="periodicidad" required><?php foreach(['Mensual','Bimestral','Semestral','Anual','Al vencimiento'] as $x):?><option><?=e($x)?></option><?php endforeach;?></select></div><div class="col-md-3"><label class="form-label required">Primer vencimiento</label><input type="date" class="form-control" name="primer_vencimiento" required></div><div class="col-12"><label class="form-label">Observaciones</label><textarea class="form-control" name="observaciones"></textarea></div></div><div id="capitalPreview" class="card mt-4 d-none"><div class="card-header">Calendario calculado</div><div class="table-responsive"><table class="table table-sm mb-0"><thead><tr><th>Cuota</th><th>Vencimiento</th><th>Días</th><th>Interés</th><th>Capital</th><th>Total</th></tr></thead><tbody id="capitalPreviewBody"></tbody><tfoot><tr class="table-primary fw-bold"><td colspan="3">Totales</td><td id="capitalTotalInteres"></td><td id="capitalTotalMonto"></td><td id="capitalTotalGeneral"></td></tr></tfoot></table></div></div><div class="d-flex gap-2 mt-3"><button type="button" class="btn btn-outline-primary" id="calcularCapital"><i class="fa fa-calculator me-1"></i>Calcular</button><button type="submit" class="btn btn-primary" id="guardarCapital" disabled><i class="fa fa-floppy-disk me-1"></i>Guardar</button></div></div></div></form><script>window.BASE_URL='<?=BASE_URL?>';let lx=document.querySelector('.lookup');autocomplete(lx,lx.nextElementSibling,'clientes');let mv=document.querySelector('#capitalMontoVisible'),mr=document.querySelector('#capitalMonto'),mc=document.querySelector('#capitalMoneda');function maskCapital(){let digits=mv.value.replace(/\D/g,'').slice(0,12),usd=mc.selectedOptions[0]?.dataset.codigo==='USD',value=usd?Number(digits)/100:Number(digits);mr.value=value.toFixed(usd?2:0);mv.value=digits?new Intl.NumberFormat('es-PY',{minimumFractionDigits:usd?2:0,maximumFractionDigits:usd?2:0}).format(value):''}function capitalFmt(n){let usd=mc.selectedOptions[0]?.dataset.codigo==='USD';return new Intl.NumberFormat('es-PY',{minimumFractionDigits:usd?2:0,maximumFractionDigits:usd?2:0}).format(n)}
function fechaCapital(base,months,index){let b=new Date(base+'T00:00:00'),day=b.getDate();if(index===0)return b;let target=new Date(b.getFullYear(),b.getMonth()+months*index,1),last=new Date(target.getFullYear(),target.getMonth()+1,0).getDate();target.setDate(Math.min(day,last));return target}
function isoCapital(d){return d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0')}
function invalidarCapital(){document.querySelector('#guardarCapital').disabled=true;document.querySelector('#capitalPreview').classList.add('d-none')}
function calcularCapital(){let f=document.querySelector('#capitalForm');if(!f.reportValidity())return;let monto=Number(mr.value),tasa=Number(f.tasa.value),cantidad=Math.max(1,Number(f.cantidad_cuotas.value)),periodo=f.periodicidad.value,meses={Mensual:1,Bimestral:2,Semestral:6,Anual:12,'Al vencimiento':0}[periodo];if(periodo==='Al vencimiento'){cantidad=1;f.cantidad_cuotas.value=1}let first=f.primer_vencimiento.value,prev=new Date(f.fecha.value+'T00:00:00'),body='',totalI=0;for(let i=0;i<cantidad;i++){let due=fechaCapital(first,meses,i),dias=Math.max(0,Math.round((due-prev)/86400000)),interes=monto*dias*tasa/<?=json_encode(loan_divisor())?>,capital=i===cantidad-1?monto:0;totalI+=interes;body+=`<tr><td>${i+1}</td><td>${isoCapital(due)}</td><td>${dias}</td><td>${capitalFmt(interes)}</td><td>${capitalFmt(capital)}</td><td class="fw-bold">${capitalFmt(interes+capital)}</td></tr>`;prev=due}document.querySelector('#capitalPreviewBody').innerHTML=body;document.querySelector('#capitalTotalInteres').textContent=capitalFmt(totalI);document.querySelector('#capitalTotalMonto').textContent=capitalFmt(monto);document.querySelector('#capitalTotalGeneral').textContent=capitalFmt(totalI+monto);document.querySelector('#capitalPreview').classList.remove('d-none');document.querySelector('#guardarCapital').disabled=false;document.querySelector('#capitalPreview').scrollIntoView({behavior:'smooth',block:'center'})}
mv.addEventListener('input',()=>{maskCapital();invalidarCapital()});mc.addEventListener('change',()=>{mv.value='';mr.value='';invalidarCapital()});document.querySelector('#capitalForm').addEventListener('input',e=>{if(e.target!==mv)invalidarCapital()});document.querySelector('#calcularCapital').addEventListener('click',calcularCapital)</script><?php endif;page_end();exit;
}

if($p==='reporte_capitales'){
 require_permission('reporte_capitales');$cid=(int)($_GET['cliente_id']??0);$capitalId=(int)($_GET['capital_id']??0);page_start('Reporte Capitales');?>
 <h2>Reporte Capitales</h2><?php if($capitalId):$cap=rows("SELECT c.*,CONCAT(cl.nombres,' ',cl.apellidos) cliente,m.codigo,m.nombre moneda,m.simbolo,m.decimales FROM capitales c JOIN clientes cl ON cl.id=c.cliente_id JOIN monedas m ON m.id=c.moneda_id WHERE c.id=$capitalId AND c.cliente_id=$cid")[0]??null;if($cap):?><div class="card"><div class="card-header">Capital #<?=$capitalId?> · <?=e($cap['cliente'])?> · <?=e($cap['moneda'])?></div><table class="table mb-0"><thead><tr><th>Cuota</th><th>Vencimiento</th><th>Interés</th><th>Capital</th><th>Pagado</th><th>Saldo</th></tr></thead><tbody><?php $total=0;foreach(rows("SELECT id FROM capital_detalles WHERE capital_id=$capitalId ORDER BY numero_cuota") as $x):$d=capital_detail_state((int)$x['id']);$total+=$d['saldo'];?><tr><td><?=$d['numero_cuota']?></td><td><?=e($d['vencimiento'])?></td><td><?=money_currency((float)$d['interes'],$cap)?></td><td><?=money_currency((float)$d['capital'],$cap)?></td><td><?=money_currency((float)$d['cobrado_interes']+(float)$d['cobrado_capital'],$cap)?></td><td class="fw-bold"><?=money_currency((float)$d['saldo'],$cap)?></td></tr><?php endforeach;?><tr class="table-primary fw-bold"><td colspan="5">Saldo operación</td><td><?=money_currency($total,$cap)?></td></tr></tbody></table></div><?php endif;
 elseif($cid):?><div class="card"><table class="table mb-0"><thead><tr><th>Operación</th><th>Fecha</th><th>Moneda</th><th>Monto</th><th>Saldo</th><th></th></tr></thead><tbody><?php $last='';foreach(rows("SELECT c.*,m.codigo,m.nombre moneda,m.simbolo,m.decimales FROM capitales c JOIN monedas m ON m.id=c.moneda_id WHERE c.cliente_id=$cid AND c.estado<>'Anulado' ORDER BY m.orden,c.id") as $cap):if($last!==$cap['codigo']):$last=$cap['codigo'];?><tr class="table-primary"><th colspan="6"><?=e($cap['moneda'])?></th></tr><?php endif;$saldo=capital_balance('c.id='.(int)$cap['id']);?><tr><td>#<?=$cap['id']?></td><td><?=e($cap['fecha'])?></td><td><?=e($cap['moneda'])?></td><td><?=money_currency((float)$cap['monto'],$cap)?></td><td class="fw-bold"><?=money_currency($saldo,$cap)?></td><td><a class="btn btn-sm btn-outline-primary no-print" href="?p=reporte_capitales&cliente_id=<?=$cid?>&capital_id=<?=$cap['id']?>">Ver detalle</a></td></tr><?php endforeach;?></tbody></table></div>
 <?php elseif(isset($_GET['lista'])):?><div class="card"><table class="table mb-0"><thead><tr><th>Cliente</th><th>Moneda</th><th>Saldo</th><th></th></tr></thead><tbody><?php $last='';foreach(rows("SELECT DISTINCT cl.id,cl.nombres,cl.apellidos,cl.razon_social,m.id moneda_id,m.codigo,m.nombre moneda,m.simbolo,m.decimales,m.orden FROM clientes cl JOIN capitales c ON c.cliente_id=cl.id JOIN monedas m ON m.id=c.moneda_id WHERE c.estado<>'Anulado' ORDER BY m.orden,cl.nombres") as $cl):$saldo=capital_balance('c.cliente_id='.(int)$cl['id'].' AND c.moneda_id='.(int)$cl['moneda_id']);if($saldo<=.009)continue;if($last!==$cl['codigo']):$last=$cl['codigo'];?><tr class="table-primary"><th colspan="4"><?=e($cl['moneda'])?></th></tr><?php endif;?><tr><td><?=e($cl['razon_social']?:trim($cl['nombres'].' '.$cl['apellidos']))?></td><td><?=e($cl['moneda'])?></td><td class="fw-bold"><?=money_currency($saldo,$cl)?></td><td><a class="btn btn-sm btn-outline-primary no-print" href="?p=reporte_capitales&cliente_id=<?=$cl['id']?>">Ver operaciones</a></td></tr><?php endforeach;?></tbody></table></div>
 <?php else:?><div class="row g-3"><?php foreach(rows("SELECT * FROM monedas WHERE activo=1 ORDER BY orden") as $m):$saldo=capital_balance('c.moneda_id='.(int)$m['id']);?><div class="col-md-6"><a class="text-decoration-none" href="?p=reporte_capitales&lista=1"><div class="card"><div class="card-body"><h5><?=e($m['nombre'])?></h5><div class="display-6 fw-bold text-primary"><?=money_currency($saldo,$m)?></div><small>Ver por cliente</small></div></div></a></div><?php endforeach;?></div><?php endif;page_end();exit;
}

if($p==='detalle_capitales'){
 require_permission('detalle_capitales');$desde=$_GET['desde']??date('Y-m-01');$hasta=$_GET['hasta']??date('Y-m-t');page_start('Detalle Capitales');?>
 <h2>Detalle Capitales</h2><form class="card card-body mb-4 no-print"><input type="hidden" name="p" value="detalle_capitales"><div class="row g-3"><div class="col-md-4"><label class="form-label">Desde</label><input type="date" class="form-control" name="desde" value="<?=e($desde)?>"></div><div class="col-md-4"><label class="form-label">Hasta</label><input type="date" class="form-control" name="hasta" value="<?=e($hasta)?>"></div><div class="col-md-2 align-self-end"><button class="btn btn-primary">Consultar</button></div></div></form><div class="card"><table class="table mb-0"><thead><tr><th>Vencimiento</th><th>Cliente</th><th>Operación/Cuota</th><th>Interés</th><th>Capital</th><th>Pagado</th><th>Saldo</th></tr></thead><tbody><?php $st=db()->prepare("SELECT d.id,cl.nombres,cl.apellidos,cl.razon_social,m.codigo,m.nombre moneda,m.simbolo,m.decimales FROM capital_detalles d JOIN capitales c ON c.id=d.capital_id JOIN clientes cl ON cl.id=c.cliente_id JOIN monedas m ON m.id=c.moneda_id WHERE d.vencimiento BETWEEN ? AND ? AND c.estado<>'Anulado' ORDER BY m.orden,d.vencimiento,cl.nombres,c.id,d.numero_cuota");$st->bind_param('ss',$desde,$hasta);$st->execute();$items=$st->get_result()->fetch_all(MYSQLI_ASSOC);$last='';foreach($items as $item):$d=capital_detail_state((int)$item['id']);if($last!==$item['codigo']):$last=$item['codigo'];?><tr class="table-primary"><th colspan="7"><?=e($item['moneda'])?></th></tr><?php endif;?><tr><td><?=e($d['vencimiento'])?></td><td><?=e($item['razon_social']?:trim($item['nombres'].' '.$item['apellidos']))?></td><td>#<?=$d['capital_id']?> / <?=$d['numero_cuota']?></td><td><?=money_currency((float)$d['interes'],$item)?></td><td><?=money_currency((float)$d['capital'],$item)?></td><td><?=money_currency((float)$d['cobrado_interes']+(float)$d['cobrado_capital'],$item)?></td><td class="fw-bold"><?=money_currency((float)$d['saldo'],$item)?></td></tr><?php endforeach;?></tbody></table></div><?php page_end();exit;
}

if($p==='eliminar_capital'){
 require_permission('eliminar_capital');$cid=(int)($_GET['cliente_id']??$_POST['cliente_id']??0);$capitalId=(int)($_POST['capital_id']??0);
 if($_SERVER['REQUEST_METHOD']==='POST'&&isset($_POST['eliminar'])){check_csrf();$check=rows("SELECT id FROM capitales WHERE id=$capitalId AND cliente_id=$cid")[0]??null;if(!$check)throw new RuntimeException('El capital seleccionado no corresponde al cliente.');$cn=db();$cn->begin_transaction();try{$cn->query("DELETE FROM capitales WHERE id=$capitalId");$cn->commit();audit('ELIMINAR','capitales',$capitalId,'Capital, cuotas y pagos eliminados');flash('success','Capital, cuotas y pagos eliminados.');redirect('app.php?p=eliminar_capital');}catch(Throwable $e){$cn->rollback();throw $e;}}
 page_start('Eliminar Capital');?>
 <h2>Eliminar Capital</h2><div class="alert alert-warning"><strong>Atención:</strong> esta opción elimina definitivamente el capital, todas sus cuotas y sus pagos.</div><form method="get" class="card card-body mb-4"><input type="hidden" name="p" value="eliminar_capital"><div class="row g-3"><div class="col-md-8 autocomplete"><label class="form-label required">Cliente</label><input class="form-control lookup" placeholder="Buscar cliente"><input type="hidden" name="cliente_id" value="<?=$cid?>"><div class="autocomplete-results"></div></div><div class="col-md-2 align-self-end"><button class="btn btn-primary">Ver capitales</button></div></div></form><?php if($cid):?><div class="card"><table class="table mb-0"><thead><tr><th>Capital</th><th>Fecha</th><th>Moneda</th><th>Monto</th><th>Saldo</th><th></th></tr></thead><tbody><?php foreach(rows("SELECT c.*,m.codigo,m.nombre moneda,m.simbolo,m.decimales FROM capitales c JOIN monedas m ON m.id=c.moneda_id WHERE c.cliente_id=$cid ORDER BY m.orden,c.id DESC") as $cap):?><tr><td>#<?=$cap['id']?></td><td><?=e($cap['fecha'])?></td><td><?=e($cap['moneda'])?></td><td><?=money_currency((float)$cap['monto'],$cap)?></td><td><?=money_currency(capital_balance('c.id='.(int)$cap['id']),$cap)?></td><td><form method="post" onsubmit="return confirm('¿Eliminar definitivamente este capital, todas sus cuotas y pagos?')"><input type="hidden" name="csrf" value="<?=csrf()?>"><input type="hidden" name="cliente_id" value="<?=$cid?>"><input type="hidden" name="capital_id" value="<?=$cap['id']?>"><button class="btn btn-sm btn-danger" name="eliminar" value="1">Eliminar</button></form></td></tr><?php endforeach;?></tbody></table></div><?php endif;?><script>window.BASE_URL='<?=BASE_URL?>';let x=document.querySelector('.lookup');autocomplete(x,x.nextElementSibling,'clientes');</script><?php page_end();exit;
}

if($p==='pago_capitales'){
 require_permission('pago_capitales');$did=(int)($_GET['detalle_id']??$_POST['detalle_id']??0);$cid=(int)($_GET['cliente_id']??$_POST['cliente_id']??0);
 if($_SERVER['REQUEST_METHOD']==='POST'&&$did){check_csrf();$amount=postfloat('monto');$d=capital_detail_state($did);if(!$d)throw new RuntimeException('Cuota no encontrada.');if($amount<=0||$amount>$d['saldo']+.01)throw new RuntimeException('El monto no puede superar el saldo.');$interest=min($amount,$d['interes_pendiente']);$capital=min($amount-$interest,$d['capital_pendiente']);$cn=db();$cn->begin_transaction();try{$rec='CAP-'.date('YmdHis');$uid=(int)user()['id'];$st=$cn->prepare("INSERT INTO capital_pagos(cliente_id,capital_detalle_id,monto,interes_aplicado,capital_aplicado,recibo,usuario_id) VALUES(?,?,?,?,?,?,?)");$st->bind_param('iidddsi',$d['cliente_id'],$did,$amount,$interest,$capital,$rec,$uid);$st->execute();$cn->query("UPDATE capital_detalles SET cobrado_interes=cobrado_interes+$interest,cobrado_capital=cobrado_capital+$capital,ultima_fecha_pago=NOW() WHERE id=$did");$remaining=capital_balance('c.id='.(int)$d['capital_id']);if($remaining<=.009)$cn->query("UPDATE capitales SET estado='Cancelado' WHERE id=".(int)$d['capital_id']);$cn->commit();audit('PAGO','capitales',(int)$d['capital_id'],"Recibo $rec");flash('success',"Pago registrado. Recibo $rec");redirect("app.php?p=pago_capitales&cliente_id={$d['cliente_id']}");}catch(Throwable $e){$cn->rollback();throw $e;}}
 if($did&&!$cid){$d=capital_detail_state($did);$cid=(int)($d['cliente_id']??0);}page_start('Pago Capitales');?>
 <h2>Pago Capitales</h2><?php if(!$did):?><form class="card card-body mb-4"><input type="hidden" name="p" value="pago_capitales"><div class="row"><div class="col-md-8 autocomplete"><label class="form-label">Cliente</label><input class="form-control lookup" placeholder="Buscar cliente"><input type="hidden" name="cliente_id" value="<?=$cid?>"><div class="autocomplete-results"></div></div><div class="col-md-2 align-self-end"><button class="btn btn-primary">Buscar</button></div></div></form><?php if($cid):?><div class="card"><table class="table mb-0"><thead><tr><th>Operación/Cuota</th><th>Vencimiento</th><th>Moneda</th><th>Monto documento</th><th>Interés</th><th>Capital</th><th>Saldo</th><th></th></tr></thead><tbody><?php foreach(rows("SELECT d.id FROM capital_detalles d JOIN capitales c ON c.id=d.capital_id JOIN monedas m ON m.id=c.moneda_id WHERE c.cliente_id=$cid AND c.estado<>'Anulado' ORDER BY m.orden,d.vencimiento,d.id") as $x):$d=capital_detail_state((int)$x['id']);if($d['saldo']<=.009)continue;?><tr><td>#<?=$d['capital_id']?> / <?=$d['numero_cuota']?></td><td><?=e($d['vencimiento'])?></td><td><?=e($d['moneda'])?></td><td><?=money_currency((float)$d['monto_documento'],$d)?></td><td><?=money_currency((float)$d['interes_pendiente'],$d)?></td><td><?=money_currency((float)$d['capital_pendiente'],$d)?></td><td class="fw-bold"><?=money_currency((float)$d['saldo'],$d)?></td><td><a class="btn btn-sm btn-outline-primary" href="?p=pago_capitales&cliente_id=<?=$cid?>&detalle_id=<?=$d['id']?>">Seleccionar</a></td></tr><?php endforeach;?></tbody></table></div><?php endif;?><?php else:$d=capital_detail_state($did);if($d):?><div class="card"><div class="card-header">Registrar pago de capital</div><div class="card-body"><h5>Operación #<?=$d['capital_id']?> / Cuota <?=$d['numero_cuota']?></h5><div class="row g-3 mb-3"><div class="col"><small>Monto documento</small><div class="fw-bold"><?=money_currency((float)$d['monto_documento'],$d)?></div></div><div class="col"><small>Interés</small><div class="fw-bold"><?=money_currency((float)$d['interes_pendiente'],$d)?></div></div><div class="col"><small>Capital</small><div class="fw-bold"><?=money_currency((float)$d['capital_pendiente'],$d)?></div></div><div class="col"><small>Saldo</small><div class="fw-bold text-primary"><?=money_currency((float)$d['saldo'],$d)?></div></div></div><form method="post" class="row g-3"><input type="hidden" name="csrf" value="<?=csrf()?>"><input type="hidden" name="cliente_id" value="<?=$cid?>"><input type="hidden" name="detalle_id" value="<?=$did?>"><div class="col-md-4"><label class="form-label">Monto a pagar</label><input type="text" inputmode="decimal" maxlength="16" id="pagoCapitalVisible" class="form-control" required><input type="hidden" name="monto" id="pagoCapital"></div><div class="col-md-4 align-self-end"><button class="btn btn-primary">Registrar pago</button> <a class="btn btn-outline-secondary" href="?p=pago_capitales&cliente_id=<?=$cid?>">Volver</a></div></form></div></div><?php endif;endif;?><script>window.BASE_URL='<?=BASE_URL?>';let lookup=document.querySelector('.lookup');if(lookup)autocomplete(lookup,lookup.nextElementSibling,'clientes');let pv=document.querySelector('#pagoCapitalVisible'),pr=document.querySelector('#pagoCapital');if(pv){const usd=<?=json_encode(($d['codigo']??'PYG')==='USD')?>;pv.addEventListener('input',()=>{let digits=pv.value.replace(/\D/g,'').slice(0,12),v=usd?Number(digits)/100:Number(digits);pr.value=v.toFixed(usd?2:0);pv.value=digits?new Intl.NumberFormat('es-PY',{minimumFractionDigits:usd?2:0,maximumFractionDigits:usd?2:0}).format(v):''})}</script><?php page_end();exit;
}
