<% layout('layouts/main') %>
<% const adminBase = typeof adminBaseUrl !== 'undefined' ? adminBaseUrl : '/admin'; %>
<% const f = fiduciary || {}; %>
<% const permissionOptions = f.permissionOptions || []; %>
<% const categoryLabel = (value) => ui.label(String(value || '').replace(/_/g, ' ')); %>
<div class="app-shell">
  <%- partial('partials/admin-nav') %>
  <section class="content advanced-module-page fiduciary-admin-page">
    <div class="page-head compact-page-head">
      <div>
        <p class="eyebrow">Portail fiduciaire</p>
        <h1>Transmettre un dossier mensuel clair, limité et sécurisé.</h1>
        <p class="muted">Accès lecture seule, périodes visibles, permissions serveur, dépenses avec justificatifs et exports prêts pour la fiduciaire.</p>
      </div>
      <div class="actions">
        <a class="button secondary" href="<%= adminBase %>/fiduciaire/exports/advanced.csv?month=<%= f.month %>">Export complet</a>
        <a class="button secondary" href="<%= adminBase %>/fiduciaire/exports/hours.csv?month=<%= f.month %>">Heures CSV</a>
      </div>
    </div>

    <section class="suite-command-grid advanced-kpis">
      <article><span>CA facturé</span><strong><%= ui.money(f.stats.invoiced || 0) %></strong><small>Période <%= f.month %></small></article>
      <article><span>Payé</span><strong><%= ui.money(f.stats.paid || 0) %></strong><small>Encaissements rapprochés</small></article>
      <article><span>Impayé</span><strong><%= ui.money(f.stats.unpaid || 0) %></strong><small>À contrôler</small></article>
      <article><span>Dépenses</span><strong><%= ui.money(f.stats.expenses || 0) %></strong><small>Achats et justificatifs</small></article>
      <article><span>Bénéfice estimatif</span><strong><%= ui.money(f.stats.estimatedProfit || 0) %></strong><small>Non fiscal, à valider</small></article>
      <article><span>TVA estimée</span><strong><%= ui.money(f.stats.vatEstimate || 0) %></strong><small>Préparation simple</small></article>
      <article><span>Heures employés</span><strong><%= ui.duration(f.stats.hours || 0) %></strong><small>Préparation salaires</small></article>
      <article><span>Pièces manquantes</span><strong><%= f.stats.missingDocuments || 0 %></strong><small>Justificatifs à compléter</small></article>
    </section>

    <section class="panel compact-panel">
      <form method="get" class="form-grid two">
        <label>Période mensuelle<input type="month" name="month" value="<%= f.month %>"></label>
        <div class="filter-actions"><button>Actualiser</button><a class="button secondary" href="<%= adminBase %>/fiduciaire">Mois courant</a></div>
      </form>
    </section>

    <div class="advanced-admin-grid" data-module-workspace data-module-workspace-label="Fiduciaire">
      <details class="panel suite-module-drawer" id="acces">
        <summary class="suite-module-title"><div><p class="eyebrow">Accès fiduciaire</p><h2>Invitation, période visible et permissions.</h2></div><span class="suite-module-toggle">Ouvrir</span></summary>
        <form method="post" action="<%= adminBase %>/fiduciaire/acces" class="form-grid compact">
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <div class="form-grid two"><label>Email fiduciaire<input type="email" name="email" required></label><label>Cabinet<input name="fiduciary_company" placeholder="Nom de la fiduciaire"></label></div>
          <div class="form-grid three"><label>Contact<input name="contact_name"></label><label>Visible dès<input type="date" name="period_from"></label><label>Visible jusqu’à<input type="date" name="period_to"></label></div>
          <div class="checkbox-row">
            <% permissionOptions.forEach(([key, label]) => { %><label class="check"><input type="checkbox" name="perm_<%= key %>" checked><span><%= label %></span></label><% }) %>
          </div>
          <button>Créer l’accès fiduciaire</button>
        </form>
        <div class="compact-list">
          <% (f.fiduciaries || []).forEach((item) => { %>
            <article class="list-card slim-card">
              <div class="list-card-head">
                <div><strong><%= item.fiduciary_company || `${item.first_name} ${item.last_name}` %></strong><span><%= item.email %> · <%= ui.label(item.status) %></span></div>
                <span class="badge"><%= item.period_from || 'Début' %> → <%= item.period_to || 'Aujourd’hui' %></span>
              </div>
              <details class="inline-edit-drawer">
                <summary>Modifier permissions</summary>
                <form method="post" action="<%= adminBase %>/fiduciaire/acces/<%= item.id %>" class="form-grid compact">
                  <input type="hidden" name="_csrf" value="<%= csrfToken %>">
                  <div class="form-grid three"><label>Visible dès<input type="date" name="period_from" value="<%= ui.dateInput(item.period_from) %>"></label><label>Visible jusqu’à<input type="date" name="period_to" value="<%= ui.dateInput(item.period_to) %>"></label><label>Statut<select name="status"><option value="active" <%= item.status==='active'?'selected':'' %>>Actif</option><option value="disabled" <%= item.status==='disabled'?'selected':'' %>>Désactivé</option></select></label></div>
                  <div class="checkbox-row"><% permissionOptions.forEach(([key, label]) => { %><label class="check"><input type="checkbox" name="perm_<%= key %>" checked><span><%= label %></span></label><% }) %></div>
                  <button class="secondary">Mettre à jour</button>
                </form>
              </details>
            </article>
          <% }) %>
          <% if (!(f.fiduciaries || []).length) { %><div class="empty-state slim"><strong>Aucun accès fiduciaire</strong><span>Invitez le cabinet qui récupère vos exports mensuels.</span></div><% } %>
        </div>
      </details>

      <details class="panel suite-module-drawer" id="depenses">
        <summary class="suite-module-title"><div><p class="eyebrow">Dépenses / justificatifs</p><h2>Saisie propre pour le dossier mensuel.</h2></div><span class="suite-module-toggle">Ouvrir</span></summary>
        <form method="post" action="<%= adminBase %>/fiduciaire/depenses" enctype="multipart/form-data" class="form-grid compact">
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <div class="form-grid three"><label>Date<input type="date" name="expense_date" required></label><label>Fournisseur<input name="supplier" required></label><label>Catégorie<select name="category"><% (f.expenseCategories || []).forEach((cat) => { %><option value="<%= cat %>"><%= categoryLabel(cat) %></option><% }) %></select></label></div>
          <div class="form-grid four"><label>HT<input type="number" step="0.01" name="amount_excl_vat"></label><label>TVA %<input type="number" step="0.01" name="vat_rate" value="8.1"></label><label>TVA CHF<input type="number" step="0.01" name="vat_amount"></label><label>TTC<input type="number" step="0.01" name="amount_incl_vat"></label></div>
          <div class="form-grid three"><label>Paiement<input name="payment_method" placeholder="Carte, virement, cash"></label><label>Statut<select name="status"><option value="complete">Complet</option><option value="missing_receipt">Justificatif manquant</option><option value="to_check">À vérifier</option></select></label><label>Justificatif<input type="file" name="attachment" accept=".pdf,image/*"></label></div>
          <label>Note<textarea name="note" rows="2"></textarea></label>
          <button>Ajouter dépense</button>
        </form>
        <div class="table-wrap compact-table-wrap">
          <table><thead><tr><th>Date</th><th>Fournisseur</th><th>Catégorie</th><th>TTC</th><th>Statut</th></tr></thead><tbody>
            <% (f.expenses || []).forEach((item) => { %><tr><td><%= ui.date(item.expense_date) %></td><td><%= item.supplier %></td><td><%= categoryLabel(item.category) %></td><td><%= ui.money(item.amount_incl_vat) %></td><td><span class="badge"><%= ui.label(item.status) %></span></td></tr><% }) %>
          </tbody></table>
        </div>
      </details>

      <details class="panel suite-module-drawer" id="documents">
        <summary class="suite-module-title"><div><p class="eyebrow">Documents administratifs</p><h2>Contrats, attestations, TVA et extraits.</h2></div><span class="suite-module-toggle">Ouvrir</span></summary>
        <form method="post" action="<%= adminBase %>/fiduciaire/documents" enctype="multipart/form-data" class="form-grid compact">
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <div class="form-grid three"><label>Type<select name="document_type"><option value="employee_contract">Contrat employé</option><option value="liability_insurance">Assurance RC</option><option value="vat">Documents TVA</option><option value="certificate">Attestation</option><option value="statement">Extrait</option><option value="other">Autre</option></select></label><label>Titre<input name="title" required></label><label>Période<input type="month" name="period_month" value="<%= f.month %>"></label></div>
          <label>Fichier<input type="file" name="document_file" accept=".pdf,image/*"></label>
          <label>Notes<textarea name="notes" rows="2"></textarea></label>
          <button>Ajouter document</button>
        </form>
        <div class="compact-list">
          <% (f.docs || []).forEach((item) => { %><article class="line-card"><strong><%= item.title %></strong><span><%= ui.label(item.document_type) %> · <%= item.period_month || 'Sans période' %></span><b><%= ui.label(item.visibility) %></b></article><% }) %>
          <% if (!(f.docs || []).length) { %><div class="empty-state slim"><strong>Aucun document</strong><span>Ajoutez les pièces accessibles à la fiduciaire.</span></div><% } %>
        </div>
      </details>

      <details class="panel suite-module-drawer" id="heures">
        <summary class="suite-module-title"><div><p class="eyebrow">Préparation salaires</p><h2>Vue mensuelle des heures et frais.</h2></div><span class="suite-module-toggle">Ouvrir</span></summary>
        <div class="table-wrap compact-table-wrap">
          <table><thead><tr><th>Employé</th><th>Heures effectuées</th><th>Frais</th><th>Notes</th></tr></thead><tbody>
            <% (f.hours || []).forEach((row) => { %>
              <tr><td><%= row.first_name %> <%= row.last_name %></td><td><%= ui.duration(row.minutes || 0) %></td><td><%= ui.money(row.expenses || 0) %></td><td>Préparation salaires, non paie officielle.</td></tr>
            <% }) %>
          </tbody></table>
        </div>
      </details>

      <details class="panel suite-module-drawer" id="exports">
        <summary class="suite-module-title"><div><p class="eyebrow">Exports</p><h2>CSV, rapports mensuels et TVA simple.</h2></div><span class="suite-module-toggle">Ouvrir</span></summary>
        <div class="suite-module-actions">
          <a class="button secondary" href="<%= adminBase %>/fiduciaire/exports/invoices.csv?month=<%= f.month %>">Factures CSV</a>
          <a class="button secondary" href="<%= adminBase %>/fiduciaire/exports/expenses.csv?month=<%= f.month %>">Dépenses CSV</a>
          <a class="button secondary" href="<%= adminBase %>/fiduciaire/exports/hours.csv?month=<%= f.month %>">Heures CSV</a>
          <a class="button secondary" href="<%= adminBase %>/fiduciaire/exports/advanced.csv?month=<%= f.month %>">Export fiduciaire avancé</a>
        </div>
        <div class="compact-list">
          <% (f.exports || []).forEach((item) => { %><article class="line-card"><strong><%= item.export_type %></strong><span><%= item.period_from || 'Début' %> → <%= item.period_to || 'Aujourd’hui' %></span><b><%= ui.label(item.status) %></b></article><% }) %>
        </div>
      </details>
    </div>
  </section>
</div>
