<?php
require __DIR__ . '/../init.php';
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>POS - FuelPOS</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="<?= site('assets/style.css') ?>">
<style>
/* POS styles */
.pump-card { cursor:pointer; }
.pump-selected { outline: 3px solid #0d6efd; box-shadow:0 6px 18px rgba(13,110,253,0.12); }
.hose-btn { cursor:pointer; }
.hose-selected { background:#0d6efd; color:#fff; border-color:#0d6efd; }
.product-card { min-height:120px; position:relative; }
.product-card.disabled { opacity:0.6; }
.product-overlay {
  position:absolute;
  inset:0;
  display:flex;
  align-items:center;
  justify-content:center;
  background:rgba(255,255,255,0.7);
  font-weight:600;
  color:#6c757d;
  border-radius:.25rem;
}
.info-muted { color:#6c757d; font-size:.9rem; }
.empty-note { color:#6c757d; font-style:italic; }
.small-note { font-size:.85rem; color:#6c757d; }
.filter-badge { font-size:.85rem; }
.hoses-count { font-size:12px; color:#6c757d; margin-top:6px; }
.debug-panel { background:#f8f9fa; border:1px solid #e9ecef; padding:10px; font-size:12px; max-height:220px; overflow:auto; white-space:pre-wrap; }
</style>
</head>
<body>
<nav class="navbar navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand">FuelPOS - Caja</a>
    <div>
      <!-- use project_url to point to project-root display -->
      <a class="btn btn-sm btn-outline-secondary" href="<?= project_url('display/index.php') ?>" target="_blank">Ver Display</a>
    </div>
  </div>
</nav>

<div class="container py-3">
  <div class="row">
    <!-- Left: Pumps + Hoses -->
    <div class="col-md-3">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h5 class="mb-0">Islas / Bombas</h5>
        <div>
          <button id="refreshPumpsBtn" class="btn btn-sm btn-outline-primary">Refrescar</button>
        </div>
      </div>
      <div id="pumpsList" class="mb-3"></div>

      <div class="d-flex justify-content-between align-items-center mb-2">
        <h6 class="mb-0">Seleccionada</h6>
        <button id="clearFilterBtn" class="btn btn-sm btn-outline-secondary" title="Mostrar todos los productos">Mostrar todo</button>
      </div>
      <div id="selectedPumpInfo" class="p-2 border rounded bg-white small info-muted">Ninguna isla seleccionada</div>

      <div class="mt-2 small-note">Seleccione una manguera para activar los productos.</div>

      <div class="mt-3">
        <strong>Estado API</strong>
        <div id="apiStatus" class="small text-muted">Cargando...</div>
      </div>

      <div class="mt-3">
        <strong>DEBUG (respuestas)</strong>
        <div id="debugPanel" class="debug-panel" style="display:none;"></div>
      </div>
    </div>

    <!-- Center: Products -->
    <div class="col-md-5">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h5 class="mb-0">Productos</h5>
        <div id="currentFilter" class="filter-badge text-muted"></div>
      </div>
      <div id="products" class="row g-2"></div>
    </div>

    <!-- Right: Cart -->
    <div class="col-md-4">
      <h5>Carrito</h5>
      <div id="cartList"></div>
      <div class="mt-2">
        <label>Pago:</label>
        <select id="payment" class="form-select"><option value="cash">Efectivo</option><option value="card">Tarjeta</option></select>
        <button id="payBtn" class="btn btn-success w-100 mt-2">Finalizar Venta</button>
      </div>
      <div id="result" class="mt-2"></div>
    </div>
  </div>
</div>

<script>
/*
  IMPORTANT: point to the project's root api.php using project_url().
  project_url() is provided by init.php and will produce e.g.:
    http://192.168.0.134/fuelpos/api.php
  This avoids "../" in generated URLs.
*/
const api = '<?= project_url('api.php') ?>';

let products = [];
let pumps = [];
let hosesByPump = {};
let selectedPumpId = null;
let selectedHoseId = null;
let cart = [];
let activeProductFilterId = null;

function esc(s){ return String(s === null || s === undefined ? '' : s); }
function findProduct(id){ return products.find(p => Number(p.id) === Number(id)); }
function findHose(hoseId){
  for (const pid in hosesByPump){
    const list = hosesByPump[pid] || [];
    const h = list.find(x => Number(x.id) === Number(hoseId));
    if (h) return Object.assign({}, h, { pump_id: Number(pid) });
  }
  return null;
}
function getPumpById(id){ return pumps.find(p => Number(p.id) === Number(id)); }

async function fetchJsonSafe(url){
  try {
    const res = await fetch(url, {cache:'no-store'});
    if (!res.ok) return { ok:0, httpStatus: res.status, error:true, url };
    const j = await res.json();
    return j;
  } catch (err) {
    return { ok:0, error:true, msg: err.message, url };
  }
}

/* RENDERERS (unchanged but robust) */
function renderPumps(){
  const wrap = document.getElementById('pumpsList');
  wrap.innerHTML = '';
  if (!pumps || pumps.length === 0) {
    wrap.innerHTML = '<div class="empty-note">No se encontraron islas (pumps). Revisa la API.</div>';
    return;
  }
  pumps.forEach(p => {
    const card = document.createElement('div');
    card.className = 'card mb-2 pump-card';
    card.dataset.pumpId = p.id;
    card.innerHTML = `<div class="card-body p-2">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <strong>${esc(p.name)}</strong><br>
          <small class="text-muted">${esc(p.location || '')}</small>
        </div>
        <div><small class="text-muted">#${esc(p.id)}</small></div>
      </div>
      <div class="mt-2" id="pump_hoses_${p.id}"></div>
    </div>`;
    wrap.appendChild(card);
  });
  pumps.forEach(p => renderHosesForPump(p.id));
  updatePumpSelectionUI();
}

function renderHosesForPump(pumpId){
  const container = document.getElementById('pump_hoses_' + pumpId);
  if (!container) return;
  container.innerHTML = '';
  const hoses = hosesByPump[pumpId] || [];
  if (!hoses.length) {
    container.innerHTML = `<div class="small info-muted">Sin mangueras registradas</div>`;
    return;
  }
  hoses.forEach(h => {
    const label = h.name || ('Manguera ' + h.id);
    const prodLabel = h.product_name ? (' — ' + h.product_name) : '';
    const btn = document.createElement('button');
    btn.className = 'btn btn-sm btn-outline-secondary me-1 mb-1 hose-btn';
    btn.dataset.hoseId = h.id;
    btn.dataset.pumpId = pumpId;
    btn.type = 'button';
    btn.innerHTML = esc(label) + esc(prodLabel);
    container.appendChild(btn);
  });
  updatePumpSelectionUI();
}

function updatePumpSelectionUI(){
  document.querySelectorAll('.pump-card').forEach(card=>{
    const pid = Number(card.dataset.pumpId);
    if (pid === Number(selectedPumpId)) card.classList.add('pump-selected'); else card.classList.remove('pump-selected');
    const btns = card.querySelectorAll('.hose-btn');
    btns.forEach(b=>{
      const hid = Number(b.dataset.hoseId);
      if (hid === Number(selectedHoseId)) {
        b.classList.add('hose-selected');
        b.classList.remove('btn-outline-secondary');
      } else {
        b.classList.remove('hose-selected');
        b.classList.add('btn-outline-secondary');
      }
    });
  });

  const info = document.getElementById('selectedPumpInfo');
  if (!selectedPumpId) {
    info.className = 'p-2 border rounded bg-white small info-muted';
    info.innerHTML = 'Ninguna isla seleccionada';
    return;
  }
  const pump = getPumpById(selectedPumpId);
  const hose = findHose(selectedHoseId);
  let html = `<div><strong>${esc(pump.name)}</strong></div><div class="small text-muted">${esc(pump.location || '')}</div>`;
  if (hose) html += `<div class="mt-1"><small>Manguera: ${esc(hose.name)} (ID ${esc(hose.id)})</small></div>`;
  else html += `<div class="mt-1 small text-danger">No hay manguera seleccionada</div>`;
  info.className = 'p-2 border rounded bg-white small';
  info.innerHTML = html;

  // hoses count
  const hoses = hosesByPump[selectedPumpId] || [];
  const countEl = document.createElement('div');
  countEl.className = 'hoses-count';
  countEl.textContent = 'Mangueras: ' + (hoses.length || 0);
  const existing = info.querySelector('.hoses-count');
  if (!existing) info.appendChild(countEl); else existing.textContent = countEl.textContent;

  // product filter display
  const filterEl = document.getElementById('currentFilter');
  if (activeProductFilterId) {
    const prod = findProduct(activeProductFilterId);
    filterEl.textContent = prod ? `Filtrado: ${prod.name}` : 'Filtrado por producto';
  } else {
    filterEl.textContent = '';
  }
}

function renderProducts(){
  const wrap = document.getElementById('products');
  wrap.innerHTML = '';
  const list = (activeProductFilterId) ? products.filter(p=>Number(p.id)===Number(activeProductFilterId)) : products;
  if (!list || list.length===0) {
    wrap.innerHTML = '<div class="empty-note">No se encontraron productos.</div>';
    return;
  }
  const enabled = (selectedHoseId != null);
  list.forEach(p=>{
    const col = document.createElement('div'); col.className='col-6 col-md-4';
    const disabledClass = enabled ? '' : 'disabled';
    col.innerHTML = `<div class="card p-2 product-card h-100 ${disabledClass}" data-product-id="${p.id}">
      <div><strong>${esc(p.name)}</strong></div>
      <div class="text-muted small">${esc(p.unit)} - $${parseFloat(p.price).toFixed(2)}</div>
      <div class="mt-2 d-flex gap-2">
        <input type="number" min="0" step="0.01" value="1" id="q_${p.id}" class="form-control form-control-sm"${enabled ? '' : ' disabled'}>
        <button class="btn ${enabled ? 'btn-primary' : 'btn-secondary'} flex-shrink-0" onclick="addProductToSelectedHose(${p.id})" ${enabled ? '' : 'disabled'}>Vender</button>
      </div>
    </div>`;
    if (!enabled) {
      const overlay = document.createElement('div');
      overlay.className = 'product-overlay';
      overlay.textContent = 'Seleccione una manguera';
      col.querySelector('.product-card').appendChild(overlay);
    }
    wrap.appendChild(col);
  });
}

/* Cart & Sale logic (as before) */
function addProductToSelectedHose(productId){
  if (!selectedHoseId) return alert('Seleccione primero la isla y la manguera (haga click en la manguera deseada).');
  const qEl = document.getElementById('q_' + productId);
  const qty = qEl ? (parseFloat(qEl.value) || 0) : 0;
  if (qty <= 0) return alert('Cantidad debe ser mayor que 0');
  const p = findProduct(productId);
  if (!p) return alert('Producto no encontrado');
  const total = qty * parseFloat(p.price || 0);
  const hose = findHose(selectedHoseId);
  const item = {
    product_id: p.id,
    name: p.name,
    qty: qty,
    unit_price: p.price,
    total: total,
    hose_id: selectedHoseId,
    hose_name: hose ? hose.name : null,
    pump_id: hose ? hose.pump_id : null,
    pump_name: hose ? getPumpById(hose.pump_id).name : null
  };
  cart.push(item);
  renderCart();
}

function renderCart(){
  const el = document.getElementById('cartList');
  if (cart.length === 0){ el.innerHTML = '<div class="text-muted">Carrito vacío</div>'; return; }
  let html = '<ul class="list-group">';
  cart.forEach((c, idx) => {
    html += `<li class="list-group-item">
      <div class="d-flex justify-content-between align-items-start">
        <div style="max-width:70%">
          <div><strong>${esc(c.name)}</strong></div>
          <div class="small text-muted">${esc(c.pump_name || '')} ${c.hose_name ? '/ ' + esc(c.hose_name) : ''}</div>
          <div class="small">${c.qty} x $${parseFloat(c.unit_price).toFixed(2)} = $${parseFloat(c.total).toFixed(2)}</div>
        </div>
        <div style="min-width:110px; text-align:right">
          <button class="btn btn-sm btn-outline-secondary mb-1" onclick="editCartItem(${idx})">Editar</button>
          <button class="btn btn-sm btn-danger" onclick="removeItem(${idx})">X</button>
        </div>
      </div>
    </li>`;
  });
  html += `</ul><div class="mt-2"><strong>Total: $${cart.reduce((s,i)=>s+i.total,0).toFixed(2)}</strong></div>`;
  el.innerHTML = html;
}
function removeItem(idx){ cart.splice(idx,1); renderCart(); }
function editCartItem(idx){
  const item = cart[idx];
  if (!item) return;
  const newQty = parseFloat(prompt('Cantidad:', item.qty));
  if (isNaN(newQty) || newQty <= 0) return alert('Cantidad inválida');
  let hoseChoices = [];
  for (const pid in hosesByPump){
    hosesByPump[pid].forEach(h => hoseChoices.push({ hose_id: h.id, label: `Hose ${h.id} - ${h.name} (Bomba ${pid})` }));
  }
  const choicesText = hoseChoices.map(h => `${h.hose_id}: ${h.label}`).join('\n');
  const chosen = prompt('Seleccione hose_id para esta línea:\n' + choicesText, item.hose_id || '');
  if (!chosen) return;
  const chosenId = parseInt(chosen,10);
  const hoseObj = findHose(chosenId);
  if (!hoseObj) return alert('Manguera no encontrada');
  item.qty = newQty;
  item.total = newQty * parseFloat(item.unit_price || 0);
  item.hose_id = chosenId;
  item.hose_name = hoseObj.name;
  item.pump_id = hoseObj.pump_id;
  item.pump_name = getPumpById(hoseObj.pump_id).name;
  cart[idx] = item;
  renderCart();
}

/* Events: delegated */
document.getElementById('pumpsList').addEventListener('click', function(e){
  const hoseBtn = e.target.closest('.hose-btn');
  if (hoseBtn) {
    const pumpId = Number(hoseBtn.dataset.pumpId) || null;
    const hoseId = Number(hoseBtn.dataset.hoseId) || null;
    if (hoseId) selectHose(pumpId, hoseId);
    return;
  }
  const card = e.target.closest('.pump-card');
  if (card) {
    const pumpId = Number(card.dataset.pumpId);
    if (pumpId) selectPump(pumpId);
  }
});

/* Selection handlers */
function selectPump(pumpId){
  selectedPumpId = Number(pumpId);
  const hoses = hosesByPump[selectedPumpId] || [];
  if (hoses.length === 1) {
    selectedHoseId = Number(hoses[0].id);
    applyProductFilterFromSelectedHose();
  } else {
    selectedHoseId = null;
    clearProductFilter();
  }
  updatePumpSelectionUI();
}
function selectHose(pumpId, hoseId){
  selectedPumpId = Number(pumpId);
  selectedHoseId = Number(hoseId);
  applyProductFilterFromSelectedHose();
  updatePumpSelectionUI();
}
function applyProductFilterFromSelectedHose(){
  const hose = findHose(selectedHoseId);
  if (hose && (hose.product_id || hose.product_id === 0 || hose.product_id === '0')) {
    activeProductFilterId = hose.product_id ? Number(hose.product_id) : null;
  } else {
    activeProductFilterId = null;
  }
  renderProducts();
}
function clearProductFilter(){
  activeProductFilterId = null;
  selectedPumpId = null;
  selectedHoseId = null;
  renderProducts();
  updatePumpSelectionUI();
}

/* Buttons */
document.getElementById('clearFilterBtn').addEventListener('click', ()=> clearProductFilter());
document.getElementById('refreshPumpsBtn').addEventListener('click', ()=> loadData());

/* Finalize sale */
document.getElementById('payBtn').addEventListener('click', async ()=>{
  if (cart.length === 0) return alert('Carrito vacío');
  for (const c of cart) if (!c.hose_id) return alert('Todos los items deben tener una manguera asignada.');
  const items = cart.map(c => ({ product_id: c.product_id, qty: c.qty, unit_price: c.unit_price, hose_id: c.hose_id }));
  const payment = document.getElementById('payment').value;
  try {
    const r = await fetch(api, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ action: 'create_sale', items, payment_method: payment })
    });
    const j = await r.json();
    if (j.ok) {
      window.open(projectUrlFor('receipt.php') + '?id=' + j.sale_id, '_blank');
      cart = []; renderCart();
      document.getElementById('result').innerHTML = `<div class="alert alert-success">Venta registrada: ${j.sale_code} - Total $${parseFloat(j.total).toFixed(2)}</div>`;
      clearProductFilter();
      setTimeout(()=> loadData(), 700);
    } else {
      alert('Error: ' + j.msg);
    }
  } catch (err) {
    console.error('create sale error', err);
    alert('Error registrando la venta. Revisa la consola.');
  }
});

/* Helper for project-level URLs */
function projectUrlFor(path) {
  const a = document.createElement('a');
  a.href = api; // e.g. http://host/fuelpos/api.php
  const base = a.href.replace(/\/api\.php(\?.*)?$/, '/');
  return base + path;
}

/* Load data and debug output */
async function loadData(){
  setApiStatus('Cargando productos y mangueras...');
  try {
    const rp = await fetchJsonSafe(api + '?action=get_products');
    products = (rp.ok && Array.isArray(rp.products)) ? rp.products : [];

    let rpu = await fetchJsonSafe(api + '?action=get_pumps');
    if (!(rpu.ok && Array.isArray(rpu.pumps) && rpu.pumps.length > 0)) {
      rpu = await fetchJsonSafe(api + '?action=get_pumps_with_last_sale');
    }
    pumps = (rpu.ok && Array.isArray(rpu.pumps)) ? rpu.pumps : [];

    hosesByPump = {};
    let allHoses = [];
    const rhAll = await fetchJsonSafe(api + '?action=get_hoses_all');
    if (rhAll.ok && Array.isArray(rhAll.hoses) && rhAll.hoses.length > 0) {
      allHoses = rhAll.hoses;
    } else {
      const rh = await fetchJsonSafe(api + '?action=get_hoses');
      if (rh.ok && Array.isArray(rh.hoses) && rh.hoses.length > 0) {
        allHoses = rh.hoses;
      } else {
        for (const p of pumps) {
          const rhp = await fetchJsonSafe(api + '?action=get_hoses&pump_id=' + p.id);
          if (rhp.ok && Array.isArray(rhp.hoses) && rhp.hoses.length) allHoses = allHoses.concat(rhp.hoses);
        }
      }
    }

    for (const hRaw of allHoses) {
      const h = Object.assign({}, hRaw);
      if (h.id === undefined && h.hose_id !== undefined) h.id = h.hose_id;
      const pid = Number(h.pump_id ?? h.pump ?? h.pumpId ?? 0) || 0;
      if (!h.product_name && h.product && typeof h.product === 'object' && h.product.name) h.product_name = h.product.name;
      hosesByPump[pid] = hosesByPump[pid] || [];
      hosesByPump[pid].push(h);
    }
    pumps.forEach(p => { hosesByPump[p.id] = hosesByPump[p.id] || []; });

    // debug panel
    const debugEl = document.getElementById('debugPanel');
    debugEl.style.display = 'block';
    const totalHoses = Object.values(hosesByPump).reduce((s,a)=>s + (a? a.length:0), 0);
    const debugObj = {
      time: new Date().toISOString(),
      api: api,
      pumpsRaw: rpu,
      hosesRaw: (typeof rhAll !== 'undefined' ? rhAll : 'not_available'),
      pumps_count: pumps.length,
      hoses_total_found: totalHoses,
      hosesByPump: hosesByPump
    };
    debugEl.textContent = JSON.stringify(debugObj, null, 2);

    setApiStatus(`Cargado: ${pumps.length} islas, ${totalHoses} mangueras`);
    selectedPumpId = null;
    selectedHoseId = null;
    activeProductFilterId = null;

    renderPumps();
    renderProducts();
    renderCart();
  } catch (err) {
    console.error('loadData error', err);
    setApiStatus('Error cargando datos: ' + (err.message || err));
    alert('Error cargando datos. Revisa la consola.');
  }
}

function setApiStatus(text){ document.getElementById('apiStatus').textContent = text; }

/* Init */
loadData();
</script>
</body>
</html>