<section class="project-form-shell">
  <div class="admin-header">
    <h1><%= quote ? 'Edit ' + quote.quoteNumber : 'New Quote' %></h1>
    <% if (quote) { %><a class="button button-secondary" href="/admin/finance/quotes/<%= quote.id %>">Back to quote &rarr;</a><% } %>
  </div>

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

    <div class="offer-tab-buttons">
      <button type="button" class="offer-tab-btn is-active" data-tab-target="client">Client &amp; Job</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 - leave as "None" for a direct lead not in the pipeline)</span>
              <select name="prospectId">
                <option value="">None (direct lead)</option>
                <% prospects.forEach(function(p) { %>
                  <option value="<%= p.id %>" <%= quote && String(quote.prospectId) === String(p.id) ? 'selected' : '' %>><%= p.companyName %><%= p.contactName ? ' - ' + p.contactName : '' %></option>
                <% }) %>
              </select>
            </label>
            <label>
              Client name
              <input type="text" name="clientName" value="<%= quote ? quote.clientName : '' %>" required placeholder="e.g. Jane Mwangi">
            </label>
            <label>
              Organization
              <input type="text" name="clientOrganization" value="<%= quote && quote.clientOrganization ? quote.clientOrganization : '' %>" placeholder="e.g. Acme Ltd">
            </label>
            <label>
              Email
              <input type="email" name="clientEmail" value="<%= quote && quote.clientEmail ? quote.clientEmail : '' %>">
            </label>
            <label>
              Phone
              <input type="text" name="clientPhone" value="<%= quote && quote.clientPhone ? quote.clientPhone : '' %>">
            </label>
            <label>
              Bill-to extra line <span class="hint">(e.g. "c/o Agency Name")</span>
              <input type="text" name="billToExtra" value="<%= quote && quote.billToExtra ? quote.billToExtra : '' %>">
            </label>
          </div>

          <div class="form-section">
            <h3 class="form-section-title">The job</h3>
            <label>
              Reference line <span class="hint">(the "Re:" line under the Bill To block)</span>
              <input type="text" name="referenceLine" value="<%= quote && quote.referenceLine ? quote.referenceLine : '' %>" placeholder="e.g. Brand Launch Campaign - PR, Events &amp; Digital Rollout">
            </label>
            <label>
              Project / event date <span class="hint">(optional - leave blank if not relevant)</span>
              <input type="date" name="eventDate" value="<%= quote && quote.eventDate ? quote.eventDate : '' %>">
            </label>
            <label>
              Quantity <span class="hint">(optional - e.g. number of guests, users, licenses)</span>
              <input type="number" min="0" step="1" name="guestCount" value="<%= quote && quote.guestCount ? quote.guestCount : '' %>">
            </label>
            <label>
              Quantity label <span class="hint">(shown as a "Per X" line on the PDF, e.g. "guest", "user" - only shown if Quantity above is also set)</span>
              <input type="text" name="perUnitLabel" value="<%= quote && quote.perUnitLabel ? quote.perUnitLabel : '' %>" placeholder="e.g. guest">
            </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 - pick an existing catalogue item and its cost comes along automatically.</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-optional">Add-on</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">Inclusions, exclusions &amp; terms</h3>
            <label>
              Inclusions
              <div id="editor-inclusionsText" class="rich-editor rich-editor-compact"><%- quote && quote.inclusionsText ? quote.inclusionsText : '' %></div>
              <textarea name="inclusionsText" id="input-inclusionsText" hidden></textarea>
            </label>
            <label>
              Exclusions
              <div id="editor-exclusionsText" class="rich-editor rich-editor-compact"><%- quote && quote.exclusionsText ? quote.exclusionsText : '' %></div>
              <textarea name="exclusionsText" id="input-exclusionsText" hidden></textarea>
            </label>
            <label>
              Terms
              <div id="editor-termsText" class="rich-editor rich-editor-compact"><%- quote && quote.termsText ? quote.termsText : '<p>Quotation valid for ' + settings.quoteValidityDays + ' days from the date above.</p>' %></div>
              <textarea name="termsText" id="input-termsText" hidden></textarea>
            </label>
          </div>

          <div class="form-section">
            <h3 class="form-section-title">Internal</h3>
            <label>
              Internal notes <span class="hint">(never shown to the client)</span>
              <div id="editor-internalNotes" class="rich-editor rich-editor-compact"><%- quote && quote.internalNotes ? quote.internalNotes : '' %></div>
              <textarea name="internalNotes" id="input-internalNotes" hidden></textarea>
            </label>
            <label>
              Drafted by (name)
              <input type="text" name="draftedByName" value="<%= quote && quote.draftedByName ? quote.draftedByName : '' %>">
            </label>
            <label>
              Drafted by (email)
              <input type="email" name="draftedByEmail" value="<%= quote && quote.draftedByEmail ? quote.draftedByEmail : '' %>">
            </label>
          </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="<%= quote ? quote.currency : settings.defaultCurrency %>" maxlength="8" required>
          </label>
          <label>
            Agency fee (%)
            <input type="number" step="0.01" min="0" name="agencyFeePercent" id="fee-input" value="<%= quote ? quote.agencyFeePercent : settings.standardAgencyFeePercent %>" required>
          </label>
          <label>
            Tax (%)
            <input type="number" step="0.01" min="0" name="taxPercent" id="tax-input" value="<%= quote ? quote.taxPercent : settings.defaultTaxPercent %>" required>
          </label>
          <label>
            Valid until
            <input type="date" name="validUntil" value="<%= quote && quote.validUntil ? quote.validUntil : '' %>">
          </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 quote</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: !!li.isOptional,
    };
  })) %>;
  window.ZUCE_STANDARD_FEE = <%= Number(settings.standardAgencyFeePercent) %>;
  window.ZUCE_MIN_MARGIN = <%= Number(settings.minimumMarginPercent) %>;
</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>
