<%- include('../../partials/header') %>
<div class="flex ic jb mb24">
  <div>
    <h2 style="font-size:20px;font-weight:700;margin-bottom:4px"><%= bill ? 'Edit Invoice' : 'New Sales Invoice' %></h2>
    <p class="muted sm">GST Tax Invoice</p>
  </div>
  <a href="/sales-bills" class="btn btn-outline btn-sm"><i class="fa fa-arrow-left"></i> Back</a>
</div>

<form action="/sales-bills<%= bill ? '/'+bill.id+'?_method=PUT' : '' %>" method="POST" id="invoiceForm">

<!-- Invoice Details -->
<div class="form-section">
  <div class="form-section-title"><i class="fa fa-file-invoice"></i> Invoice Details</div>
  <div class="form-grid form-grid-4">
    <div class="form-group">
      <label>Invoice Type</label>
      <select name="billType">
        <% ['Tax Invoice','Credit Note','Debit Note','Proforma'].forEach(t=>{ %><option value="<%= t %>" <%= bill&&bill.billType===t?'selected':'' %>><%= t %></option><% }) %>
      </select>
    </div>
    <div class="form-group">
      <label>Invoice Date *</label>
      <input type="date" name="invoiceDate" required value="<%= bill ? moment(bill.invoiceDate).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD') %>">
    </div>
    <div class="form-group">
      <label>PO Number</label>
      <input type="text" name="poNo" value="<%= bill ? bill.poNo||'' : '' %>" placeholder="Customer PO No.">
    </div>
    <div class="form-group">
      <label>PO Date</label>
      <input type="date" name="poDate" value="<%= bill && bill.poDate ? moment(bill.poDate).format('YYYY-MM-DD') : '' %>">
    </div>
    <div class="form-group">
      <label>Payment Terms (Days)</label>
      <input type="number" name="paymentTerms" value="<%= bill ? bill.paymentTerms||45 : (settings?.invoice?.defaultPaymentTerms||45) %>">
    </div>
    <div class="form-group">
      <label>Supply Type</label>
      <select name="supplyType">
        <% ['B2B','B2C','Export','SEZ'].forEach(t=>{ %><option value="<%= t %>" <%= bill&&bill.supplyType===t?'selected':'' %>><%= t %></option><% }) %>
      </select>
    </div>
    <div class="form-group">
      <label>Place of Supply</label>
      <input type="text" name="placeOfSupply" value="<%= bill ? bill.transport?.placeOfSupply||'' : 'Maharashtra' %>">
    </div>
    <div class="form-group">
      <label>Transport Mode</label>
      <select name="transportMode">
        <option value="BY ROAD">BY ROAD</option><option value="BY RAIL">BY RAIL</option><option value="BY AIR">BY AIR</option>
      </select>
    </div>
    <div class="form-group">
      <label>Vehicle No.</label>
      <input type="text" name="vehicleNo" value="<%= bill ? bill.transport?.vehicleNo||'' : '' %>" placeholder="MH12AB1234">
    </div>
    <div class="form-group">
      <label>Dispatch Date</label>
      <input type="date" name="dispatchDate" value="<%= bill && bill.transport?.dispatchDate ? moment(bill.transport.dispatchDate).format('YYYY-MM-DD') : '' %>">
    </div>
  </div>
</div>

