<?php
require 'header.php';
require 'db.php';
require 'unit_converters.php';

$msg = '';

/* Fetch available items grouped by category for the select */
$items_by_cat = [];
$res = $conn->query("SELECT id, sku, name, category, quantity, weight_g FROM stock ORDER BY category, name");
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $items_by_cat[$row['category']][] = $row;
    }
}

/* POST handling: remove from stock table after logging */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['id'] ?? 0);
    $reason = $conn->real_escape_string($_POST['reason'] ?? 'Manual out');
    $grams_input = floatval($_POST['out_grams'] ?? 0.0);

    // Determine out weight in grams
    if ($grams_input > 0) {
        $out_g = $grams_input;
    } else {
        $v = intval($_POST['out_vori'] ?? 0);
        $a = intval($_POST['out_ana'] ?? 0);
        $r = intval($_POST['out_roti'] ?? 0);
        $p = floatval($_POST['out_point'] ?? 0);
        $out_g = unitsToGrams($v, $a, $r, $p);
    }
    $out_g = max(0.0, $out_g);

    if ($id <= 0) {
        $msg = 'Please select an item first.';
    } else {
        $item = $conn->query("SELECT * FROM stock WHERE id=$id")->fetch_assoc();
        if (!$item) {
            $msg = 'Item not found in stock.';
        } else {
            $cur_g = floatval($item['weight_g']);
            $final_out = $out_g > 0 ? $out_g : $cur_g; // if no out_g, remove full weight

            // Log in stock_out_records
            $stmt = $conn->prepare('INSERT INTO stock_out_records (stock_id, out_weight_g, reason) VALUES (?,?,?)');
            if ($stmt === false) {
                $msg = 'Prepare failed: ' . $conn->error;
            } else {
                $stmt->bind_param('ids', $id, $final_out, $reason);
                if ($stmt->execute()) {
                    // Delete the item from stock completely
                    $conn->query("DELETE FROM stock WHERE id = $id");
                    $msg = 'Item "' . htmlspecialchars($item['name']) . '" has been removed from stock (' . number_format($final_out,4) . ' g).';
                } else {
                    $msg = 'Insert failed: ' . $stmt->error;
                }
                $stmt->close();
            }
        }
    }
}

/* Load item if pre-selected by ID */
$selected_item = null;
if (isset($_GET['id'])) {
    $selected_item = $conn->query('SELECT * FROM stock WHERE id = ' . (int)$_GET['id'])->fetch_assoc();
}
?>

