{% extends "base.html" %}
{% block title %}New Invoice{% endblock %}
{% block page_heading %}New Invoice{% endblock %}
{% block content %}
<style>
.invoice-hero{display:grid;grid-template-columns:1.4fr .8fr;gap:1.25rem;margin-bottom:1.25rem}.invoice-hero-card{background:linear-gradient(135deg,#0f172a,#064e3b);color:#fff;border-radius:28px;padding:2rem;box-shadow:0 24px 60px rgba(15,23,42,.22);position:relative;overflow:hidden}.invoice-hero-card:after{content:"";position:absolute;right:-60px;bottom:-60px;width:230px;height:230px;border-radius:50%;background:rgba(34,197,94,.25)}.invoice-hero-card h1{font-size:2rem;font-weight:900;margin:0 0 .5rem}.invoice-hero-card p{margin:0;color:#cbd5e1;font-weight:700}.invoice-side-card{background:#fff;border:1px solid rgba(148,163,184,.25);border-radius:28px;padding:1.5rem;box-shadow:0 18px 40px rgba(15,23,42,.08)}.invoice-form-grid{display:grid;grid-template-columns:repeat(4,minmax(160px,1fr));gap:1rem}.friendly-label{font-weight:900;color:#1e293b;margin-bottom:.4rem;font-size:.82rem;text-transform:uppercase;letter-spacing:.04em}.invoice-line{border:1px solid rgba(148,163,184,.28);border-radius:24px;background:linear-gradient(180deg,#fff,#f8fafc);box-shadow:0 14px 35px rgba(15,23,42,.06);padding:1.25rem;margin-bottom:1rem}.line-head{display:flex;align-items:center;justify-content:space-between;gap:1rem;margin-bottom:1rem}.line-title{font-weight:900;color:#0f172a;font-size:1.05rem}.type-pill{display:inline-flex;align-items:center;gap:.4rem;border-radius:999px;padding:.35rem .75rem;background:#e0f2fe;color:#075985;font-weight:900;font-size:.78rem}.summary-sticky{position:sticky;bottom:0;background:rgba(255,255,255,.9);backdrop-filter:blur(14px);border:1px solid rgba(148,163,184,.22);border-radius:24px;padding:1rem;box-shadow:0 -16px 40px rgba(15,23,42,.08);display:flex;justify-content:space-between;align-items:center;gap:1rem;z-index:5}.grand-total{font-size:1.7rem;font-weight:950;color:#059669}.help-chip{display:inline-flex;padding:.45rem .7rem;border-radius:999px;background:#ecfdf5;color:#047857;font-weight:800;margin:.2rem}.btn-row{display:flex;gap:.75rem;flex-wrap:wrap}.product-only.service-mode{opacity:.45}.item-mini-total{font-weight:900;color:#059669}.soft-note{color:#64748b;font-weight:700;font-size:.88rem}.add-item-big{width:100%;border:2px dashed rgba(16,185,129,.55);background:#ecfdf5;color:#047857;border-radius:22px;padding:1rem;font-weight:950;font-size:1.05rem}.add-item-big:hover{background:#d1fae5}.input-group-text{font-weight:900}.old-warning{background:#fff7ed;border:1px solid #fed7aa;color:#9a3412;border-radius:18px;padding:1rem;font-weight:800;margin-bottom:1rem}@media(max-width:1100px){.invoice-hero{grid-template-columns:1fr}.invoice-form-grid{grid-template-columns:repeat(2,1fr)}}@media(max-width:700px){.invoice-form-grid{grid-template-columns:1fr}.invoice-hero-card{padding:1.4rem}.invoice-hero-card h1{font-size:1.55rem}.summary-sticky{display:block}.grand-total{font-size:1.35rem}.line-head{align-items:flex-start}.btn-row .premium-btn,.btn-row .ghost-btn{width:100%;justify-content:center}}
</style>

<div class="invoice-hero">
  <div class="invoice-hero-card">
    <h1>🧾 Create New Invoice</h1>
    <p>Add many products and services in one order. Product stock reduces automatically. Services do not reduce stock.</p>
    <div class="mt-3">
      <span class="help-chip">Multiple products</span>
      <span class="help-chip">Services supported</span>
      <span class="help-chip">Warranty per item</span>
      <span class="help-chip">IMEI / Serial</span>
    </div>
  </div>
  <div class="invoice-side-card">
    <div class="fw-bold text-muted text-uppercase small">Quick guide</div>
    <div class="mt-2 soft-note">1. Enter customer/contact details.<br>2. Add product or service lines.<br>3. Select stock only for product items.<br>4. Enter warranty days per item.</div>
    <a class="ghost-btn mt-3" href="{{ url_for('index') }}">📋 View Order History</a>
  </div>
</div>

<form method="POST" id="invoiceForm" class="premium-card">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

  <div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-3">
    <div>
      <h2 class="m-0 fw-black">Customer & Invoice Details</h2>
      <div class="soft-note">Invoice number is auto generated if you leave it empty.</div>
    </div>
    <a class="ghost-btn" href="{{ url_for('global_search') }}">🔎 Search Customer</a>
  </div>

  <div class="invoice-form-grid mb-4">
    <div><div class="friendly-label">Invoice No</div><input class="form-control" name="invoice_no" placeholder="Auto: INV-2026-0001"></div>
    <div><div class="friendly-label">Date</div><input class="form-control" type="date" name="order_date"></div>
    <div><div class="friendly-label">Order ID</div><input class="form-control" name="order_id" placeholder="Daraz/Tudo/Manual ID"></div>
    <div><div class="friendly-label">Cash Received</div><div class="input-group"><span class="input-group-text">LKR</span><input class="form-control" type="number" step="0.01" name="cash_received" value="0"></div></div>
    <div><div class="friendly-label">Contact 1 *</div><input class="form-control" name="contact1" required placeholder="Customer phone"></div>
    <div><div class="friendly-label">Contact 2</div><input class="form-control" name="contact2" placeholder="Optional"></div>
    <div><div class="friendly-label">Order Via</div><select class="form-select" name="order_via">{% for m in order_methods %}<option>{{ m }}</option>{% endfor %}</select></div>
    <div><div class="friendly-label">Store</div><select class="form-select" name="store">{% for s in stores %}<option>{{ s }}</option>{% endfor %}</select></div>
  </div>

  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
    <div>
      <h2 class="m-0 fw-black">Invoice Items</h2>
      <div class="soft-note">Use one line for each product or service.</div>
    </div>
    <button type="button" class="premium-btn" onclick="addLine('product')">+ Product</button>
    <button type="button" class="ghost-btn" onclick="addLine('service')">+ Service</button>
  </div>

  <div id="lines"></div>
  <button type="button" class="add-item-big" onclick="addLine('product')">＋ Add another item line</button>

  <div class="summary-sticky mt-4">
    <div>
      <div class="soft-note">Invoice Total</div>
      <div class="grand-total">LKR <span id="grandTotal">0.00</span></div>
    </div>
    <div class="btn-row">
      <button class="premium-btn" type="submit">✅ Save Invoice</button>
      <a class="ghost-btn" href="{{ url_for('index') }}">Cancel / History</a>
    </div>
  </div>
</form>

<template id="lineTemplate">
  <div class="invoice-line">
    <div class="line-head">
      <div>
        <span class="type-pill line-badge">📦 Product</span>
        <span class="line-title ms-2">Item Line</span>
      </div>
      <div class="d-flex align-items-center gap-2">
        <span class="item-mini-total">LKR <span class="line-total">0.00</span></span>
        <button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest('.invoice-line').remove(); renumberLines(); calcTotal();">Remove</button>
      </div>
    </div>
    <div class="invoice-form-grid">
      <div>
        <div class="friendly-label">Item Type</div>
        <select class="form-select item-type" name="item_type[]" onchange="toggleType(this)">
          <option value="product">Product</option>
          <option value="service">Service</option>
        </select>
      </div>
      <div class="product-only">
        <div class="friendly-label">Stock Product</div>
        <select class="form-select stock-select" name="stock_id[]" onchange="fillProduct(this)">
          <option value="">Manual product / no stock link</option>
          {% for stock in stocks %}
          <option value="{{ stock.id }}" data-name="{{ stock.item_name|e }}" data-price="{{ stock.unit_cost or 0 }}" data-qty="{{ stock.qty or 0 }}">{{ stock.item_name }} — Stock: {{ stock.qty }}</option>
          {% endfor %}
        </select>
      </div>
      <div><div class="friendly-label">Item / Service Name *</div><input class="form-control item-name" name="item_name[]" required placeholder="Example: MF68E Router / Setup Service"></div>
      <div><div class="friendly-label">Quantity</div><input class="form-control qty" type="number" name="qty[]" value="1" min="1" oninput="calcTotal()"></div>
      <div><div class="friendly-label">Unit Price</div><div class="input-group"><span class="input-group-text">LKR</span><input class="form-control price" type="number" step="0.01" name="unit_price[]" value="0" oninput="calcTotal()"></div></div>
      <div><div class="friendly-label">Cost</div><div class="input-group"><span class="input-group-text">LKR</span><input class="form-control cost" type="number" step="0.01" name="cost[]" value="0"></div></div>
      <div class="product-only"><div class="friendly-label">IMEI</div><input class="form-control" name="imei[]" placeholder="Product only"></div>
      <div class="product-only"><div class="friendly-label">Serial</div><input class="form-control" name="serial[]" placeholder="Product only"></div>
      <div><div class="friendly-label">Product/Service Warranty Days</div><input class="form-control" type="number" name="product_warranty_days[]" value="0" placeholder="0 = No warranty"></div>
      <div class="product-only"><div class="friendly-label">Battery Warranty Days</div><input class="form-control" type="number" name="battery_warranty_days[]" value="0" placeholder="Optional"></div>
      <div style="grid-column:1/-1"><div class="friendly-label">Line Notes</div><input class="form-control" name="notes[]" placeholder="Example: No warranty for physical damage / setup completed"></div>
    </div>
  </div>
</template>

<script>
function addLine(type='product'){
  const t=document.getElementById('lineTemplate');
  const node=t.content.cloneNode(true);
  document.getElementById('lines').appendChild(node);
  const line=document.querySelectorAll('.invoice-line')[document.querySelectorAll('.invoice-line').length-1];
  line.querySelector('.item-type').value=type;
  toggleType(line.querySelector('.item-type'));
  renumberLines();
  calcTotal();
}
function renumberLines(){document.querySelectorAll('.invoice-line').forEach((line,i)=>{line.querySelector('.line-title').textContent='Item Line '+(i+1);});}
function fillProduct(sel){
  const opt=sel.options[sel.selectedIndex];
  const line=sel.closest('.invoice-line');
  if(opt && opt.dataset.name){
    line.querySelector('.item-name').value=opt.dataset.name;
    line.querySelector('.price').value=opt.dataset.price||0;
    const cost=line.querySelector('.cost'); if(cost) cost.value=opt.dataset.price||0;
  }
  calcTotal();
}
function toggleType(sel){
  const line=sel.closest('.invoice-line');
  const isService=sel.value==='service';
  line.querySelector('.line-badge').textContent=isService?'🛠️ Service':'📦 Product';
  line.querySelectorAll('.product-only').forEach(el=>el.classList.toggle('service-mode',isService));
  const stock=line.querySelector('.stock-select');
  if(isService && stock){stock.value='';}
}
function calcTotal(){
  let total=0;
  document.querySelectorAll('.invoice-line').forEach(line=>{
    const q=parseFloat(line.querySelector('.qty').value||0);
    const p=parseFloat(line.querySelector('.price').value||0);
    const lineTotal=q*p;
    total+=lineTotal;
    const lineTotalEl=line.querySelector('.line-total');
    if(lineTotalEl) lineTotalEl.textContent=lineTotal.toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});
  });
  document.getElementById('grandTotal').textContent=total.toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});
}
addLine('product');
</script>
{% endblock %}