<!-- Client Selection — FIXED -->
<div class="form-section">
  <div class="form-section-title"><i class="fa fa-building-user"></i> Billed To</div>
  <div class="form-grid form-grid-2">
    <div>
      <div class="form-group mb8">
        <label>Search & Select Client *</label>
        <div style="position:relative">
          <input type="text" id="clientSearch" placeholder="Type client name to search…"
            autocomplete="off" value="<%= bill&&bill.client ? (bill.client.name||'') : '' %>"
            style="padding-left:36px">
          <i class="fa fa-search" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--text3);font-size:13px;pointer-events:none"></i>
        </div>
        <!-- CRITICAL: this hidden input carries the actual client ObjectId -->
        <input type="hidden" name="client" id="clientId" value="<%= bill&&bill.client ? (bill.client.id||bill.client||'') : '' %>" required>
        <div class="mt8"><a href="/clients/new" target="_blank" class="cacc sm"><i class="fa fa-plus"></i> Add new client</a></div>
      </div>

      <!-- Product restriction notice -->
      <div class="prod-notice" id="prodNotice"></div>

      <!-- Client details preview -->
      <div id="clientDetails" style="background:var(--bg3);border:1px solid var(--border);border-radius:6px;padding:12px;font-size:12px;display:<%= bill&&bill.billedTo?.name?'block':'none' %>">
        <div style="font-weight:600;color:var(--text);margin-bottom:4px" id="cd-name"><%= bill ? bill.billedTo?.name||'' : '' %></div>
        <div class="muted" id="cd-gstin">GSTIN: <%= bill ? bill.billedTo?.gstin||'' : '' %></div>
        <div class="muted" id="cd-addr"><%= bill ? bill.billedTo?.address||'' : '' %></div>
        <div class="muted" id="cd-phone"><%= bill ? bill.billedTo?.phone||'' : '' %></div>
      </div>
    </div>
    <div>
      <div class="form-group mb8">
        <label>Ship To Name</label>
        <input type="text" name="shipName" id="shipName" value="<%= bill ? bill.shippedTo?.name||'' : '' %>" placeholder="Same as billing by default">
      </div>
      <div class="form-grid form-grid-2">
        <div class="form-group">
          <label>Ship GSTIN</label>
          <input type="text" name="shipGstin" id="shipGstin" value="<%= bill ? bill.shippedTo?.gstin||'' : '' %>">
        </div>
        <div class="form-group">
          <label>Ship State Code</label>
          <input type="text" name="shipStateCode" id="shipStateCode" value="<%= bill ? bill.shippedTo?.stateCode||'27' : '27' %>" style="width:80px">
        </div>
      </div>
      <div class="form-group mt8">
        <label>Ship Address</label>
        <textarea name="shipAddress" rows="2" id="shipAddress"><%= bill ? bill.shippedTo?.address||'' : '' %></textarea>
      </div>
    </div>
  </div>
</div>

