<% layout('layouts/main') %>
<% const adminBase = typeof adminBaseUrl !== 'undefined' ? adminBaseUrl : '/admin'; %>
<% const currentTerms = invoice.due_date ? Math.round((new Date(`${ui.dateInput(invoice.due_date)}T00:00:00`).setHours(0,0,0,0) - new Date(`${ui.dateInput(invoice.created_at)}T00:00:00`).setHours(0,0,0,0)) / 86400000) : 30; %>
<% const invoiceMailSubject = `Votre facture ${invoice.invoice_number} - ${currentCompany ? currentCompany.name : 'Lustra'}`; %>
<% const invoiceMailBody = `Bonjour,\n\nVotre facture ${invoice.invoice_number} est disponible. Vous la trouverez en pièce jointe de cet email.\n\nMontant: ${ui.money(invoice.total)}\nÉchéance: ${ui.date(invoice.due_date)}\n\nAvec nos meilleures salutations`; %>
<div class="app-shell">
  <%- partial('partials/admin-nav') %>
  <section class="content invoice-page">
    <div class="page-head">
      <div><p class="eyebrow">Facture</p><h1><%= invoice.invoice_number %></h1></div>
      <span class="badge"><%= ui.label(invoice.status) %></span>
    </div>

    <div class="panel">
      <div class="detail-grid compact">
        <div class="detail-item"><span>Client</span><strong><%= invoice.first_name %> <%= invoice.last_name %></strong></div>
        <div class="detail-item"><span>Total</span><strong><%= ui.money(invoice.total) %></strong></div>
        <div class="detail-item"><span>Payé</span><strong><%= ui.money(invoice.paid_amount) %></strong></div>
        <div class="detail-item"><span>Échéance</span><strong><%= ui.date(invoice.due_date) %></strong></div>
      </div>
      <div class="actions inline-actions">
        <a class="button secondary" href="/invoices/<%= invoice.id %>/pdf">Télécharger le PDF</a>
        <form method="post" action="<%= adminBase %>/factures/<%= invoice.id %>/regenerer-pdf"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button class="secondary">Régénérer le PDF</button></form>
        <form method="post" action="<%= adminBase %>/factures/<%= invoice.id %>/envoyer" class="invoice-send-review-form" data-email-review-form data-email-title="Envoyer la facture" data-default-to="<%= invoice.email %>" data-default-subject="<%= invoiceMailSubject %>" data-default-body="<%= invoiceMailBody %>" data-attachment-url="/invoices/<%= invoice.id %>/pdf" data-attachment-label="<%= invoice.invoice_number %>.pdf">
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <input type="hidden" name="email_to">
          <input type="hidden" name="email_subject">
          <input type="hidden" name="email_body">
          <label class="check premium-check small">
            <input type="checkbox" name="send_google_review_request" value="1" <%= reviewRequest ? 'disabled' : '' %>>
            <span><strong>Demander un avis Google</strong><small><%= reviewRequest ? `Déjà envoyé le ${ui.date(reviewRequest.sent_at || reviewRequest.requested_at, true)}` : (googleReviewUrl ? 'Envoyer une seule demande avec cette facture.' : 'Configurez le lien Google Avis dans les paramètres.') %></small></span>
          </label>
          <button>Envoyer au client</button>
        </form>
      </div>
    </div>

    <form method="post" action="<%= adminBase %>/factures/<%= invoice.id %>" class="invoice-editor" data-invoice-form data-issue-date="<%= ui.dateInput(invoice.created_at) %>">
      <input type="hidden" name="_csrf" value="<%= csrfToken %>">

      <section class="invoice-section">
        <div class="section-title"><span>1</span><h2>Client & paiement</h2></div>
        <div class="form-grid two">
          <label>Client<select name="user_id"><% clients.forEach(c=>{ %><option value="<%= c.id %>" <%= invoice.user_id===c.id?'selected':'' %>><%= c.first_name %> <%= c.last_name %> - <%= c.email %></option><% }) %></select></label>
          <label>Compte bancaire QR-facture
            <select name="bank_account_id">
              <option value="">Aucun compte / pas de QR-facture</option>
              <% bankAccounts.forEach(account=>{ %><option value="<%= account.id %>" <%= invoice.bank_account_id===account.id?'selected':'' %>><%= account.label %> - <%= account.iban %></option><% }) %>
            </select>
          </label>
        </div>
        <div class="form-grid two">
          <label>Conditions de paiement
            <select name="payment_terms_days" data-payment-terms>
              <option value="10" <%= currentTerms === 10 ? 'selected' : '' %>>A 10 jours</option>
              <option value="30" <%= currentTerms !== 10 ? 'selected' : '' %>>A 30 jours</option>
            </select>
          </label>
          <label>Échéance automatique<input type="date" name="due_date" value="<%= ui.dateInput(invoice.due_date) %>" data-due-date></label>
        </div>
      </section>

      <section class="invoice-section">
        <div class="section-title"><span>2</span><h2>Prestation</h2></div>
        <div class="form-grid two"><label>Prestation<input name="service_type" value="<%= invoice.service_type %>" required></label><label>Statut<select name="status"><% ['brouillon','envoyee','partiellement_payee','payee','en_retard','annulee'].forEach(s=>{ %><option value="<%= s %>" <%= invoice.status===s?'selected':'' %>><%= ui.label(s) %></option><% }) %></select></label></div>
        <label>Description<textarea name="description"><%= invoice.description || '' %></textarea></label>
      </section>

      <section class="invoice-section">
        <div class="section-title"><span>3</span><h2>Lignes de facture</h2></div>
        <p class="field-help">Choisissez l’unité adaptée. Pour les heures, vous pouvez saisir par exemple 1h35, 1:35 ou 1.5.</p>
        <div class="invoice-lines-head"><span>Description</span><span>Quantité</span><span>Unité</span><span>Prix unitaire</span><span>Total</span><span></span></div>
        <div id="invoice-lines" class="invoice-lines">
          <% const existingItems = items.length ? items : [{ description: '', quantity: 1, unit: 'forfait', unit_price: '' }]; %>
          <% const unitOptions = [
            ['forfait', 'Forfait'],
            ['heure', 'Heures'],
            ['m2', 'm²'],
            ['piece', 'Pièce'],
            ['fenetre', 'Fenêtre'],
            ['store', 'Store'],
            ['jour', 'Jour'],
            ['deplacement', 'Déplacement']
          ]; %>
          <% existingItems.forEach(item => { %>
            <div class="line-row invoice-line" data-invoice-line>
              <label class="mini-field"><span>Description</span><input name="item_description" placeholder="Description" value="<%= item.description || '' %>"></label>
              <label class="mini-field"><span data-quantity-label>Quantité</span><input name="item_quantity" value="<%= item.quantity || 1 %>" placeholder="1" inputmode="decimal" data-line-quantity></label>
              <label class="mini-field"><span>Unité</span><select name="item_unit" data-line-unit>
                <% unitOptions.forEach(([value, label]) => { %><option value="<%= value %>" <%= (item.unit || 'forfait') === value ? 'selected' : '' %>><%= label %></option><% }) %>
              </select></label>
              <label class="mini-field"><span data-price-label>Prix unitaire</span><input name="item_price" placeholder="Prix" value="<%= item.unit_price || '' %>" inputmode="decimal" data-line-price></label>
              <div class="line-total"><span>Total</span><strong data-line-total>CHF 0.00</strong></div>
              <button type="button" class="icon-danger" data-remove-line aria-label="Supprimer cette ligne">×</button>
            </div>
          <% }) %>
        </div>
        <button type="button" class="secondary" data-add-line="#invoice-lines">Ajouter une ligne</button>
      </section>

      <section class="invoice-section">
        <div class="section-title"><span>4</span><h2>TVA & finalisation</h2></div>
        <div class="form-grid two">
          <label class="check premium-check"><input type="checkbox" name="vat_enabled" <%= invoice.vat_enabled ? 'checked' : '' %>><span><strong>TVA active</strong><small>Le taux est appliqué au total des lignes.</small></span></label>
          <label>Taux TVA<input name="vat_rate" value="<%= invoice.vat_rate || app.tvaRate %>" inputmode="decimal"></label>
        </div>
        <label>Conditions internes ou note optionnelle<textarea name="conditions"><%= invoice.conditions || '' %></textarea></label>
        <button>Enregistrer et régénérer le PDF</button>
      </section>
    </form>

    <div class="panel">
      <h2>Paiements</h2>
      <div class="mobile-list compact-list">
        <% payments.forEach(p => { %><article class="line-card"><strong><%= ui.money(p.amount) %></strong><span><%= ui.date(p.paid_at) %> - <%= p.method || 'Méthode non renseignée' %></span></article><% }) %>
        <% if (!payments.length) { %><p class="muted">Aucun paiement enregistré.</p><% } %>
      </div>
      <form method="post" action="<%= adminBase %>/factures/<%= invoice.id %>/paiement" class="payment-form">
        <input type="hidden" name="_csrf" value="<%= csrfToken %>">
        <input name="amount" placeholder="Montant">
        <input type="date" name="paid_at">
        <input name="method" placeholder="Méthode">
        <button>Ajouter un paiement</button>
      </form>
    </div>

    <form method="post" action="<%= adminBase %>/factures/<%= invoice.id %>/supprimer" class="panel danger-zone">
      <input type="hidden" name="_csrf" value="<%= csrfToken %>">
      <h2>Supprimer la facture</h2>
      <p class="muted">La suppression est bloquée si un paiement est déjà enregistré. Pour une facture payée, utilisez plutôt le statut “Annulée” si nécessaire.</p>
      <button class="secondary">Supprimer cette facture</button>
    </form>
  </section>
</div>
