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

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sku = $conn->real_escape_string($_POST['sku'] ?? '');
    $name = $conn->real_escape_string($_POST['name'] ?? '');
    $category = $_POST['category'] ?? 'gold';
    $grams_input = floatval($_POST['grams'] ?? 0);

    if ($grams_input > 0) {
        $add_g = $grams_input;
    } else {
        $v = intval($_POST['vori'] ?? 0);
        $a = intval($_POST['ana'] ?? 0);
        $r = intval($_POST['roti'] ?? 0);
        $p = floatval($_POST['point'] ?? 0);
        $add_g = unitsToGrams($v, $a, $r, $p);
    }

    $qty = intval($_POST['qty'] ?? 1);

    if (!empty($_POST['id'])) {
        $id = intval($_POST['id']);
        // Update existing stock: only quantity, weight_g, and category
        $stmt = $conn->prepare('UPDATE stock SET quantity = quantity + ?, weight_g = weight_g + ?, category=? WHERE id=?');
        if ($stmt === false) {
            $msg = 'Prepare failed: ' . $conn->error;
        } else {
            $stmt->bind_param('idsi', $qty, $add_g, $category, $id);
            if ($stmt->execute()) {
                $msg = 'Stock updated successfully';
            } else {
                $msg = 'Update failed: ' . $stmt->error;
            }
            $stmt->close();
        }
    } else {
        // Insert new stock record without buy/sell prices
        $stmt = $conn->prepare('INSERT INTO stock (sku,name,quantity,weight_g,category) VALUES (?,?,?,?,?)');
        if ($stmt === false) {
            $msg = 'Prepare failed: ' . $conn->error;
        } else {
            $stmt->bind_param('ssids', $sku, $name, $qty, $add_g, $category);
            if ($stmt->execute()) {
                $msg = 'New stock added';
            } else {
                $msg = 'Insert failed: ' . $stmt->error;
            }
            $stmt->close();
        }
    }
}

$editing = null;
if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $editing = $conn->query("SELECT * FROM stock WHERE id=$id")->fetch_assoc();
}
?>