<!-- Modern standard UI styles for Stock Out -->
<style>
:root{
  --bg:#f6f8fb;
  --card:#ffffff;
  --muted:#6b7280;
  --accent:#ef4444; /* danger/red for removal */
  --accent-hover:#dc2626;
  --success:#16a34a;
  --radius:12px;
  --glass: rgba(2,6,23,0.04);
  --shadow: 0 10px 30px rgba(2,6,23,0.06);
}
*{box-sizing:border-box;font-family: Inter, system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial;}
body{background:var(--bg);color:#0f172a}
.container{max-width:1000px;margin:28px auto;padding:18px}
.header{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px;gap:12px}
.title{font-size:1.2rem;font-weight:800}
.subtitle{color:var(--muted);font-size:0.95rem}
.card{background:var(--card);border-radius:var(--radius);box-shadow:var(--shadow);padding:18px;border:1px solid var(--glass)}
.grid{display:grid;grid-template-columns:1fr 360px;gap:18px}
.form-group{display:flex;flex-direction:column;margin-bottom:12px}
label{font-weight:700;color:#0f172a;margin-bottom:6px}
select, input[type=number], input[type=text]{
  padding:10px 12px;border-radius:10px;border:1px solid #e6eef8;background:transparent;font-size:0.98rem;
}
.small{max-width:160px}
.row{display:flex;gap:12px;align-items:flex-start}
.btn{display:inline-flex;gap:8px;align-items:center;padding:10px 14px;border-radius:10px;border:none;cursor:pointer;font-weight:700}
.btn-danger{background:linear-gradient(90deg,var(--accent),var(--accent-hover));color:white}
.btn-outline{background:transparent;border:1px solid #e6eef8;color:var(--muted);font-weight:700}
.hint{color:var(--muted);font-size:0.9rem}
.preview-title{font-weight:800;font-size:1rem}
.preview-sub{color:var(--muted);font-size:0.92rem;margin-top:4px}
.kv{color:var(--muted);font-size:0.95rem}
.chips{display:flex;gap:8px;margin-top:8px}
.chip{background:#fff5f5;padding:6px 10px;border-radius:999px;color:#7f1d1d;font-weight:700}
.msg{padding:12px;border-radius:10px;margin-bottom:12px}
.msg-success{background:#ecfdf5;color:#064e3b}
.msg-error{background:#fff1f2;color:#7f1d1d}
.actions{display:flex;gap:8px;align-items:center;margin-top:12px}
.footer-note{color:var(--muted);font-size:0.88rem;margin-top:12px}
@media(max-width:900px){.grid{grid-template-columns:1fr}.small{max-width:120px}}
</style>

<div class="container">
  <div class="header">
    <div>
      <div class="title">Manual Stock Out — Remove Item</div>
      <div class="subtitle">আইটেমটি স্টক থেকে ম্যানুয়ালি সরান (রেকর্ড তৈরি হবে)</div>
    </div>
    <div class="hint">Tip: নির্দিষ্ট ওজন দিন বা খালি রেখে পুরো আইটেমই সরিয়ে দিন</div>
  </div>

  <?php if($msg): ?>
    <div class="msg <?php echo (strpos($msg,'not')!==false || strpos($msg,'failed')!==false)?'msg-error':'msg-success' ?>">
      <?php echo htmlspecialchars($msg) ?>
    </div>
  <?php endif; ?>

  <div class="grid">
    <div class="card">
      <form method="post" id="outForm">
        <div class="form-group">
          <label for="select_item">Choose item to remove</label>
          <select name="id" id="select_item" required>
            <option value="">-- Select item --</option>
            <?php
            $order = ['gold'=>'Gold','silver'=>'Rupa','diamond'=>'Hira'];
            foreach ($order as $cat_key => $cat_label):
                if (empty($items_by_cat[$cat_key])) continue;
            ?>
              <optgroup label="<?php echo htmlspecialchars($cat_label) ?>">
                <?php foreach ($items_by_cat[$cat_key] as $it):
                    $u = gramsToUnits($it['weight_g']);
                    $label = htmlspecialchars($it['name'].' ('.$it['sku'].') - qty:'.intval($it['quantity']).' - '.$u['vori'].'ভরি '.$u['ana'].'আনা ('.$u['grams'].' g)');
                ?>
                  <option value="<?php echo $it['id'] ?>"
                    data-weight="<?php echo htmlspecialchars($it['weight_g']) ?>"
                    data-qty="<?php echo htmlspecialchars($it['quantity']) ?>"
                    data-name="<?php echo htmlspecialchars($it['name']) ?>"
                    <?php if (isset($selected_item['id']) && $selected_item['id']==$it['id']) echo 'selected'; ?>>
                    <?php echo $label ?>
                  </option>
                <?php endforeach; ?>
              </optgroup>
            <?php endforeach; ?>
          </select>
        </div>

        <div id="selected_summary" class="form-group kv">
          <?php
          if ($selected_item) {
              $u = gramsToUnits($selected_item['weight_g'] ?? 0);
              echo '<strong>Selected:</strong> '.htmlspecialchars($selected_item['name']).' — qty:'.intval($selected_item['quantity']).' — '.$u['vori'].' ভরি '.$u['ana'].' আনা ('.$u['grams'].' g)';
          } else {
              echo '<em>No item selected</em>';
          }
          ?>
        </div>

        <div class="row">
          <div style="flex:1" class="form-group">
            <label>Out weight (grams)</label>
            <input name="out_grams" id="out_grams" type="number" step="0.0001" class="small" placeholder="0.0000">
            <div class="hint">অথবা নীচের ইউনিট ব্যবহার করুন</div>
          </div>
          <div style="width:12px"></div>
          <div style="flex:1" class="form-group">
            <label>Reason</label>
            <input name="reason" id="reason" type="text" value="Removed from stock">
            <div class="hint">কারণ লিখুন (ডিফল্ট: Removed from stock)</div>
          </div>
        </div>

        <p style="margin:8px 0;font-weight:700">OR units:</p>
        <div style="display:flex;gap:10px;flex-wrap:wrap">
          <div style="width:110px" class="form-group">
            <label>ভরি</label>
            <input name="out_vori" id="out_vori" type="number" min="0" class="small">
          </div>
          <div style="width:110px" class="form-group">
            <label>আনা</label>
            <input name="out_ana" id="out_ana" type="number" min="0" class="small">
          </div>
          <div style="width:110px" class="form-group">
            <label>রটি</label>
            <input name="out_roti" id="out_roti" type="number" min="0" class="small">
          </div>
          <div style="width:130px" class="form-group">
            <label>পয়েন্ট</label>
            <input name="out_point" id="out_point" type="number" step="0.01" min="0" class="small">
          </div>
        </div>

        <div class="actions">
          <button type="submit" class="btn btn-danger" id="removeBtn">Remove from Stock</button>
          <button type="button" class="btn btn-outline" id="fill_half">Fill 50%</button>
          <button type="button" class="btn btn-outline" id="fill_full">Fill max</button>
          <div style="margin-left:auto" class="hint">If out weight is empty, the full item's weight will be used.</div>
        </div>

      </form>
    </div>

    <div class="card">
      <div>
        <div class="preview-title" id="preview_name">No item selected</div>
        <div class="preview-sub" id="preview_meta">Choose an item to view details</div>

        <div class="chips" style="margin-top:12px">
          <div class="chip" id="chip_qty">Qty: —</div>
          <div class="chip" id="chip_weight">Weight: —</div>
        </div>

        <hr style="margin:14px 0;border:none;border-top:1px solid #f1f5f9">

        <div style="margin-top:8px">
          <div style="font-weight:700">Computed out grams</div>
          <div id="preview_grams" class="kv">0.0000 g</div>
        </div>

        <div class="footer-note">প্রয়োজন হলে full removal করবে — সাবমিট করার আগে নিশ্চিত হওয়ার জন্য confirmation আসবে।</div>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const GRAM_PER_VORI = 11.664;

  const sel = document.getElementById('select_item');
  const summary = document.getElementById('selected_summary');
  const outGrams = document.getElementById('out_grams');
  const v = document.getElementById('out_vori');
  const a = document.getElementById('out_ana');
  const r = document.getElementById('out_roti');
  const p = document.getElementById('out_point');
  const previewName = document.getElementById('preview_name');
  const previewMeta = document.getElementById('preview_meta');
  const chipQty = document.getElementById('chip_qty');
  const chipWeight = document.getElementById('chip_weight');
  const previewGrams = document.getElementById('preview_grams');
  const fillHalf = document.getElementById('fill_half');
  const fillFull = document.getElementById('fill_full');
  const form = document.getElementById('outForm');

  function gramsToReadable(g) {
    g = parseFloat(g) || 0;
    if (g <= 0) return '0 g';
    let totalVori = g / GRAM_PER_VORI;
    let vori = Math.floor(totalVori);
    let remVori = totalVori - vori;
    let totalAna = remVori * 16.0;
    let ana = Math.floor(totalAna);
    let remAna = totalAna - ana;
    let totalRoti = remAna * 6.0;
    let roti = Math.floor(totalRoti);
    let remRoti = totalRoti - roti;
    let totalPoint = Math.round(remRoti * 10 * 100)/100;
    return vori + ' ভরি ' + ana + ' আনা ' + roti + ' রটি ' + totalPoint + ' পয়েন্ট (' + g.toFixed(4) + ' g)';
  }

  function unitsToGrams(){
    const vv = parseFloat(v.value) || 0;
    const aa = parseFloat(a.value) || 0;
    const rr = parseFloat(r.value) || 0;
    const pp = parseFloat(p.value) || 0;
    const totalVori = vv + (aa/16) + (rr/(16*6)) + (pp/(16*6*10));
    const grams = totalVori * GRAM_PER_VORI;
    return +(grams.toFixed(4));
  }

  function updateSummary() {
    const opt = sel.options[sel.selectedIndex];
    if (!opt || !opt.value) {
      summary.innerHTML = '<em>No item selected</em>';
      previewName.innerText = 'No item selected';
      previewMeta.innerText = 'Choose an item to view details';
      chipQty.innerText = 'Qty: —';
      chipWeight.innerText = 'Weight: —';
      return;
    }
    const name = opt.getAttribute('data-name') || '—';
    const qty = opt.getAttribute('data-qty') || '0';
    const weight = parseFloat(opt.getAttribute('data-weight') || '0');
    summary.innerHTML = '<strong>Selected:</strong> ' + name + ' — qty:' + qty + ' — ' + gramsToReadable(weight);
    previewName.innerText = name;
    previewMeta.innerText = 'Available: ' + qty + ' pieces';
    chipQty.innerText = 'Qty: ' + qty;
    chipWeight.innerText = 'Weight: ' + weight.toFixed(4) + ' g';
  }

  function updateComputedPreview(){
    const gramsFromUnits = unitsToGrams();
    const gramsField = parseFloat(outGrams.value) || 0;
    const computed = gramsField > 0 ? gramsField : (gramsFromUnits > 0 ? gramsFromUnits : (sel.options[sel.selectedIndex] ? parseFloat(sel.options[sel.selectedIndex].getAttribute('data-weight')||0) : 0));
    previewGrams.innerText = computed.toFixed(4) + ' g';
  }

  sel.addEventListener('change', function(){
    updateSummary();
    updateComputedPreview();
  });

  [v,a,r,p].forEach(el => el.addEventListener('input', function(){
    const u = unitsToGrams();
    if (u > 0) outGrams.value = ''; // keep empty to show units-only until user fills grams explicitly
    updateComputedPreview();
  }));

  outGrams.addEventListener('input', updateComputedPreview);

  fillHalf.addEventListener('click', function(){
    const opt = sel.options[sel.selectedIndex];
    if (!opt || !opt.value) return alert('Select an item first');
    const weight = parseFloat(opt.getAttribute('data-weight') || '0');
    const half = +(weight/2).toFixed(4);
    outGrams.value = half;
    updateComputedPreview();
  });

  fillFull.addEventListener('click', function(){
    const opt = sel.options[sel.selectedIndex];
    if (!opt || !opt.value) return alert('Select an item first');
    const weight = parseFloat(opt.getAttribute('data-weight') || '0');
    outGrams.value = weight.toFixed(4);
    updateComputedPreview();
  });

  // confirm before actual submit
  form.addEventListener('submit', function(e){
    e.preventDefault();
    const opt = sel.options[sel.selectedIndex];
    if (!opt || !opt.value) { alert('Please select an item'); return; }
    const name = opt.getAttribute('data-name') || '—';
    const availableWeight = parseFloat(opt.getAttribute('data-weight') || '0');
    const gramsFromUnits = unitsToGrams();
    const gramsField = parseFloat(outGrams.value) || 0;
    const final = gramsField > 0 ? gramsField : (gramsFromUnits > 0 ? gramsFromUnits : availableWeight);
    const confirmMsg = 'Confirm removal:\\n\\nItem: ' + name + '\\nRemove weight: ' + final.toFixed(4) + ' g\\n\\nThis will delete the stock row. Proceed?';
    if (confirm(confirmMsg)) {
      // real submit
      form.submit();
    }
  });

  // init
  updateSummary();
  updateComputedPreview();
})();
</script>

<?php require 'footer.php'; ?>
