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

$msg = '';
// fetch available items grouped by category (no price)
$items_by_cat = [];
$res = $conn->query("SELECT id, sku, name, category, quantity, weight_g FROM stock WHERE (weight_g > 0 OR quantity > 0) ORDER BY category, name");
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $items_by_cat[$row['category']][] = $row;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['id'] ?? 0);
    // default qty 0 so weight-only sales are allowed
    $qty = max(0, intval($_POST['qty'] ?? 0));
    $grams_input = floatval($_POST['sell_grams'] ?? 0);

    if ($grams_input > 0) {
        $sell_g = $grams_input;
    } else {
        $v = intval($_POST['sell_vori'] ?? 0);
        $a = intval($_POST['sell_ana'] ?? 0);
        $r = intval($_POST['sell_roti'] ?? 0);
        $p = floatval($_POST['sell_point'] ?? 0);
        $sell_g = unitsToGrams($v, $a, $r, $p);
    }

    $sell_g = max(0.0, floatval($sell_g));

    // fetch item safely
    $stmt = $conn->prepare('SELECT id, name, quantity, weight_g FROM stock WHERE id = ? LIMIT 1');
    if ($stmt === false) {
        $msg = 'Prepare failed: ' . $conn->error;
    } else {
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $res2 = $stmt->get_result();
        $row = $res2->fetch_assoc();
        $stmt->close();

        if (!$row) {
            $msg = 'Item not found.';
        } else {
            $available_qty = intval($row['quantity']);
            // ensure we treat NULL/empty weight as 0.0
            $available_weight = is_null($row['weight_g']) ? 0.0 : floatval($row['weight_g']);

            /*
             * New logic:
             * - Only enforce weight check when DB reports a positive available weight.
             *   This prevents "Not enough weight... Available: 0 g" when weight_g is 0 but user wants a weight-only sale (qty == 0).
             * - Still enforce piece/qty check whenever qty > 0.
             */
            if ($sell_g > 0 && $available_weight > 0 && $sell_g > $available_weight) {
                $msg = 'Not enough weight in stock. Available: ' . round($available_weight,4) . ' g';
            } elseif ($qty > 0 && $qty > $available_qty) {
                $msg = 'Not enough pieces in stock. Available qty: ' . $available_qty;
            } else {
                // record sale without any price
                $conn->begin_transaction();
                try {
                    $ins = $conn->prepare('INSERT INTO sales (stock_id, qty, sold_weight_g) VALUES (?,?,?)');
                    if ($ins === false) throw new Exception('Prepare failed (insert sales): ' . $conn->error);
                    $ins->bind_param('iid', $id, $qty, $sell_g);
                    if (!$ins->execute()) throw new Exception('Execute failed (insert sales): ' . $ins->error);
                    $ins->close();

                    $upd = $conn->prepare('UPDATE stock SET weight_g = GREATEST(0, COALESCE(weight_g,0) - ?), quantity = GREATEST(0, quantity - ?) WHERE id = ?');
                    if ($upd === false) throw new Exception('Prepare failed (update stock): ' . $conn->error);
                    // bind as double, int, int
                    $upd->bind_param('dii', $sell_g, $qty, $id);
                    if (!$upd->execute()) throw new Exception('Execute failed (update stock): ' . $upd->error);
                    $upd->close();

                    $conn->commit();
                    $msg = 'Sale recorded successfully (no price).';
                } catch (Exception $e) {
                    $conn->rollback();
                    $msg = 'Transaction failed: ' . $e->getMessage();
                }
            }
        }
    }
}

// optional: if GET id provided, select that item to show initial summary
$selected_item = null;
if (isset($_GET['id'])) {
    $selected_item = $conn->query('SELECT * FROM stock WHERE id = ' . (int)$_GET['id'])->fetch_assoc();
}
?>

