<?php
require __DIR__ . '/../init.php';
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Kiosco - FuelPOS</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.0.0/dist/signature_pad.umd.min.js"></script>
<style>
  body{background:#f6f7fb; margin:0; padding:12px; font-family:Inter,Segoe UI,Arial;}
  .card { border-radius:10px; box-shadow:0 6px 18px rgba(20,30,60,0.06); }
  #canvas { border:1px solid #ddd; border-radius:6px; width:100%; height:180px; touch-action:none; }
  .small-muted { color:#6c757d; font-size:0.9rem; }
  @media (max-width:576px){
    #canvas { height:140px; }
  }
</style>
</head>
<body>
<div class="container">
  <div class="row gy-3">
    <div class="col-12">
      <div class="d-flex justify-content-between align-items-center">
        <h4 class="m-0">Kiosco - Venta en isla</h4>
        <div>
          <a class="btn btn-sm btn-outline-secondary" href="<?= site('pos/index.php') ?>">Ir a Caja</a>
          <a class="btn btn-sm btn-outline-secondary" href="<?= site('display/index.php') ?>" target="_blank">Ver Display</a>
        </div>
      </div>
    </div>

    <div class="col-md-6">
      <div class="card p-3">
        <h5 class="mb-2">Seleccionar bomba / manguera</h5>
        <div id="pumpsArea" class="mb-2">Cargando bombas...</div>

        <div id="hoseArea" style="display:none;" class="mt-2">
          <h6>Manguera seleccionada:</h6>
          <div id="hoseInfo" class="mb-2"></div>

          <div class="mb-2">
            <label class="form-label small-muted">Modo</label>
            <select id="mode" class="form-select">
              <option value="qty">Litros / Unidades</option>
              <option value="amount">Importe</option>
            </select>
          </div>

          <div id="qtyRow" class="mb-2">
            <label class="form-label small-muted" id="qtyLabel">Cantidad (L):</label>
            <input id="qty" type="number" min="0" step="0.01" class="form-control" value="1">
          </div>

          <div id="amountRow" class="mb-2" style="display:none;">
            <label class="form-label small-muted">Importe ($):</label>
            <input id="amount" type="number" min="0" step="0.01" class="form-control" value="">
          </div>

          <div class="mb-2">
            <label class="form-label small-muted">Total estimado:</label>
            <div id="total" class="fs-5 fw-600">$0.00</div>
          </div>
        </div>

      </div>
    </div>

    <div class="col-md-6">
      <div class="card p-3">
        <h5 class="mb-2">Firma del cliente</h5>
        <div>
          <canvas id="canvas"></canvas>
          <div class="d-flex gap-2 mt-2">
            <button id="clearSig" class="btn btn-sm btn-outline-secondary">Limpiar</button>
            <button id="fillSig" class="btn btn-sm btn-outline-secondary">Firma de prueba</button>
          </div>
        </div>

        <hr>

        <div class="mb-2">
          <label class="form-label small-muted">Método de pago</label>
          <select id="payment" class="form-select">
            <option value="pump">Pago en isla</option>
            <option value="cash">Efectivo</option>
            <option value="card">Tarjeta</option>
          </select>
        </div>

        <div class="d-grid mt-3">
          <button id="finalize" class="btn btn-success btn-lg">Finalizar venta</button>
        </div>

        <div id="msg" class="mt-3"></div>
      </div>
    </div>

  </div>
</div>

<script>
const api = '<?= site('api.php') ?>';
let pumps = [];
let selectedPump = null;
let selectedHose = null;
let signaturePad;
let productPrice = 0;
let productUnit = 'L';

function setMsg(html, type='info'){
  const el = document.getElementById('msg');
  const cls = type==='error' ? 'alert-danger' : type==='success' ? 'alert-success' : 'alert-info';
  el.innerHTML = `<div class="alert ${cls}">${html}</div>`;
}

function clearMsg(){ document.getElementById('msg').innerHTML = ''; }

async function loadPumps(){
  try {
    const res = await fetch(api+'?action=get_pumps');
    const j = await res.json();
    if (!j.ok) { document.getElementById('pumpsArea').innerText = 'Error cargando bombas'; return; }
    pumps = j.pumps;
    renderPumps();
  } catch(e){
    document.getElementById('pumpsArea').innerText = 'Error de conexión';
    console.error(e);
  }
}

function renderPumps(){
  const wrap = document.getElementById('pumpsArea');
  if (!pumps || pumps.length===0) { wrap.innerHTML = '<div class="text-muted">No hay bombas definidas en el sistema</div>'; return; }
  let html = '<div class="list-group">';
  pumps.forEach(p=>{
    html += `<div class="list-group-item">
      <div class="d-flex justify-content-between align-items-center">
        <div><strong>${escapeHtml(p.name)}</strong><div class="small-muted">${escapeHtml(p.location || '')}</div></div>
        <div>
          <button class="btn btn-sm btn-outline-primary" onclick="showHoses(${p.id})">Seleccionar</button>
        </div>
      </div>
    </div>`;
  });
  html += '</div>';
  wrap.innerHTML = html;
}

async function showHoses(pumpId){
  clearMsg();
  selectedPump = pumps.find(x=>x.id==pumpId);
  // fetch hoses for pump
  try {
    const res = await fetch(api+'?action=get_hoses&pump_id='+pumpId);
    const j = await res.json();
    if (!j.ok) return setMsg('No se pudieron cargar mangueras','error');
    const hoses = j.hoses;
    if (!hoses.length) return setMsg('Esta bomba no tiene mangueras asignadas','error');
    let html = '<div class="list-group">';
    hoses.forEach(h=>{
      html += `<button class="list-group-item list-group-item-action" onclick='selectHose(${JSON.stringify(h)})'>${escapeHtml(h.name)} — ${escapeHtml(h.product_name)} — $${parseFloat(h.price).toFixed(3)} / ${escapeHtml(h.unit)}</button>`;
    });
    html += '</div>';
    document.getElementById('hoseArea').style.display = 'block';
    document.getElementById('hoseInfo').innerHTML = html;
    // reset selection
    selectedHose = null;
    updateTotals();
  } catch(e){
    console.error(e);
    setMsg('Error cargando mangueras','error');
  }
}

function selectHose(hose){
  // hose is an object passed from onclick via JSON.stringify -> will be string; ensure object:
  if (typeof hose === 'string') {
    try { hose = JSON.parse(hose); } catch(e){ console.error(e); }
  }
  selectedHose = hose;
  productPrice = parseFloat(hose.price) || 0;
  productUnit = hose.unit || 'L';
  document.getElementById('hoseInfo').innerHTML = `<div><strong>${escapeHtml(hose.name)}</strong> — ${escapeHtml(hose.product_name)} <div class="small-muted">Precio: $${productPrice.toFixed(3)} / ${escapeHtml(productUnit)}</div></div>`;
  // update qty label depending on unit
  document.getElementById('qtyLabel').innerText = productUnit === 'UN' ? 'Cantidad (unidades):' : 'Cantidad (L):';
  document.getElementById('qty').value = productUnit === 'UN' ? 1 : 1.00;
  document.getElementById('amount').value = '';
  updateTotals();
}

function updateTotals(){
  let mode = document.getElementById('mode').value;
  let total = 0;
  if (!selectedHose) {
    document.getElementById('total').innerText = '$0.00';
    return;
  }
  if (mode === 'qty'){
    const qty = parseFloat(document.getElementById('qty').value) || 0;
    total = qty * productPrice;
  } else {
    const amt = parseFloat(document.getElementById('amount').value) || 0;
    total = amt;
  }
  document.getElementById('total').innerText = '$' + total.toFixed(2);
}

document.getElementById('mode').addEventListener('change', function(){
  const m = this.value;
  document.getElementById('qtyRow').style.display = m==='qty' ? 'block' : 'none';
  document.getElementById('amountRow').style.display = m==='amount' ? 'block' : 'none';
  updateTotals();
});
document.getElementById('qty').addEventListener('input', updateTotals);
document.getElementById('amount').addEventListener('input', updateTotals);

// signature pad init
window.addEventListener('load', function(){
  const canvas = document.getElementById('canvas');
  signaturePad = new SignaturePad(canvas, { backgroundColor: 'rgba(255,255,255,1)' });
  // resize canvas for high DPI
  function resizeCanvas() {
    const ratio = Math.max(window.devicePixelRatio || 1, 1);
    canvas.width = canvas.offsetWidth * ratio;
    canvas.height = canvas.offsetHeight * ratio;
    canvas.getContext('2d').scale(ratio, ratio);
    signaturePad.clear();
  }
  window.addEventListener('resize', resizeCanvas);
  resizeCanvas();
});

document.getElementById('clearSig').addEventListener('click', ()=>signaturePad.clear());
document.getElementById('fillSig').addEventListener('click', ()=>{
  const ctx = document.getElementById('canvas').getContext('2d');
  ctx.strokeStyle = "#111"; ctx.lineWidth = 2;
  ctx.beginPath(); ctx.moveTo(10,40); ctx.lineTo(80,60); ctx.lineTo(140,30); ctx.lineTo(220,90); ctx.stroke();
  signaturePad.fromData(signaturePad.toData()); // keep internal state
});

document.getElementById('finalize').addEventListener('click', async ()=>{
  clearMsg();
  if (!selectedHose) return setMsg('Seleccione una manguera','error');
  let mode = document.getElementById('mode').value;
  let qty = parseFloat(document.getElementById('qty').value) || 0;
  let amount = parseFloat(document.getElementById('amount').value) || 0;
  if (mode === 'qty' && qty <= 0) return setMsg('Ingrese cantidad válida','error');
  if (mode === 'amount' && amount <= 0) return setMsg('Ingrese importe válido','error');

  // calculate item
  let itemQty = qty;
  let unitPrice = productPrice;
  if (mode === 'amount') {
    // convert amount to qty if unit is L: qty = amount / price
    if (productUnit === 'L' && productPrice > 0) {
      itemQty = amount / productPrice;
      unitPrice = productPrice;
    } else {
      // if unit not L, assume qty = 1 and unitPrice = amount
      itemQty = 1;
      unitPrice = amount;
    }
  }

  // prepare payload
  const items = [{
    product_id: parseInt(selectedHose.product_id),
    qty: parseFloat(itemQty.toFixed(3)),
    unit_price: parseFloat(unitPrice.toFixed(4))
  }];

  // signature (optional) as dataURL
  let sigData = '';
  if (!signaturePad.isEmpty()) {
    sigData = signaturePad.toDataURL('image/png');
  }

  const payload = { action: 'create_sale', items: items, payment_method: document.getElementById('payment').value, signature: sigData };

  try {
    setMsg('Registrando venta...','info');
    const r = await fetch(api, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });
    const j = await r.json();
    if (!j.ok) {
      setMsg('Error: ' + (j.msg || 'No se pudo completar la venta'),'error');
      return;
    }
    setMsg('Venta registrada: ' + j.sale_code, 'success');
    // open receipt in new window
    window.open('<?= site('pos/receipt.php') ?>?id=' + j.sale_id, '_blank');
    // clear form
    signaturePad.clear();
    document.getElementById('qty').value = productUnit === 'UN' ? 1 : 1.00;
    document.getElementById('amount').value = '';
    updateTotals();
  } catch (e) {
    console.error(e);
    setMsg('Error de conexión o servidor','error');
  }
});

// small helper
function escapeHtml(s){ return String(s||'').replace(/[&<>"']/g, function(m){ return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]); }); }

loadPumps();
</script>
</body>
</html>