<?php
global $db, $config;
$basePath = rtrim(($config['app']['base_path'] ?? ''), '/');

$houseId = (int)($_GET['house_bl_id'] ?? 0);
if ($houseId <= 0) { echo "<div class='glass rounded-3xl p-5'>Missing HBL.</div>"; return; }

// load HBL header info for context
$h = $db->prepare("
  SELECT
    h.id,
    h.hbl_no,
    h.master_bl_id,
    h.chargeable_units,
    h.goods_description,
    c.name AS consignee_name,
    m.mbl_no
  FROM house_bls h
  JOIN master_bls m ON m.id = h.master_bl_id
  LEFT JOIN customers c ON c.id = h.consignee_customer_id
  WHERE h.id = ?
");
$h->execute([$houseId]);
$hbl = $h->fetch();

if (!$hbl) {
  echo "<div class='glass rounded-3xl p-5'>HBL not found.</div>";
  return;
}

$charges = $db->query("
  SELECT id, name, basis, default_rate
  FROM charge_types
  ORDER BY id ASC
")->fetchAll();

function estimate_qty_for_basis($basis, $chargeableUnits) {
  return ($basis === 'PER_UNIT_WM') ? (float)$chargeableUnits : 1.0;
}
?>

<div class="flex items-start justify-between mb-4 gap-3">
  <div>
    <h1 class="text-2xl font-semibold">Select Invoice Charges</h1>
    <div class="text-white/80 text-sm">
      Prepare invoice lines for this HBL. Charge names and rates edited here affect this invoice only.
    </div>
  </div>

  <div class="flex gap-2">
    <a class="px-4 py-2 rounded-2xl bg-white/15 hover:bg-white/20 transition"
       href="<?= h($basePath) ?>/hbl" data-nav>Back</a>
  </div>
</div>

<!-- Top context row -->
<div class="glass rounded-3xl p-4 mb-4">
  <div class="grid md:grid-cols-4 gap-3 text-sm">
    <div class="rounded-2xl bg-white/10 border border-white/10 px-4 py-3">
      <div class="text-white/60 text-xs uppercase tracking-wide">HBL No</div>
      <div class="font-semibold mt-1"><?= h($hbl['hbl_no'] ?? '—') ?></div>
    </div>

    <div class="rounded-2xl bg-white/10 border border-white/10 px-4 py-3">
      <div class="text-white/60 text-xs uppercase tracking-wide">MBL No</div>
      <div class="font-semibold mt-1"><?= h($hbl['mbl_no'] ?? '—') ?></div>
    </div>

    <div class="rounded-2xl bg-white/10 border border-white/10 px-4 py-3">
      <div class="text-white/60 text-xs uppercase tracking-wide">Consignee</div>
      <div class="font-semibold mt-1"><?= h($hbl['consignee_name'] ?? '—') ?></div>
    </div>

    <div class="rounded-2xl bg-white/10 border border-white/10 px-4 py-3">
      <div class="text-white/60 text-xs uppercase tracking-wide">W/M Units</div>
      <div class="font-semibold mt-1"><?= h($hbl['chargeable_units'] ?? 0) ?></div>
    </div>
  </div>

  <div class="mt-3 rounded-2xl bg-white/10 border border-white/10 px-4 py-3">
    <div class="text-white/60 text-xs uppercase tracking-wide">Goods Description</div>
    <div class="font-semibold mt-1 whitespace-pre-line">
      <?= h(trim((string)($hbl['goods_description'] ?? '')) !== '' ? $hbl['goods_description'] : '—') ?>
    </div>
  </div>
</div>

<form class="glass rounded-3xl p-6" id="chargeSelectForm" data-house-id="<?= (int)$houseId ?>">
  <input type="hidden" name="house_bl_id" value="<?= (int)$houseId ?>">

  <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4">
    <div class="text-sm text-white/80">
      Tick the charges to include. You may edit the charge name, rate, and quantity before posting.
    </div>

    <div class="flex gap-2">
      <button type="button"
              class="px-3 py-2 rounded-2xl bg-white/15 hover:bg-white/20 transition"
              id="checkAllBtn">Check all</button>

      <button type="button"
              class="px-3 py-2 rounded-2xl bg-white/15 hover:bg-white/20 transition"
              id="uncheckAllBtn">Uncheck all</button>
    </div>
  </div>

  <div class="overflow-x-auto">
    <table class="w-full text-sm min-w-[1100px]">
      <thead>
        <tr class="text-left border-b border-white/15">
          <th class="py-2 pr-3 w-12">Use</th>
          <th class="py-2 pr-3">Charge Name</th>
          <th class="py-2 pr-3">Basis</th>
          <th class="py-2 pr-3 text-right">Rate</th>
          <th class="py-2 pr-3 text-right">Qty</th>
          <th class="py-2 text-right">Amount</th>
        </tr>
      </thead>

      <tbody>
        <?php foreach ($charges as $i => $ch):
          $basis = (string)$ch['basis'];
          $qty   = estimate_qty_for_basis($basis, $hbl['chargeable_units'] ?? 0);
          $rate  = (float)$ch['default_rate'];
          $amt   = round($qty * $rate, 2);
        ?>
          <tr class="border-b border-white/10 charge-row">
            <td class="py-2 pr-3 align-top">
              <input type="checkbox"
                     name="lines[<?= $i ?>][use]"
                     value="1"
                     checked
                     class="line-use mt-3 w-4 h-4 accent-orange-500" />

              <input type="hidden" name="lines[<?= $i ?>][charge_type_id]" value="<?= (int)$ch['id'] ?>">
              <input type="hidden" name="lines[<?= $i ?>][basis]" value="<?= h($basis) ?>">
            </td>

            <td class="py-2 pr-3 align-top">
              <input type="text"
                     name="lines[<?= $i ?>][name]"
                     value="<?= h($ch['name']) ?>"
                     class="line-name mt-1 w-full px-4 py-3 rounded-2xl border border-white/15 bg-white/10 text-white placeholder:text-white/40 outline-none focus:border-orange-300" />
            </td>

            <td class="py-2 pr-3 align-top">
              <div class="mt-3 text-white/85 whitespace-nowrap"><?= h($basis) ?></div>
            </td>

            <td class="py-2 pr-3 align-top text-right">
              <input type="number"
                     step="0.01"
                     min="0"
                     name="lines[<?= $i ?>][rate]"
                     value="<?= h(number_format($rate, 2, '.', '')) ?>"
                     class="line-rate mt-1 w-32 ml-auto px-4 py-3 rounded-2xl border border-white/15 bg-white/10 text-white text-right outline-none focus:border-orange-300" />
            </td>

            <td class="py-2 pr-3 align-top text-right">
              <input type="number"
                     step="0.001"
                     min="0"
                     name="lines[<?= $i ?>][qty]"
                     value="<?= h(number_format($qty, 3, '.', '')) ?>"
                     class="line-qty mt-1 w-28 ml-auto px-4 py-3 rounded-2xl border border-white/15 bg-white/10 text-white text-right outline-none focus:border-orange-300" />
            </td>

            <td class="py-2 align-top text-right">
              <div class="line-amount mt-3 font-semibold text-orange-200"><?= number_format($amt, 2) ?></div>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>

      <tfoot>
        <tr>
          <td colspan="5" class="pt-4 text-right font-semibold text-white/80">Selected Total</td>
          <td class="pt-4 text-right font-bold text-lg text-orange-200" id="grandTotal">0.00</td>
        </tr>
      </tfoot>
    </table>
  </div>

  <div class="flex items-center justify-end mt-5 gap-2">
    <button type="submit"
            class="px-5 py-3 rounded-2xl bg-white text-wsc-700 font-semibold hover:bg-white/90 transition">
      Post & Generate Invoice
    </button>
  </div>

  <div class="text-xs text-white/70 mt-3">
    Note: Edited names, quantities and rates are applied to this invoice only. Master charge types remain unchanged.
  </div>
</form>

<script>
(function(){
  const form = document.getElementById('chargeSelectForm');
  const checkAllBtn = document.getElementById('checkAllBtn');
  const uncheckAllBtn = document.getElementById('uncheckAllBtn');
  const grandTotalEl = document.getElementById('grandTotal');

  function num(v){
    const n = parseFloat(v);
    return isNaN(n) ? 0 : n;
  }

  function recalcRow(row){
    const use = row.querySelector('.line-use')?.checked;
    const rate = num(row.querySelector('.line-rate')?.value);
    const qty = num(row.querySelector('.line-qty')?.value);
    const amount = use ? (rate * qty) : 0;

    const amountEl = row.querySelector('.line-amount');
    if (amountEl) amountEl.textContent = amount.toFixed(2);

    row.classList.toggle('opacity-50', !use);
    return amount;
  }

  function recalcAll(){
    let total = 0;

    form.querySelectorAll('.charge-row').forEach(row => {
      total += recalcRow(row);
    });

    grandTotalEl.textContent = total.toFixed(2);
  }

  function setAll(state){
    form.querySelectorAll('.line-use').forEach(cb => cb.checked = state);
    recalcAll();
  }

  checkAllBtn.addEventListener('click', () => setAll(true));
  uncheckAllBtn.addEventListener('click', () => setAll(false));

  form.addEventListener('input', function(e){
    if (
      e.target.classList.contains('line-rate') ||
      e.target.classList.contains('line-qty') ||
      e.target.classList.contains('line-use')
    ) {
      const row = e.target.closest('.charge-row');
      if (row) recalcRow(row);

      let total = 0;
      form.querySelectorAll('.charge-row').forEach(r => total += recalcRow(r));
      grandTotalEl.textContent = total.toFixed(2);
    }
  });

  form.addEventListener('submit', async (e) => {
    e.preventDefault();

    const selectedRows = Array.from(form.querySelectorAll('.line-use')).filter(cb => cb.checked);
    if (!selectedRows.length) {
      alert('Select at least one charge.');
      return;
    }

    for (const row of form.querySelectorAll('.charge-row')) {
      const checked = row.querySelector('.line-use')?.checked;
      if (!checked) continue;

      const name = (row.querySelector('.line-name')?.value || '').trim();
      const rate = num(row.querySelector('.line-rate')?.value);
      const qty = num(row.querySelector('.line-qty')?.value);

      if (!name) {
        alert('Every selected charge must have a name.');
        row.querySelector('.line-name')?.focus();
        return;
      }

      if (rate < 0) {
        alert('Rate cannot be negative.');
        row.querySelector('.line-rate')?.focus();
        return;
      }

      if (qty <= 0) {
        alert('Quantity must be greater than zero for selected charges.');
        row.querySelector('.line-qty')?.focus();
        return;
      }
    }

    const fd = new FormData(form);

    try {
      if (window.lock) window.lock();

      const res = await fetch('<?= h($basePath) ?>/api/invoice/create-selected', {
        method: 'POST',
        body: fd,
        headers: {'X-Requested-With':'XMLHttpRequest'}
      });

      const data = await res.json().catch(() => ({ok:false,msg:'Server error'}));
      if (!data.ok) {
        alert(data.msg || 'Failed');
        return;
      }

      const url = data.url || data.redirect;
      if (!url) {
        alert('Invoice URL missing');
        return;
      }

      window.open(url, '_blank', 'noopener');

      if (window.loadPartial) {
        window.loadPartial('<?= h($basePath) ?>/hbl?master_bl_id=<?= (int)($hbl['master_bl_id'] ?? 0) ?>', true);
      }
    } finally {
      if (window.unlock) window.unlock();
    }
  });

  recalcAll();
})();
</script>