<!-- Modern standard UI styles -->
<style>
:root{
  --bg:#f5f7fb;
  --card:#ffffff;
  --muted:#6b7280;
  --accent:#0ea5e9;
  --accent-2:#2563eb;
  --success:#16a34a;
  --danger:#ef4444;
  --radius:12px;
  --glass: rgba(2,6,23,0.04);
  --shadow: 0 8px 20px rgba(2,6,23,0.06);
}
*{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:1000px;margin:28px auto;padding:18px}
.header{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px}
.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}
input[type=text], input[type=number], select, textarea{
  padding:10px 12px;border-radius:10px;border:1px solid #e6edf6;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-primary{background:linear-gradient(90deg,var(--accent),var(--accent-2));color:white}
.btn-outline{background:transparent;border:1px solid #e6eef8;color:var(--accent-2);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:#f1f9ff;padding:6px 10px;border-radius:999px;color:#073544;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">Stock In</div>
      <div class="subtitle">নতুন স্টক যোগ করুন অথবা বিদ্যমান স্টক আপডেট করুন</div>
    </div>
    <div class="hint">Tip: ওজন দিতে হলে weight/units দাও — pieces দিলে qty ইনক্রিমেন্ট হবে</div>
  </div>

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

  <div class="grid">
    <div class="card">
      <form method="post" id="stockForm">
        <input type="hidden" name="id" value="<?php echo $editing['id'] ?? '' ?>">

        <div class="form-group">
          <label for="sku">SKU</label>
          <input id="sku" name="sku" type="text" required value="<?php echo htmlspecialchars($editing['sku'] ?? '') ?>">
        </div>

        <div class="form-group">
          <label for="name">Name</label>
          <input id="name" name="name" type="text" required value="<?php echo htmlspecialchars($editing['name'] ?? '') ?>">
        </div>

        <div class="form-group">
          <label for="category">Category</label>
          <select id="category" name="category">
            <option value="gold" <?php echo (isset($editing['category']) && $editing['category']=='gold')?'selected':'' ?>>Gold</option>
            <option value="silver" <?php echo (isset($editing['category']) && $editing['category']=='silver')?'selected':'' ?>>Silver</option>
            <option value="diamond" <?php echo (isset($editing['category']) && $editing['category']=='diamond')?'selected':'' ?>>Diamond</option>
          </select>
        </div>

        <div class="row">
          <div style="flex:1" class="form-group">
            <label>Pieces / Qty</label>
            <input name="qty" id="qty_input" type="number" value="<?php echo $editing['quantity'] ?? 1 ?>" class="small" min="0">
            <div class="hint">Pieces দিলে qty বাড়বে।</div>
          </div>

          <div style="flex:1" class="form-group">
            <label>OR Enter weight (grams)</label>
            <input name="grams" id="grams_input" type="number" step="0.0001" value="" class="small" min="0" placeholder="0.0000">
            <div class="hint">গ্রাম এ সরাসরি দিন বা নীচের ইউনিট ব্যবহার করুন</div>
          </div>
        </div>

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

        <div class="actions">
          <button type="submit" class="btn btn-primary">Save</button>
          <button type="button" id="clearBtn" class="btn btn-outline">Clear</button>
          <div style="margin-left:auto" class="hint">DB safety: weight/qty capped at zero by server.</div>
        </div>

      </form>
    </div>

    <div class="card">
      <div>
        <div class="preview-title" id="preview_name">New stock</div>
        <div class="preview-sub" id="preview_sub">Fill fields to preview computed weight</div>

        <div class="chips" style="margin-top:12px">
          <div class="chip" id="chip_qty">Qty: <?php echo intval($editing['quantity'] ?? 0) ?></div>
          <div class="chip" id="chip_weight">Weight: <?php echo isset($editing['weight_g'])?number_format($editing['weight_g'],4):'0.0000' ?> g</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 grams</div>
          <div id="computed_grams" class="kv">0.0000 g</div>
        </div>

        <div style="margin-top:12px;display:flex;gap:8px">
          <button id="fillUnits" class="btn btn-outline">Fill units → grams</button>
          <button id="fillZero" class="btn btn-outline">Set grams = 0</button>
        </div>

        <div class="footer-note">আগে units দিয়ে ভর/আনা দিলে গ্রাম অটোমেটিক হিসাব হবে (1 ভরি = 11.664 g)।</div>
      </div>
    </div>
  </div>
</div>

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

  const vori = document.getElementById('vori');
  const ana = document.getElementById('ana');
  const roti = document.getElementById('roti');
  const point = document.getElementById('point');
  const gramsInput = document.getElementById('grams_input');
  const computed = document.getElementById('computed_grams');
  const chipWeight = document.getElementById('chip_weight');
  const chipQty = document.getElementById('chip_qty');
  const qtyInput = document.getElementById('qty_input');
  const fillUnits = document.getElementById('fillUnits');
  const fillZero = document.getElementById('fillZero');
  const clearBtn = document.getElementById('clearBtn');

  function unitsToGrams(){
    const v = parseFloat(vori.value) || 0;
    const a = parseFloat(ana.value) || 0;
    const r = parseFloat(roti.value) || 0;
    const p = parseFloat(point.value) || 0;
    const totalVori = v + (a/16) + (r/(16*6)) + (p/(16*6*10));
    const grams = totalVori * GRAM_PER_VORI;
    return +(grams.toFixed(4));
  }

  function updatePreviewFromUnits(){
    const g = unitsToGrams();
    computed.innerText = g.toFixed(4) + ' g';
    chipWeight.innerText = 'Weight: ' + g.toFixed(4) + ' g';
  }

  [vori, ana, roti, point].forEach(el => el.addEventListener('input', updatePreviewFromUnits));

  gramsInput.addEventListener('input', function(){
    const g = parseFloat(gramsInput.value) || 0;
    computed.innerText = g.toFixed(4) + ' g';
    chipWeight.innerText = 'Weight: ' + g.toFixed(4) + ' g';
  });

  qtyInput.addEventListener('input', function(){
    const q = parseInt(qtyInput.value) || 0;
    chipQty.innerText = 'Qty: ' + q;
  });

  fillUnits.addEventListener('click', function(){
    const g = unitsToGrams();
    gramsInput.value = g.toFixed(4);
    computed.innerText = g.toFixed(4) + ' g';
    chipWeight.innerText = 'Weight: ' + g.toFixed(4) + ' g';
  });

  fillZero.addEventListener('click', function(){
    gramsInput.value = '0.0000';
    computed.innerText = '0.0000 g';
    chipWeight.innerText = 'Weight: 0.0000 g';
  });

  clearBtn.addEventListener('click', function(){
    document.getElementById('stockForm').reset();
    computed.innerText = '0.0000 g';
    chipWeight.innerText = 'Weight: 0.0000 g';
    chipQty.innerText = 'Qty: 0';
  });

  // init preview using editing values if present
  (function init(){
    const existingWeight = <?php echo isset($editing['weight_g'])?json_encode(number_format($editing['weight_g'],4)):json_encode('0.0000') ?>;
    const existingQty = <?php echo isset($editing['quantity'])?json_encode(intval($editing['quantity'])):json_encode(0) ?>;
    computed.innerText = existingWeight + ' g';
    chipWeight.innerText = 'Weight: ' + existingWeight + ' g';
    chipQty.innerText = 'Qty: ' + existingQty;
  })();

})();
</script>

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