<?php /* purchases/edit.php — Admin only */
$sym = setting('currency_symbol','Rs.');
?>
<style>
.pur-hero{background:linear-gradient(135deg,#451a03,#92400e 55%,#d97706);
  border-radius:12px;padding:18px 24px;color:#fff;margin-bottom:18px}
.prod-res-item{display:flex;justify-content:space-between;align-items:center;
  padding:8px 12px;cursor:pointer;border-bottom:1px solid #f1f5f9;font-size:.82rem}
.prod-res-item:hover{background:#f0f9ff}
#prod-results{position:absolute;left:0;right:0;top:100%;z-index:99;
  background:#fff;border:1px solid #e2e8f0;border-radius:0 0 8px 8px;
  max-height:260px;overflow-y:auto;box-shadow:0 4px 12px rgba(0,0,0,.1)}
</style>

<!-- Admin notice -->
<div class="alert alert-warning d-flex align-items-center gap-2 py-2 mb-3">
  <i class="bi bi-shield-lock-fill text-warning"></i>
  <span class="small">
    <strong>Admin Edit Mode</strong> — You are editing an existing purchase order.
    Stock levels and supplier balance will be recalculated automatically.
  </span>
</div>

<div class="pur-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5 class="fw-bold mb-1"><i class="bi bi-pencil-square me-2"></i>Edit Purchase Order</h5>
      <div style="opacity:.85;font-size:.82rem">
        <?=e($purchase['invoice_no'])?> &nbsp;·&nbsp;
        <?=e($purchase['supplier_name'])?>
      </div>
    </div>
    <a href="<?=APP_URL?>/purchases/view/<?=$purchase['id']?>"
       class="btn btn-outline-light btn-sm">
      <i class="bi bi-arrow-left me-1"></i>Cancel
    </a>
  </div>
</div>

<?= flashMessages() ?>

<form method="POST" action="<?=APP_URL?>/purchases/edit/<?=$purchase['id']?>"
      id="purchase-form" onsubmit="return submitEdit(event)">
  <?=Auth::csrfField()?>
  <input type="hidden" name="items_json" id="items_json">

  <div class="row g-3">
    <!-- Left -->
    <div class="col-lg-8">

      <!-- Header -->
      <div class="card mb-3">
        <div class="card-header bg-dark text-white fw-semibold small">
          <i class="bi bi-info-circle me-1"></i>Purchase Details
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-4">
              <label class="form-label small fw-semibold">Invoice No.</label>
              <input type="text" class="form-control" value="<?=e($purchase['invoice_no'])?>" readonly>
            </div>
            <div class="col-md-4">
              <label class="form-label small fw-semibold">Supplier</label>
              <input type="text" class="form-control" value="<?=e($purchase['supplier_name'])?>" readonly>
            </div>
            <div class="col-md-4">
              <label class="form-label small fw-semibold">Purchase Date</label>
              <input type="date" name="purchase_date" class="form-control"
                     value="<?=e($purchase['purchase_date'])?>" required>
            </div>
          </div>
        </div>
      </div>

      <!-- Product Search -->
      <div class="card mb-3">
        <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center py-2">
          <span class="fw-semibold small"><i class="bi bi-box-seam me-1"></i>Items</span>
          <span class="badge bg-secondary" id="item-count-badge">0 items</span>
        </div>
        <div class="card-body pb-2">
          <div class="position-relative mb-3">
            <div class="input-group">
              <span class="input-group-text bg-primary text-white">
                <i class="bi bi-upc-scan"></i>
              </span>
              <input type="text" id="prod-search" class="form-control"
                     placeholder="Scan barcode or search product…" autocomplete="off">
              <button class="btn btn-outline-secondary" type="button" id="clear-search"
                      style="display:none" onclick="clearSearch()">
                <i class="bi bi-x"></i>
              </button>
            </div>
            <div id="prod-results" style="display:none"></div>
          </div>

          <!-- Items Table -->
          <div class="table-responsive">
            <table class="table table-sm mb-0" id="items-table">
              <thead class="table-light">
                <tr>
                  <th>#</th><th>Product</th>
                  <th style="width:90px">Qty</th>
                  <th style="width:115px">Cost Price</th>
                  <th style="width:90px">Discount</th>
                  <th style="width:65px">Tax %</th>
                  <th class="text-end" style="width:105px">Total</th>
                  <th style="width:30px"></th>
                </tr>
              </thead>
              <tbody id="items-body">
                <tr id="empty-row">
                  <td colspan="8" class="text-center text-muted py-4">
                    <i class="bi bi-box-seam fs-2 d-block mb-1 opacity-25"></i>
                    No items — use the search above to add
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Note -->
      <div class="card mb-3">
        <div class="card-body py-2">
          <label class="form-label small fw-semibold">Internal Note</label>
          <textarea name="note" class="form-control" rows="2"><?=e($purchase['note']??'')?></textarea>
        </div>
      </div>

    </div>

    <!-- Right: Totals -->
    <div class="col-lg-4">
      <div class="card mb-3">
        <div class="card-header bg-dark text-white fw-semibold small">
          <i class="bi bi-calculator me-1"></i>Order Totals
        </div>
        <div class="card-body">
          <table class="table table-sm mb-0">
            <tr>
              <td class="text-muted">Subtotal</td>
              <td class="text-end fw-semibold" id="t-sub"><?=$sym?>0.00</td>
            </tr>
            <tr>
              <td class="text-muted">
                Discount
                <input type="number" name="discount" id="t-disc-input"
                       class="form-control form-control-sm mt-1"
                       value="<?=e($purchase['discount']??0)?>"
                       step="0.01" min="0" oninput="recalc()">
              </td>
              <td class="text-end text-danger" id="t-disc">-<?=$sym?>0.00</td>
            </tr>
            <tr>
              <td class="text-muted">Tax</td>
              <td class="text-end" id="t-tax"><?=$sym?>0.00</td>
            </tr>
            <tr style="border-top:2px solid #e2e8f0">
              <td class="fw-bold fs-5">Total</td>
              <td class="text-end fw-bold fs-5 text-primary" id="t-total"><?=$sym?>0.00</td>
            </tr>
          </table>

          <div class="alert alert-info small py-2 mt-2 mb-0">
            <i class="bi bi-info-circle me-1"></i>
            Amount already paid: <strong><?=$sym?><?=number_format($purchase['paid'],2)?></strong><br>
            Payment status will be recalculated on save.
          </div>
        </div>
      </div>

      <button type="submit" class="btn btn-warning fw-bold w-100 btn-lg">
        <i class="bi bi-check-circle me-2"></i>Save Changes
      </button>
      <a href="<?=APP_URL?>/purchases/view/<?=$purchase['id']?>"
         class="btn btn-outline-secondary w-100 mt-2">Cancel</a>
    </div>
  </div>
</form>

<script>
const APP_URL = '<?=APP_URL?>';
const SYM     = '<?=e(setting("currency_symbol","Rs."))?>';
let items     = [];
let searchTimer;

// ── Pre-load existing items ──────────────────────────────────
<?php foreach($items as $existing): ?>
items.push({
  id:      <?=(int)$existing['product_id']?>,
  name:    <?=json_encode($existing['product_name'])?>,
  code:    <?=json_encode($existing['product_code'])?>,
  qty:     <?=(float)$existing['quantity']?>,
  cost:    <?=(float)$existing['cost_price']?>,
  disc:    <?=(float)$existing['discount']?>,
  tax_pct: <?=(float)$existing['tax'] > 0 && (float)$existing['total'] > 0
              ? round((float)$existing['tax']/(float)$existing['total']*100,2) : 0 ?>,
});
<?php endforeach; ?>
renderItems();

// ── Product Search ───────────────────────────────────────────
const searchInput   = document.getElementById('prod-search');
const searchResults = document.getElementById('prod-results');
const clearBtn      = document.getElementById('clear-search');

searchInput.addEventListener('input', function(){
  clearTimeout(searchTimer);
  const q = this.value.trim();
  clearBtn.style.display = q ? 'block' : 'none';
  if(!q){searchResults.style.display='none';return;}
  searchTimer = setTimeout(()=>searchProducts(q), 220);
});
document.addEventListener('click', e=>{
  if(!e.target.closest('#prod-search')&&!e.target.closest('#prod-results'))
    searchResults.style.display='none';
});
searchInput.addEventListener('keydown', e=>{if(e.key==='Escape')clearSearch();});

function clearSearch(){
  searchInput.value='';searchResults.style.display='none';
  clearBtn.style.display='none';searchInput.focus();
}

async function searchProducts(q){
  const res  = await fetch(APP_URL+'/products/search?q='+encodeURIComponent(q));
  const data = await res.json();
  if(!data.length){
    searchResults.innerHTML='<div class="p-3 text-muted small text-center">No products found.</div>';
    searchResults.style.display='block';return;
  }
  searchResults.innerHTML = data.map(p=>`
    <div class="prod-res-item" onclick='addItem(${JSON.stringify(p).replace(/'/g,"&#39;")})'>
      <div>
        <div class="fw-semibold small">${esc(p.product_name)}</div>
        <div class="text-muted" style="font-size:.72rem">${esc(p.product_code)}</div>
      </div>
      <div class="text-end">
        <div class="text-primary fw-semibold small">Cost: ${SYM} ${parseFloat(p.cost_price).toFixed(2)}</div>
        <div class="text-muted" style="font-size:.7rem">Stock: ${p.current_stock}</div>
      </div>
    </div>`).join('');
  searchResults.style.display='block';
}

function addItem(p){
  clearSearch();
  const ex = items.find(i=>i.id==p.id);
  if(ex){ex.qty++;renderItems();return;}
  items.push({id:p.id,name:p.product_name,code:p.product_code,
    qty:1,cost:parseFloat(p.cost_price)||0,disc:0,tax_pct:parseFloat(p.tax_percent)||0});
  renderItems();
}

function renderItems(){
  const tb = document.getElementById('items-body');
  const badge = document.getElementById('item-count-badge');
  badge.textContent = items.length + ' items';
  if(!items.length){
    tb.innerHTML=`<tr id="empty-row"><td colspan="8" class="text-center text-muted py-4">
      <i class="bi bi-box-seam fs-2 d-block mb-1 opacity-25"></i>
      No items — use the search above to add</td></tr>`;
    recalc();return;
  }
  tb.innerHTML = items.map((it,i)=>`
    <tr>
      <td class="ps-2 text-muted">${i+1}</td>
      <td>
        <div class="fw-semibold small">${esc(it.name)}</div>
        <div class="text-muted" style="font-size:.65rem">${esc(it.code)}</div>
      </td>
      <td><input type="number" class="form-control form-control-sm text-center"
          value="${it.qty}" min="0.01" step="0.01"
          onchange="items[${i}].qty=parseFloat(this.value)||1;renderItems()"></td>
      <td><input type="number" class="form-control form-control-sm"
          value="${it.cost.toFixed(2)}" min="0" step="0.01"
          onchange="items[${i}].cost=parseFloat(this.value)||0;renderItems()"></td>
      <td><input type="number" class="form-control form-control-sm"
          value="${it.disc.toFixed(2)}" min="0" step="0.01"
          onchange="items[${i}].disc=parseFloat(this.value)||0;renderItems()"></td>
      <td><input type="number" class="form-control form-control-sm text-center"
          value="${it.tax_pct.toFixed(1)}" min="0" step="0.1"
          onchange="items[${i}].tax_pct=parseFloat(this.value)||0;renderItems()"></td>
      <td class="text-end fw-semibold">${SYM} ${lineTotal(it).toFixed(2)}</td>
      <td><button type="button" class="btn btn-sm btn-outline-danger py-0 px-1"
          onclick="items.splice(${i},1);renderItems()">
          <i class="bi bi-x"></i></button></td>
    </tr>`).join('');
  recalc();
}

function lineTotal(it){ return (it.qty*it.cost)-(it.disc||0); }

function recalc(){
  const disc = parseFloat(document.getElementById('t-disc-input').value)||0;
  let sub=0, tax=0;
  items.forEach(it=>{
    const line = lineTotal(it);
    sub += line;
    tax += line*(it.tax_pct/100);
  });
  const total = sub - disc + tax;
  document.getElementById('t-sub').textContent   = SYM+sub.toFixed(2);
  document.getElementById('t-disc').textContent  = '-'+SYM+disc.toFixed(2);
  document.getElementById('t-tax').textContent   = SYM+tax.toFixed(2);
  document.getElementById('t-total').textContent = SYM+total.toFixed(2);
}

function submitEdit(e){
  if(!items.length){ e.preventDefault(); alert('Please add at least one product.'); return false; }
  document.getElementById('items_json').value = JSON.stringify(items);
  return true;
}

function esc(s){
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
</script>