<section class="project-form-shell">
  <div class="admin-header">
    <h1><%= invoice ? 'Edit ' + invoice.invoiceNumber : 'New Invoice' %></h1>
    <% if (invoice) { %><a class="button button-secondary" href="/admin/finance/invoices/<%= invoice.id %>">Back to invoice &rarr;</a><% } %>
  </div>
  <% if (!invoice) { %><p class="hint">Most invoices should come from converting an accepted quote (see the quote's detail page), which keeps the pricing consistent with what the client already agreed to. Use this form only for work with no prior quote.</p><% } %>

  <form method="POST" action="<%= invoice ? '/admin/finance/invoices/' + invoice.id + '?_method=PUT' : '/admin/finance/invoices' %>" id="invoice-form">

    <div class="offer-tab-buttons">
      <button type="button" class="offer-tab-btn is-active" data-tab-target="client">Client</button>
      <button type="button" class="offer-tab-btn" data-tab-target="items">Line Items</button>
      <button type="button" class="offer-tab-btn" data-tab-target="terms">Terms &amp; Notes</button>
    </div>

    <div class="form-grid">
      <div class="form-main">

        <div class="offer-tab-panel is-active" data-tab-panel="client">
          <div class="form-section">
            <h3 class="form-section-title">Client</h3>
            <label>
              Linked CRM prospect <span class="hint">(optional)</span>
              <select name="prospectId">
                <option value="">None (direct lead)</option>
                <% prospects.forEach(function(p) { %>
                  <option value="<%= p.id %>" <%= invoice && String(invoice.prospectId) === String(p.id) ? 'selected' : '' %>><%= p.companyName %><%= p.contactName ? ' - ' + p.contactName : '' %></option>
                <% }) %>
              </select>
            </label>
            <label>
              Client name
              <input type="text" name="clientName" value="<%= invoice ? invoice.clientName : '' %>" required>
            </label>
            <label>
              Organization
              <input type="text" name="clientOrganization" value="<%= invoice && invoice.clientOrganization ? invoice.clientOrganization : '' %>">
            </label>
            <label>
              Email
              <input type="email" name="clientEmail" value="<%= invoice && invoice.clientEmail ? invoice.clientEmail : '' %>">
            </label>
            <label>
              Phone
              <input type="text" name="clientPhone" value="<%= invoice && invoice.clientPhone ? invoice.clientPhone : '' %>">
            </label>
            <label>
              Bill-to extra line
              <input type="text" name="billToExtra" value="<%= invoice && invoice.billToExtra ? invoice.billToExtra : '' %>">
            </label>
            <label>
              Reference line
              <input type="text" name="referenceLine" value="<%= invoice && invoice.referenceLine ? invoice.referenceLine : '' %>">
            </label>
          </div>
        </div>

        <div class="offer-tab-panel" data-tab-panel="items">
          <div class="form-section">
            <h3 class="form-section-title">Line items</h3>
            <p class="hint">Search the catalogue to reuse a saved price, or just type a description for a one-off line. Cost price only needs typing for a brand-new item.</p>
            <table class="line-items-table" id="line-items-table">
              <thead>
                <tr>
                  <th style="width:14%">Category</th>
                  <th style="width:20%">Catalogue item</th>
                  <th>Description</th>
                  <th class="col-qty">Qty</th>
                  <th class="col-unit">Unit</th>
                  <th class="col-money">Cost</th>
                  <th class="col-money">Sell</th>
                  <th class="col-remove"></th>
                </tr>
              </thead>
              <tbody id="line-items-body"></tbody>
            </table>
            <button type="button" class="button button-secondary line-items-add" id="add-row-btn">+ Add line item</button>
          </div>
        </div>

        <div class="offer-tab-panel" data-tab-panel="terms">
          <div class="form-section">
            <h3 class="form-section-title">Terms</h3>
            <div id="editor-termsText" class="rich-editor rich-editor-compact"><%- invoice && invoice.termsText ? invoice.termsText : '<p>Payment due within ' + settings.invoiceDueDays + ' days of the invoice date above.</p>' %></div>
            <textarea name="termsText" id="input-termsText" hidden></textarea>
          </div>

          <div class="form-section">
            <h3 class="form-section-title">Internal</h3>
            <div id="editor-internalNotes" class="rich-editor rich-editor-compact"><%- invoice && invoice.internalNotes ? invoice.internalNotes : '' %></div>
            <textarea name="internalNotes" id="input-internalNotes" hidden></textarea>
            <p class="hint">Never shown to the client.</p>
          </div>
        </div>

      </div>

      <div class="form-sidebar">
        <div class="form-section">
          <h3 class="form-section-title">Pricing</h3>
          <label>
            Currency
            <input type="text" name="currency" id="currency-input" value="<%= invoice ? invoice.currency : settings.defaultCurrency %>" maxlength="8" required>
          </label>
          <label>
            Agency fee (%)
            <input type="number" step="0.01" min="0" name="agencyFeePercent" id="fee-input" value="<%= invoice ? invoice.agencyFeePercent : settings.standardAgencyFeePercent %>" required>
          </label>
          <label>
            Tax (%)
            <input type="number" step="0.01" min="0" name="taxPercent" id="tax-input" value="<%= invoice ? invoice.taxPercent : settings.defaultTaxPercent %>" required>
          </label>
          <label>
            Issue date
            <input type="date" name="issueDate" value="<%= invoice && invoice.issueDate ? invoice.issueDate : '' %>">
          </label>
          <label>
            Due date
            <input type="date" name="dueDate" value="<%= invoice && invoice.dueDate ? invoice.dueDate : '' %>">
          </label>
        </div>

        <div class="form-section">
          <h3 class="form-section-title">Live totals</h3>
          <div class="finance-totals-panel" id="totals-panel">
            <div class="totals-row"><span>Subtotal</span><span id="t-subtotal">0.00</span></div>
            <div class="totals-row"><span>Agency fee</span><span id="t-fee">0.00</span></div>
            <div class="totals-row"><span>Tax</span><span id="t-tax">0.00</span></div>
            <div class="totals-row total"><span>Total</span><span id="t-total">0.00</span></div>
            <div class="totals-row"><span>Internal cost</span><span id="t-cost">0.00</span></div>
            <div class="totals-row profit" id="t-profit-row"><span>Profit</span><span id="t-profit">0.00 (0%)</span></div>
          </div>
        </div>

        <div class="form-section">
          <button type="submit" class="button button-primary form-save-button">Save invoice</button>
        </div>
      </div>
    </div>
  </form>
</section>

<script>
  window.ZUCE_SERVICES = <%- JSON.stringify(services.map(function(s) {
    return {
      id: s.id, name: s.name, category: s.category || '', unit: s.unit,
      costPrice: Number(s.costPrice),
      markupPercent: (s.markupPercent !== null && s.markupPercent !== undefined) ? Number(s.markupPercent) : null,
      sellPrice: (s.sellPrice !== null && s.sellPrice !== undefined) ? Number(s.sellPrice) : null,
    };
  })) %>;
  window.ZUCE_EXISTING_LINE_ITEMS = <%- JSON.stringify((lineItems || []).map(function(li) {
    return {
      serviceId: li.serviceId || '', category: li.category || '', description: li.description,
      quantity: Number(li.quantity), unit: li.unit || '', unitCost: Number(li.unitCost),
      unitSellPrice: Number(li.unitSellPrice), isOptional: false,
    };
  })) %>;
  window.ZUCE_STANDARD_FEE = <%= Number(settings.standardAgencyFeePercent) %>;
  window.ZUCE_MIN_MARGIN = <%= Number(settings.minimumMarginPercent) %>;
  window.ZUCE_SHOW_OPTIONAL_COLUMN = false;
</script>
<script src="/js/finance-line-items.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/quill/1.3.7/quill.min.js"></script>
<script src="/js/finance-rich-text.js"></script>
<script>
  (function () {
    var buttons = document.querySelectorAll('.offer-tab-btn[data-tab-target]');
    var panels = document.querySelectorAll('.offer-tab-panel[data-tab-panel]');
    Array.prototype.forEach.call(buttons, function (btn) {
      btn.addEventListener('click', function () {
        var target = btn.getAttribute('data-tab-target');
        Array.prototype.forEach.call(buttons, function (b) { b.classList.toggle('is-active', b === btn); });
        Array.prototype.forEach.call(panels, function (p) { p.classList.toggle('is-active', p.getAttribute('data-tab-panel') === target); });
      });
    });
  })();
</script>
