<%- include('../partials/header') %>
<div class="flex ic jb mb24">
  <h2 style="font-size:20px;font-weight:700"><%= client ? 'Edit Client' : 'Add New Client' %></h2>
  <a href="/clients" class="btn btn-outline btn-sm"><i class="fa fa-arrow-left"></i> Back</a>
</div>

<form action="<%= action %>" method="<%= method %>">

<!-- GSTIN LOOKUP SECTION — at the top for auto-fill magic -->
<div class="form-section" style="border-color:rgba(61,127,255,.3);background:linear-gradient(135deg,var(--bg2),var(--bg3))">
  <div class="form-section-title"><i class="fa fa-magnifying-glass-chart"></i> GSTIN Auto-Fill
    <span class="muted xs" style="margin-left:8px;font-weight:400;text-transform:none;letter-spacing:0">Enter GSTIN to automatically fetch company details from GST Portal</span>
  </div>
  <div class="form-grid form-grid-2">
    <div class="form-group">
      <label>Enter GSTIN to Auto-Fill Details</label>
      <div class="gstin-wrap">
        <input type="text" id="gstinInput" placeholder="e.g. 27ATCPB2023M1Z1" maxlength="15"
          style="text-transform:uppercase;letter-spacing:1px;font-family:var(--mono)"
          value="<%= client ? client.gstin||'' : '' %>">
        <button type="button" class="gstin-lookup-btn" id="gstinLookupBtn">
          <i class="fa fa-search"></i> Fetch Details
        </button>
      </div>
      <div class="gstin-status" id="gstinStatus"></div>
    </div>
    <div style="display:flex;align-items:center;padding:12px;background:var(--bg4);border-radius:var(--r);font-size:12px;color:var(--text2)">
      <div>
        <div style="font-weight:600;color:var(--text);margin-bottom:4px"><i class="fa fa-bolt" style="color:var(--amber)"></i> How it works</div>
        <div style="color:var(--text3)">1. Type the 15-digit GSTIN above<br>2. Click "Fetch Details" (or wait for auto-detect)<br>3. Company name, address & state fills automatically<br>4. Review & save the form</div>
      </div>
    </div>
  </div>
</div>

<!-- BASIC INFO — IDs match what initGSTINLookup() fills -->
<div class="form-section">
  <div class="form-section-title"><i class="fa fa-building-user"></i> Basic Information</div>
  <div class="form-grid form-grid-3">
    <div class="form-group">
      <label>Client / Company Name *</label>
      <input type="text" id="fieldName" name="name" value="<%= client?client.name:'' %>" required placeholder="Legal name">
    </div>
    <div class="form-group">
      <label>Trade Name</label>
      <input type="text" id="fieldTradeName" name="tradeName" value="<%= client?client.tradeName||'':'' %>" placeholder="Brand / trade name">
    </div>
    <div class="form-group">
      <label>GST Type</label>
      <select id="fieldGSTType" name="gstType">
        <% ['Regular','Composition','Unregistered','SEZ','Export'].forEach(t=>{ %>
          <option value="<%= t %>" <%= client&&client.gstType===t?'selected':'' %>><%= t %></option>
        <% }) %>
      </select>
    </div>
    <div class="form-group">
      <label>GSTIN</label>
      <input type="text" name="gstin" value="<%= client?client.gstin||'':'' %>"
        placeholder="27XXXXX1234X1Z1" style="text-transform:uppercase;font-family:var(--mono)">
    </div>
    <div class="form-group">
      <label>PAN Number</label>
      <input type="text" id="fieldPAN" name="pan" value="<%= client?client.pan||'':'' %>"
        placeholder="Auto-filled from GSTIN" style="text-transform:uppercase;font-family:var(--mono)">
    </div>
    <div class="form-group">
      <label>Payment Terms (Days)</label>
      <input type="number" name="paymentTerms" value="<%= client?client.paymentTerms||45:45 %>">
    </div>
  </div>
