<?php
if(!isset($_SESSION)){ session_start(); }
require_once('conecta.php');
mysqli_set_charset($conecta,"utf8");

$fecha_hoy = date('Y-m-d');

$res_cuentas = mysqli_query($conecta,"SELECT idcuenta, denominacion FROM cuenta WHERE estado='ABIERTA'");
$res_tipos   = mysqli_query($conecta,"SELECT idtipo_cuenta, nombre FROM tipo_cuenta");
?>

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Venta POS</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<style>
body{background:#f1f5f9;padding:20px;font-family:Segoe UI}
.panel{background:#fff;padding:20px;border-radius:8px;margin-bottom:15px}
.result-box{
position:absolute;background:#fff;border:1px solid #ccc;width:100%;
max-height:250px;overflow:auto;z-index:9999;
}
.item{padding:8px;cursor:pointer;border-bottom:1px solid #eee}
.item:hover{background:#e2e8f0}
.total{font-size:30px;font-weight:bold;text-align:right;background:#111;color:#0f0;padding:10px}
</style>

</head>
<body>

<div class="container">

<form method="POST" action="procesar_venta_final.php">

<!-- CLIENTE -->
<div class="panel">
<label>Cliente</label>
<input type="text" id="input-cli" class="form-control" onkeyup="buscarCliente(event)">
<input type="hidden" id="idcli" name="idcliente">

<div id="box-cli" class="result-box" style="display:none"></div>
</div>

<!-- ARTICULOS -->
<div class="panel" style="position:relative">

<label>Articulo</label>
<input type="text" id="input-art" class="form-control" onkeyup="buscarArticulo(event)">

<div id="box-art" class="result-box" style="display:none"></div>

</div>

<!-- CARRITO -->
<div class="panel">
<table class="table">
<thead>
<tr>
<th>Producto</th>
<th>Cant</th>
<th>Precio</th>
<th>Subtotal</th>
<th></th>
</tr>
</thead>
<tbody id="carrito"></tbody>
</table>

<div class="total" id="total">0</div>
<input type="hidden" name="total_final" id="total_input">
</div>

<!-- PAGOS -->
<div class="panel">

<select id="cta">
<?php while($c=mysqli_fetch_assoc($res_cuentas)){ ?>
<option value="<?= $c['idcuenta'] ?>"><?= $c['denominacion'] ?></option>
<?php } ?>
</select>

<select id="tipo">
<?php while($t=mysqli_fetch_assoc($res_tipos)){ ?>
<option value="<?= $t['idtipo_cuenta'] ?>"><?= $t['nombre'] ?></option>
<?php } ?>
</select>

<input type="text" id="monto_txt" oninput="formato(this)" placeholder="monto">
<input type="hidden" id="monto">

<button type="button" onclick="addPago()">Agregar pago</button>

<table class="table">
<tbody id="pagos"></tbody>
</table>

</div>

<button class="btn btn-success btn-block">FINALIZAR</button>

</form>
</div>

<script>

let listaArt = [];
let listaCli = [];

function buscarArticulo(e){

let v = document.getElementById('input-art').value;

fetch('buscar_articulos.php?q='+v)
.then(r=>r.json())
.then(d=>{

listaArt = d;

let box = document.getElementById('box-art');
box.innerHTML='';
box.style.display='block';

d.forEach(i=>{
box.innerHTML += `<div class="item" onclick='addArt(${JSON.stringify(i)})'>
${i.codigo} - ${i.nom} (${i.precio})
</div>`;
});

});
}

function addArt(i){

let fila = `
<tr>
<td>${i.nom}<input type="hidden" name="art_ids[]" value="${i.id}"></td>
<td><input type="number" name="cant[]" value="1" oninput="calc()"></td>
<td>${i.precio}</td>
<td class="sub">${i.precio}</td>
<td><button type="button" onclick="this.closest('tr').remove();calc()">x</button></td>
</tr>`;

document.getElementById('carrito').innerHTML += fila;

document.getElementById('input-art').value='';
document.getElementById('box-art').style.display='none';

calc();
}

function calc(){

let total=0;

document.querySelectorAll('#carrito tr').forEach(tr=>{
let c = tr.querySelector('input[name="cant[]"]').value;
let p = parseFloat(tr.children[2].innerText);
let s = c*p;
tr.querySelector('.sub').innerText=s;
total+=s;
});

document.getElementById('total').innerText=total;
document.getElementById('total_input').value=total;
}

function buscarCliente(e){

let v = document.getElementById('input-cli').value;

fetch('buscar_clientes.php?q='+v)
.then(r=>r.json())
.then(d=>{

let box = document.getElementById('box-cli');
box.innerHTML='';
box.style.display='block';

d.forEach(i=>{
box.innerHTML += `<div class="item" onclick='selCli(${JSON.stringify(i)})'>
${i.text}
</div>`;
});

});
}

function selCli(i){
document.getElementById('input-cli').value=i.text;
document.getElementById('idcli').value=i.id;
document.getElementById('box-cli').style.display='none';
}

function formato(el){
let v=el.value.replace(/\D/g,'');
document.getElementById('monto').value=v;
el.value=v;
}

function addPago(){

let m=document.getElementById('monto').value;

if(!m) return;

let fila=`
<tr>
<td>${document.getElementById('cta').selectedOptions[0].text}</td>
<td>${document.getElementById('tipo').selectedOptions[0].text}</td>
<td>${m}</td>
<td><button onclick="this.closest('tr').remove()">x</button></td>
</tr>`;

document.getElementById('pagos').innerHTML+=fila;

}

</script>

</body>
</html>