<!-- Standard modern UI styles -->
<style>
:root{
  --bg:#f6f8fb;
  --card:#ffffff;
  --muted:#64748b;
  --accent:#2563eb; /* blue */
  --accent-2:#06b6d4; /* teal */
  --danger:#ef4444;
  --radius:12px;
  --glass: rgba(15,23,42,0.04);
}
*{box-sizing:border-box;font-family: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial}
body{background:var(--bg);color:#0f172a}
.container{max-width:1100px;margin:28px auto;padding:20px}
.header{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px}
.h-title{font-size:1.25rem;font-weight:700}
.h-sub{color:var(--muted);font-size:0.95rem}
.card{background:var(--card);border-radius:var(--radius);box-shadow:0 8px 20px rgba(2,6,23,0.06);padding:18px;border:1px solid var(--glass)}
.grid{display:grid;grid-template-columns:1fr 360px;gap:18px}
.form-row{display:flex;gap:12px;align-items:flex-start}
.field{display:flex;flex-direction:column;margin-bottom:12px}
label{font-weight:600;color:#0f172a;margin-bottom:6px}
input[type=number], select{padding:10px 12px;border-radius:10px;border:1px solid #e6eef8;background:transparent}
.small{max-width:160px}
.btn{display:inline-flex;align-items:center;gap:8px;padding:10px 14px;border-radius:10px;border:none;cursor:pointer;font-weight:700}
.btn-primary{background:linear-gradient(90deg,var(--accent),var(--accent-2));color:white}
.btn-outline{background:transparent;border:1px solid #e6eef8;color:var(--accent)}
.hint{color:var(--muted);font-size:0.9rem}
.selected-summary{padding:12px;border-radius:10px;background:#fbfdff;border:1px solid #eef8ff}
.kv{color:var(--muted);font-size:0.95rem}
.chips{display:flex;gap:8px}
.chip{background:#f1f9ff;padding:6px 10px;border-radius:999px;color:#0f172a;font-weight:600}
.msg{padding:12px;border-radius:10px;margin-bottom:12px}
.msg-success{background:#ecfdf5;color:#065f46}
.msg-error{background:#fff1f2;color:#7f1d1d}
.footer-note{color:var(--muted);font-size:0.9rem;margin-top:8px}
@media(max-width:900px){.grid{grid-template-columns:1fr}.small{max-width:120px}}
</style>

<div class="container">
  <div class="header">
    <div>
      <div class="h-title">Sell Item</div>
      <div class="h-sub">Sell by weight (qty = 0) or by pieces (qty &gt; 0)</div>
    </div>
    <div class="hint">Tip: leave <strong>qty</strong> as <em>0</em> to record a weight-only sale</div>
  </div>

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

  <div class="grid">
    <div class="card">
      <form method="post">
        <div class="field">
          <label for="select_item_sell">Select item to sell</label>
          <select name="id" id="select_item_sell" 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 class="form-row">
          <div class="field" style="flex:1">
            <label>Pieces / Qty</label>
            <input name="qty" id="qty_input" type="number" value="0" class="small" min="0">
            <div class="hint">Set &gt;0 when selling pieces. Default 0 (weight-only).</div>
          </div>

          <div style="width:12px"></div>

          <div class="field" style="flex:1">
            <label>Sell by weight (grams)</label>
            <input name="sell_grams" id="sell_grams" type="number" step="0.0001" min="0" placeholder="0.0000">
            <div class="hint">Or use unit inputs below to compute grams.</div>
          </div>
        </div>

        <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:8px">
          <div class="field" style="width:90px">
            <label>ভরি</label>
            <input name="sell_vori" id="sell_vori" type="number" min="0">
          </div>
          <div class="field" style="width:90px">
            <label>আনা</label>
            <input name="sell_ana" id="sell_ana" type="number" min="0">
          </div>
          <div class="field" style="width:90px">
            <label>রটি</label>
            <input name="sell_roti" id="sell_roti" type="number" min="0">
          </div>
          <div class="field" style="width:110px">
            <label>পয়েন্ট</label>
            <input name="sell_point" id="sell_point" type="number" step="0.01" min="0">
          </div>
        </div>

        <div style="display:flex;gap:8px;margin-top:14px;align-items:center">
          <button type="submit" class="btn btn-primary">Record sale</button>
          <button type="button" class="btn btn-outline" id="clear_btn">Clear</button>
          <div style="margin-left:auto" class="hint">DB safety: stock capped at zero automatically.</div>
        </div>

      </form>
    </div>

    <div class="card">
      <div style="display:flex;justify-content:space-between;align-items:center">
        <div>
          <div style="font-weight:700;font-size:1.05rem" id="preview_name">No item selected</div>
          <div class="kv" id="preview_meta">Select an item to see details</div>
        </div>
        <div class="chips" id="preview_chips">
          <div class="chip">Qty: —</div>
          <div class="chip">Weight: —</div>
        </div>
      </div>

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

      <div class="selected-summary" id="selected_summary_sell">
        <?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 style="margin-top:12px">
        <div style="font-weight:700">Computed grams</div>
        <div id="preview_grams" class="kv">0.0000 g</div>
      </div>

      <div style="margin-top:14px;display:flex;gap:8px">
        <button id="fill_half" class="btn btn-outline">Fill 50%</button>
        <button id="fill_full" class="btn btn-outline">Fill max</button>
      </div>

      <div class="footer-note">Want a different color theme or larger buttons? Tell me which style and I'll update.</div>
    </div>
  </div>
</div>

<script>
(function(){
  const sel = document.getElementById('select_item_sell');
  const summary = document.getElementById('selected_summary_sell');
  const sellGrams = document.getElementById('sell_grams');
  const vInput = document.getElementById('sell_vori');
  const aInput = document.getElementById('sell_ana');
  const rInput = document.getElementById('sell_roti');
  const pInput = document.getElementById('sell_point');
  const qtyInput = document.getElementById('qty_input');
  const previewName = document.getElementById('preview_name');
  const previewMeta = document.getElementById('preview_meta');
  const previewChips = document.getElementById('preview_chips');
  const previewGrams = document.getElementById('preview_grams');
  const clearBtn = document.getElementById('clear_btn');
  const fillHalf = document.getElementById('fill_half');
  const fillFull = document.getElementById('fill_full');

  const GRAM_PER_VORI = 11.664;

  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 unitsToGramsClient() {
    const v = parseFloat(vInput.value) || 0;
    const a = parseFloat(aInput.value) || 0;
    const r = parseFloat(rInput.value) || 0;
    const p = parseFloat(pInput.value) || 0;
    const totalVori = v + (a/16) + (r/(16*6)) + (p/(16*6*10));
    const grams = totalVori * GRAM_PER_VORI;
    sellGrams.value = +(grams.toFixed(4));
    previewGrams.innerText = +(grams.toFixed(4)) + ' g';
  }

  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 = 'Select an item to see details';
      previewChips.innerHTML = '<div class="chip">Qty: —</div><div class="chip">Weight: —</div>';
      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 — ' + weight.toFixed(4) + ' g';
    previewChips.innerHTML = '<div class="chip">Qty: ' + qty + '</div><div class="chip">Weight: ' + weight.toFixed(4) + ' g</div>';
  }

  sel.addEventListener('change', function(){
    updateSummary();
    vInput.value=''; aInput.value=''; rInput.value=''; pInput.value='';
    sellGrams.value='';
    // default to 0 pieces so weight-only sales are easy
    qtyInput.value = 0;
    previewGrams.innerText = '0.0000 g';
  });

  [vInput,aInput,rInput,pInput].forEach(inp => inp.addEventListener('input', unitsToGramsClient));

  clearBtn.addEventListener('click', function(){
    vInput.value=''; aInput.value=''; rInput.value=''; pInput.value=''; sellGrams.value=''; qtyInput.value=0; previewGrams.innerText = '0.0000 g';
  });

  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) );
    sellGrams.value = half; previewGrams.innerText = half + ' g';
  });

  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');
    sellGrams.value = +(weight.toFixed(4)); previewGrams.innerText = +(weight.toFixed(4)) + ' g';
  });

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

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