</div>

<!-- BILLING ADDRESS — IDs match GSTIN autofill -->
<div class="form-section">
  <div class="form-section-title"><i class="fa fa-location-dot"></i> Billing Address</div>
  <div class="form-grid form-grid-3">
    <div class="form-group full">
      <label>Address Line 1</label>
      <input type="text" id="fieldAddrLine1" name="address[line1]" value="<%= client?client.address?.line1||'':'' %>" placeholder="Street, locality, building">
    </div>
    <div class="form-group full">
      <label>Address Line 2</label>
      <input type="text" id="fieldAddrLine2" name="address[line2]" value="<%= client?client.address?.line2||'':'' %>" placeholder="Area, landmark">
    </div>
    <div class="form-group">
      <label>City / District</label>
      <input type="text" id="fieldCity" name="address[city]" value="<%= client?client.address?.city||'':'' %>">
    </div>
    <div class="form-group">
      <label>State</label>
      <input type="text" id="fieldState" name="address[state]" value="<%= client?client.address?.state||'Maharashtra':'Maharashtra' %>">
    </div>
    <div class="form-group">
      <label>State Code</label>
      <input type="text" id="fieldStateCode" name="address[stateCode]" value="<%= client?client.address?.stateCode||'27':'27' %>" style="width:80px">
    </div>
    <div class="form-group">
      <label>Pincode</label>
      <input type="text" id="fieldPincode" name="address[pincode]" value="<%= client?client.address?.pincode||'':'' %>" maxlength="6">
    </div>
  </div>
</div>

<!-- CONTACT -->
<div class="form-section">
  <div class="form-section-title"><i class="fa fa-phone"></i> Contact Details</div>
  <div class="form-grid form-grid-4">
    <div class="form-group"><label>Contact Person</label><input type="text" name="contact[person]" value="<%= client?client.contact?.person||'':'' %>"></div>
    <div class="form-group"><label>Phone</label><input type="text" name="contact[phone]" value="<%= client?client.contact?.phone||'':'' %>"></div>
    <div class="form-group"><label>Alt Phone</label><input type="text" name="contact[altPhone]" value="<%= client?client.contact?.altPhone||'':'' %>"></div>
    <div class="form-group"><label>Email</label><input type="email" name="contact[email]" value="<%= client?client.contact?.email||'':'' %>"></div>
  </div>
</div>

<!-- BANK -->
<div class="form-section">
  <div class="form-section-title"><i class="fa fa-building-columns"></i> Bank Details (Optional)</div>
  <div class="form-grid form-grid-4">
    <div class="form-group"><label>Account Name</label><input type="text" name="bank[accountName]" value="<%= client?client.bank?.accountName||'':'' %>"></div>
    <div class="form-group"><label>Account Number</label><input type="text" name="bank[accountNumber]" value="<%= client?client.bank?.accountNumber||'':'' %>"></div>
    <div class="form-group"><label>Bank Name</label><input type="text" name="bank[bankName]" value="<%= client?client.bank?.bankName||'':'' %>"></div>
    <div class="form-group"><label>IFSC Code</label><input type="text" name="bank[ifsc]" value="<%= client?client.bank?.ifsc||'':'' %>" style="text-transform:uppercase"></div>
  </div>
</div>