<!-- Line Items — FIXED: proper name attributes, works with parseLineItems -->
<div class="form-section">
  <div class="form-section-title"><i class="fa fa-list"></i> Line Items
    <span class="muted xs" style="margin-left:8px;font-weight:400">(Select a client first to see their assigned products)</span>
  </div>
  <div style="overflow-x:auto">
    <table class="li-table" style="width:100%">
      <thead><tr>
        <th style="width:32px">#</th>
        <th style="min-width:200px">Particulars / Description</th>
        <th>HSN</th><th>Qty</th><th>Unit</th><th>Rate</th><th>GST%</th>
        <th class="tr">Total</th><th style="width:32px"></th>
      </tr></thead>
      <tbody id="lineItemsBody">
        <% if (bill && bill.lineItems && bill.lineItems.length > 0) { %>
          <% bill.lineItems.forEach((item, i) => { %>
          <tr class="li-row">
            <td style="text-align:center;color:var(--text3);font-size:12px;padding:6px 4px"><%= i+1 %></td>
            <td style="padding:4px 2px;min-width:200px">
              <div style="position:relative">
                <input type="text" name="particulars" data-search value="<%= item.particulars %>" required style="width:100%" autocomplete="off">
              </div>
            </td>
            <td style="padding:4px 2px"><input type="text" name="hsnCode" data-hsn value="<%= item.hsnCode||'' %>" style="width:90px"></td>
            <td style="padding:4px 2px"><input type="number" name="qty" data-qty value="<%= item.qty %>" min="0.001" step="any" style="width:70px" required></td>
            <td style="padding:4px 2px">
              <select name="unit" style="width:68px">
                <% ['NOS','KG','MTR','LTR','BOX','SET','PCS','PAIR'].forEach(u=>{ %><option <%= u===item.unit?'selected':'' %>><%= u %></option><% }) %>
              </select>
            </td>
            <td style="padding:4px 2px"><input type="number" name="mrp" data-rate value="<%= item.mrp||'' %>" step="any" style="width:75px" required placeholder="Rate"></td>
            <td style="padding:4px 2px;text-align:center;font-weight:600">
              <input type="hidden" name="gstRate" data-gst value="<%= item.gstRate %>" />
              <%= item.gstRate %>%
            </td>
            <td class="row-total" data-total style="text-align:right;padding:4px 8px;font-family:var(--mono);font-weight:600;white-space:nowrap">₹<%= (item.total||0).toLocaleString('en-IN',{minimumFractionDigits:2}) %></td>
            <td style="padding:4px 2px"><button type="button" class="rm-btn" onclick="LineItems.removeRow(this)"><i class="fa fa-times"></i></button></td>
          </tr>
          <% }) %>
        <% } %>
      </tbody>
    </table>
    <button type="button" class="add-row-btn" onclick="LineItems.addRow()">
      <i class="fa fa-plus"></i> Add Line Item
    </button>
  </div>

  <!-- Totals -->
  <div style="display:flex;justify-content:flex-end;margin-top:20px">
    <div class="totals-box">
      <div class="tot-row"><span class="lbl">Total Amount</span><span class="val" id="sum-taxable">₹0.00</span></div>
      <div class="tot-row"><span class="lbl">GST</span><span class="val" id="sum-gst">₹0.00</span></div>
      <div class="tot-row grand divider"><span class="lbl">Net Payable</span><span class="val cacc" id="sum-net">₹0.00</span></div>
      <!-- Hidden inputs sent with form -->
      <input type="hidden" name="taxableAmount" id="inp-taxable">
      <input type="hidden" name="totalGst"      id="inp-gst">
      <input type="hidden" name="totalAmount"   id="inp-total">
      <input type="hidden" name="roundOff"      id="inp-roundoff" value="0">
      <input type="hidden" name="netPayable"    id="inp-net">
    </div>
  </div>
</div>

<!-- Notes -->
<div class="form-section">
  <div class="form-section-title"><i class="fa fa-note-sticky"></i> Notes & Terms</div>
  <div class="form-grid form-grid-2">
    <div class="form-group"><label>Notes</label><textarea name="notes" rows="3" placeholder="Delivery instructions…"><%= bill ? bill.notes||'' : '' %></textarea></div>
    <div class="form-group"><label>Terms & Conditions</label><textarea name="termsConditions" rows="3"><%= bill ? bill.termsConditions||'' : (settings?.invoice?.termsConditions||'') %></textarea></div>
  </div>
</div>

<div class="flex g8 jb">
  <a href="/sales-bills" class="btn btn-outline">Cancel</a>
  <div class="flex g8">
    <button type="submit" name="status" value="Draft" class="btn btn-outline"><i class="fa fa-save"></i> Save Draft</button>
    <button type="submit" class="btn btn-primary"><i class="fa fa-file-invoice"></i> <%= bill ? 'Update Invoice' : 'Generate Invoice' %></button>
  </div>
</div>

</form>

<script>
// Init line items engine
LineItems.init('lineItemsBody');

// Add first empty row if new invoice
<% if (!bill || !bill.lineItems || bill.lineItems.length === 0) { %>
LineItems.addRow();
<% } else { %>
LineItems.recalcAll();
<% } %>

// If editing an existing bill — load the client's products automatically
<% if (bill && bill.client) { %>
(async () => {
  const clientId = '<%= bill.client.id || bill.client %>';
  if (clientId && clientId.length >= 10) {
    await loadClientProducts(clientId);
    const notice = document.getElementById('prodNotice');
    if (notice && clientProducts.length > 0) {
      notice.style.display = 'block';
      notice.innerHTML = `<i class="fa fa-boxes-stacked"></i> <strong>${clientProducts.length} product(s)</strong> available for this client.`;
    }
  }
})();
<% } %>
</script>
<%- include('../../partials/footer') %>
