/* reservations.js — KREMER Régis v2.4.1 (Lot 4)
   Réservations de stock (sans retrait physique).
   Correctif cascade magasin → catégorie → produit → emplacement.
*/

(function(){
  const root = document.getElementById('reservationsPage');
  if(!root) return;

  const elTable = document.getElementById('reservationsTable');
  const elBody = elTable ? elTable.querySelector('tbody') : null;
  const elStatus = document.getElementById('resStatus');
  const elSearch = document.getElementById('resSearch');

  let reservations = [];
  let products = [];
  let warehouses = [];
  let locations = [];
  let categories = [];

  function esc(s){ return (s??'').toString().replace(/[&<>"']/g,m=>({"&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","'":"&#039;"}[m])); }

  function productLabel(pid){
    const p = products.find(x=>String(x.id)===String(pid));
    return p ? `${p.name||''}${p.sku?(' ('+p.sku+')'):''}` : `#${pid}`;
  }
  function warehouseLabel(wid){
    const w = warehouses.find(x=>String(x.id)===String(wid));
    return w ? (w.name||`#${wid}`) : `#${wid}`;
  }
  function locationLabel(locId){
    const l = locations.find(x=>String(x.id)===String(locId));
    return l ? (l.code||l.name||locId) : (locId||'default');
  }

  function render(){
    if(!elBody) return;
    const q = (elSearch?.value||'').trim().toLowerCase();
    const st = (elStatus?.value||'').trim();
    let list = reservations;
    if(st) list = list.filter(r => String(r.status||'active')===st);
    if(q){
      list = list.filter(r =>
        productLabel(r.productId).toLowerCase().includes(q) ||
        (r.worksite||'').toLowerCase().includes(q) ||
        (r.label||'').toLowerCase().includes(q)
      );
    }

    elBody.innerHTML = list.map(r=>{
      const status = (r.status||'active');
      const badge = status==='active' ? 'badge badge-warning' : (status==='released' ? 'badge badge-success' : 'badge badge-muted');
      const badgeTxt = status==='active' ? 'Active' : (status==='released' ? 'Libérée' : 'Annulée');
      const canRelease = status==='active';
      return `
        <tr>
          <td><strong>${esc(productLabel(r.productId))}</strong></td>
          <td>${esc(warehouseLabel(r.warehouseId))}</td>
          <td>${esc(locationLabel(r.locationId||'default'))}</td>
          <td>${esc(r.qty)} ${esc(r.unit)}</td>
          <td>${esc(r.worksite||'')}</td>
          <td><span class="${badge}">${badgeTxt}</span></td>
          <td>
            ${canRelease?`<button class="btn btn-success btn-sm" data-act="release" data-id="${esc(r.id)}">Libérer</button>`:''}
            <button class="btn btn-danger btn-sm" data-act="del" data-id="${esc(r.id)}">Supprimer</button>
          </td>
        </tr>`;
    }).join('');
  }

  async function load(){
    [products, warehouses, locations, categories] = await Promise.all([
      Api.products(),
      Api.warehouses(),
      Api.locations(),
      Api.categories(),
    ]);
    reservations = await Api.reservations();
    render();
  }

  function buildProductOptions(list, selected=''){
    return `<option value="">— Choisir —</option>` +
      list.map(p=>`<option value="${p.id}" ${String(p.id)===String(selected)?'selected':''}>${esc(p.name)}${p.sku?(' — '+esc(p.sku)) : ''}</option>`).join('');
  }

  function buildLocationOptions(list, selected='default'){
    return `<option value="default">Défaut</option>` +
      list.map(l=>`<option value="${l.id}" ${String(l.id)===String(selected)?'selected':''}>${esc(l.code||l.name||l.id)}</option>`).join('');
  }

  function getProductsForModalScope(warehouseId, category){
    if(window.StockCascade){
      return StockCascade.filterProducts(products, { warehouseId, category, includeUnrestricted: true });
    }
    let out = products.slice();
    if(category) out = out.filter(p => String(p.category||'') === String(category));
    return out;
  }

  function openCreate(){
    const initialWarehouseId = String(warehouses[0]?.id || '');
    const initialCategories = window.StockCascade
      ? StockCascade.getWarehouseCategories(warehouses, initialWarehouseId, products, categories)
      : (categories || []);
    const initialProducts = getProductsForModalScope(initialWarehouseId, '');
    const initialLocations = window.StockCascade
      ? StockCascade.getLocationsForWarehouse(locations, initialWarehouseId)
      : locations;

    const html = `
      <div>
        <div class="row" style="gap:10px;flex-wrap:wrap">
          <div style="min-width:220px">
            <label class="label">Magasin</label>
            <select class="sel" id="resWid">
              ${warehouses.map(w=>`<option value="${w.id}" ${String(w.id)===initialWarehouseId?'selected':''}>${esc(w.name||('Magasin #'+w.id))}</option>`).join('')}
            </select>
          </div>
          <div style="min-width:220px">
            <label class="label">Catégorie</label>
            <select class="sel" id="resCat">
              <option value="">Toutes catégories</option>
              ${initialCategories.map(c=>`<option value="${esc(c)}">${esc(c)}</option>`).join('')}
            </select>
          </div>
          <div style="flex:1;min-width:240px">
            <label class="label">Produit</label>
            <select class="sel" id="resPid">
              ${buildProductOptions(initialProducts)}
            </select>
          </div>
          <div style="min-width:220px">
            <label class="label">Emplacement</label>
            <select class="sel" id="resLoc">
              ${buildLocationOptions(initialLocations)}
            </select>
          </div>
        </div>
        <div class="row" style="gap:10px;flex-wrap:wrap;margin-top:10px">
          <div style="min-width:180px">
            <label class="label">Quantité</label>
            <input class="inp" id="resQty" type="number" step="0.001" value="1" />
          </div>
          <div style="min-width:180px">
            <label class="label">Unité</label>
            <input class="inp" id="resUnit" value="piece" />
          </div>
          <div style="flex:1;min-width:220px">
            <label class="label">Chantier / Centre de coût</label>
            <input class="inp" id="resWorksite" placeholder="Ex: Chantier X" />
          </div>
        </div>
        <div style="margin-top:10px">
          <label class="label">Libellé</label>
          <input class="inp" id="resLabel" placeholder="Ex: Réservation pour intervention" />
        </div>
        <div class="row" style="justify-content:flex-end;gap:8px;margin-top:14px">
          <button class="btn btn-secondary" id="btnCancel">Annuler</button>
          <button class="btn btn-primary" id="btnSave">Réserver</button>
        </div>
      </div>`;

    Modal.show({ title:'Nouvelle réservation', sub:'Réserver du stock sans sortie physique.', icon:'check', html });

    const widSel = document.getElementById('resWid');
    const catSel = document.getElementById('resCat');
    const pidSel = document.getElementById('resPid');
    const locSel = document.getElementById('resLoc');

    const refreshModalCascade = () => {
      const wid = widSel?.value || '';
      const cat = catSel?.value || '';
      const selectedPid = pidSel?.value || '';
      const selectedLoc = locSel?.value || 'default';

      const allowedCats = window.StockCascade
        ? StockCascade.getWarehouseCategories(warehouses, wid, products, categories)
        : (categories || []);
      if(catSel){
        catSel.innerHTML = `<option value="">Toutes catégories</option>` + allowedCats.map(c=>`<option value="${esc(c)}">${esc(c)}</option>`).join('');
        if(allowedCats.includes(cat)) catSel.value = cat; else catSel.value = '';
      }

      const filteredProducts = getProductsForModalScope(wid, catSel?.value || '');
      if(pidSel){
        pidSel.innerHTML = buildProductOptions(filteredProducts, selectedPid);
      }

      const filteredLocations = window.StockCascade
        ? StockCascade.getLocationsForWarehouse(locations, wid)
        : locations;
      if(locSel){
        locSel.innerHTML = buildLocationOptions(filteredLocations, selectedLoc);
        if(filteredLocations.some(l => String(l.id) === String(selectedLoc)) || selectedLoc === 'default') {
          locSel.value = selectedLoc;
        }
      }
    };

    widSel?.addEventListener('change', refreshModalCascade);
    catSel?.addEventListener('change', refreshModalCascade);
    refreshModalCascade();

    document.getElementById('btnCancel')?.addEventListener('click', ()=>Modal.close());
    document.getElementById('btnSave')?.addEventListener('click', async ()=>{
      const productId = Number(document.getElementById('resPid')?.value||0);
      const warehouseId = Number(document.getElementById('resWid')?.value||0);
      const locationId = (document.getElementById('resLoc')?.value||'default');
      const qty = Number(document.getElementById('resQty')?.value||0);
      const unit = (document.getElementById('resUnit')?.value||'piece').trim();
      const worksite = (document.getElementById('resWorksite')?.value||'').trim();
      const label = (document.getElementById('resLabel')?.value||'').trim();

      if(!productId || !warehouseId || qty<=0){ toast('Champs invalides.','error'); return; }
      try{
        await Api.reservationCreate({ productId, warehouseId, locationId, qty, unit, worksite, label });
        toast('Réservation créée.','success');
        Modal.close();
        await load();
      } catch(err){
        toast(err?.message || 'Erreur', 'error');
      }
    });
  }

  async function onClick(e){
    const btn = e.target.closest('button[data-act]');
    if(!btn) return;
    const id = btn.getAttribute('data-id');
    const act = btn.getAttribute('data-act');

    if(act==='release'){
      try{ await Api.reservationUpdate({ id, status:'released' }); toast('Réservation libérée.','success'); await load(); } catch(err){ toast(err?.message||'Erreur','error'); }
    }
    if(act==='del'){
      if(!confirm('Supprimer cette réservation ?')) return;
      try{ await Api.reservationDelete(id); toast('Réservation supprimée.','success'); await load(); } catch(err){ toast(err?.message||'Erreur','error'); }
    }
  }

  document.getElementById('btnResReload')?.addEventListener('click', load);
  document.getElementById('btnResCreate')?.addEventListener('click', openCreate);
  elStatus?.addEventListener('change', render);
  elSearch?.addEventListener('input', render);
  elBody?.addEventListener('click', onClick);

  load();
})();