<!-- PRODUCT RESTRICTION -->
<div class="form-section">
  <div class="form-section-title"><i class="fa fa-boxes-stacked"></i> Allowed Products — Client Restriction
    <span class="muted xs" style="margin-left:8px;font-weight:400;text-transform:none;letter-spacing:0">Leave blank = client can purchase ALL products</span>
  </div>
  <div style="background:var(--bg3);border:1px solid rgba(245,158,11,.3);border-radius:6px;padding:12px 14px;margin-bottom:14px;font-size:12px;color:var(--amber)">
    <i class="fa fa-lock"></i> <strong>Product Restriction:</strong> Select specific products to restrict this client. When creating an invoice, only these products will appear in the item search dropdown for this client.
  </div>
  <div style="margin-bottom:10px">
    <input type="text" id="productFilter" placeholder="Filter products by name…"
      oninput="filterProducts(this.value)" style="max-width:320px">
  </div>
  <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px;max-height:320px;overflow-y:auto;background:var(--bg3);border:1px solid var(--border);border-radius:6px;padding:12px" id="productList">
    <% products.forEach(p => {
      const isChecked = client && client.allowedProducts &&
        client.allowedProducts.some(ap => {
          const apId = ap.id ? ap.id.toString() : ap.toString();
          return apId === p.id.toString();
        });
    %>
    <label class="prod-item" data-name="<%= p.name.toLowerCase() %>"
      style="display:flex;align-items:flex-start;gap:8px;padding:8px 10px;background:var(--bg2);border:1px solid <%= isChecked ? 'var(--accent)' : 'var(--border)' %>;border-radius:6px;cursor:pointer;transition:border-color .15s;font-size:12px"
      onmouseover="this.style.borderColor='var(--accent)'"
      onmouseout="this.style.borderColor=this.querySelector('input').checked?'var(--accent)':'var(--border)'">
      <input type="checkbox" name="allowedProducts" value="<%= p.id %>"
        <%= isChecked ? 'checked' : '' %>
        style="width:14px;height:14px;accent-color:var(--accent);cursor:pointer;flex-shrink:0;margin-top:2px"
        onchange="this.closest('label').style.borderColor=this.checked?'var(--accent)':'var(--border)';updateCount()">
      <div style="min-width:0">
        <div style="font-weight:600;color:var(--text);word-break:break-word;line-height:1.3"><%= p.name %></div>
        <div class="muted xs" style="margin-top:3px">HSN: <%= p.hsnCode %> · GST: <%= p.gstRate %>% · ₹<%= (p.saleRate||0).toFixed(2) %></div>
      </div>
    </label>
    <% }) %>
  </div>
  <div style="display:flex;gap:8px;align-items:center;margin-top:10px">
    <button type="button" class="btn btn-outline btn-sm" onclick="selectAllProducts(true)"><i class="fa fa-check-square"></i> Select All</button>
    <button type="button" class="btn btn-ghost btn-sm" onclick="selectAllProducts(false)"><i class="fa fa-square"></i> Clear All</button>
    <span id="selectedCount" class="muted sm">
      <%= client && client.allowedProducts && client.allowedProducts.length > 0
        ? client.allowedProducts.length + ' product(s) selected — client is restricted'
        : 'None selected — all products allowed' %>
    </span>
  </div>
</div>

<div class="form-section">
  <div class="form-group"><label>Notes</label><textarea name="notes" rows="2" placeholder="Additional notes…"><%= client?client.notes||'':'' %></textarea></div>
</div>

<div class="flex g8 jb">
  <a href="/clients" class="btn btn-outline">Cancel</a>
  <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> <%= client ? 'Update Client' : 'Save Client' %></button>
</div>
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Init GSTIN lookup for clients
  initGSTINLookup('/clients/api/gstin');
});

function filterProducts(q) {
  document.querySelectorAll('.prod-item').forEach(item => {
    item.style.display = (item.dataset.name||'').includes(q.toLowerCase()) ? '' : 'none';
  });
}
function selectAllProducts(check) {
  document.querySelectorAll('#productList input[type="checkbox"]').forEach(cb => {
    cb.checked = check;
    cb.closest('label').style.borderColor = check ? 'var(--accent)' : 'var(--border)';
  });
  updateCount();
}
function updateCount() {
  const n = document.querySelectorAll('#productList input:checked').length;
  const el = document.getElementById('selectedCount');
  if (el) el.textContent = n > 0 ? `${n} product(s) selected — client is restricted` : 'None selected — all products allowed';
}
</script>
<%- include('../partials/footer') %>
