<%- include('../partials/head', { title, bodyClass: 'app-page admin-page' }) %>
<%- include('../partials/app-header') %>

<main class="app-main admin-affiliation-page">
  <%- include('../partials/admin-nav') %>

  <section class="page-title">
    <p class="eyebrow">Croissance</p>
    <h1>Affiliation</h1>
    <p>Suivez les affiliés, les commissions Stripe, les remboursements négatifs et les paiements mensuels.</p>
  </section>

  <%
    const platform = affiliatePlatform || { tiers: [], affiliates: [] };
    const euro = (value) => Number(value || 0).toLocaleString('es-ES', { style: 'currency', currency: 'EUR' });
    const rate = (value) => value === null || typeof value === 'undefined' || value === '' ? '' : Number(value || 0).toFixed(2).replace(/\.00$/, '');
  %>

  <section class="glass-panel">
    <h2>Plateforme affiliée TopStats</h2>
    <p>Ces données alimentent le dashboard affilié en production : clics, inscriptions, conversions, commissions et paiements par virement bancaire.</p>
  </section>

  <section class="table-card">
    <h2>Paliers de commission</h2>
    <table>
      <thead>
        <tr>
          <th>Palier</th>
          <th>Clients actifs</th>
          <th>Taux</th>
          <th>Actif</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <% if (!platform.tiers.length) { %>
          <tr><td colspan="5">No hay ningún tramo configurado.</td></tr>
        <% } %>
        <% platform.tiers.forEach((tier) => { %>
          <tr>
            <td colspan="5">
              <form method="post" action="/admin/affiliation/platform/tiers" class="form-grid">
                <input type="hidden" name="id" value="<%= tier.id %>">
                <label>Libellé
                  <input type="text" name="label" value="<%= tier.label %>" required>
                </label>
                <label>Minimum clients actifs
                  <input type="number" name="min_active_customers" value="<%= tier.min_active_customers %>" min="1" required>
                </label>
                <label>Maximum clients actifs
                  <input type="number" name="max_active_customers" value="<%= tier.max_active_customers || '' %>" min="<%= tier.min_active_customers %>" placeholder="∞">
                </label>
                <label>Taux %
                  <input type="number" step="0.01" min="0" max="100" name="commission_rate" value="<%= rate(tier.commission_rate) %>" required>
                </label>
                <label>Actif
                  <select name="is_active">
                    <option value="1" <%= Number(tier.is_active) === 1 ? 'selected' : '' %>>Oui</option>
                    <option value="0" <%= Number(tier.is_active) !== 1 ? 'selected' : '' %>>Non</option>
                  </select>
                </label>
                <button class="btn btn-soft btn-small" type="submit">Enregistrer</button>
              </form>
            </td>
          </tr>
        <% }) %>
        <tr>
          <td colspan="5">
            <form method="post" action="/admin/affiliation/platform/tiers" class="form-grid">
              <label>Libellé
                <input type="text" name="label" placeholder="Nouveau palier" required>
              </label>
              <label>Minimum clients actifs
                <input type="number" name="min_active_customers" min="1" value="1" required>
              </label>
              <label>Maximum clients actifs
                <input type="number" name="max_active_customers" min="1" placeholder="∞">
              </label>
              <label>Taux %
                <input type="number" step="0.01" min="0" max="100" name="commission_rate" value="20" required>
              </label>
              <label>Actif
                <select name="is_active"><option value="1">Oui</option><option value="0">Non</option></select>
              </label>
              <button class="btn btn-primary btn-small" type="submit">Ajouter</button>
            </form>
          </td>
        </tr>
      </tbody>
    </table>
  </section>

  <section class="table-card">
    <h2>Affiliés dashboard production</h2>
    <table>
      <thead>
        <tr>
          <th>Affilié</th>
          <th>Tracking</th>
          <th>Revenus</th>
          <th>Validation & manager</th>
          <th>Banque</th>
          <th>Taux individuel</th>
        </tr>
      </thead>
      <tbody>
        <% if (!platform.affiliates.length) { %>
          <tr><td colspan="6">No hay ninguna cuenta afiliada en el panel por ahora.</td></tr>
        <% } %>
        <% platform.affiliates.forEach((affiliate) => { %>
          <tr>
            <td>
              <strong><%= affiliate.name %></strong><br>
              <small>
                <%= affiliate.email %><br>
                <%= affiliate.telegram || 'Telegram non renseigné' %><br>
                <%= affiliate.affiliate_id %><br>
                Statut : <strong><%= affiliate.status %></strong>
              </small>
            </td>
            <td>
              <small>
                Clics : <%= Number(affiliate.clicks || 0).toLocaleString('es-ES') %><br>
                Inscriptions : <%= Number(affiliate.signups || 0).toLocaleString('es-ES') %><br>
                Clients actifs : <%= Number(affiliate.paid_customers || 0).toLocaleString('es-ES') %>
              </small>
            </td>
            <td>
              <small>
                CA : <%= euro(affiliate.revenue) %><br>
                Commissions : <strong><%= euro(affiliate.commissions) %></strong><br>
                À payer : <strong><%= euro(affiliate.payable) %></strong>
              </small>
            </td>
            <td>
              <form method="post" action="/admin/affiliation/platform/affiliates/<%= affiliate.id %>/review" class="form-grid compact-form">
                <label>Statut
                  <select name="status">
                    <option value="pending" <%= affiliate.status === 'pending' ? 'selected' : '' %>>En attente</option>
                    <option value="active" <%= affiliate.status === 'active' ? 'selected' : '' %>>Actif</option>
                    <option value="suspended" <%= affiliate.status === 'suspended' ? 'selected' : '' %>>Suspendu</option>
                  </select>
                </label>
                <label>Manager
                  <input type="text" name="affiliate_manager_name" value="<%= affiliate.affiliate_manager_name || '' %>" placeholder="Nom manager">
                </label>
                <label>Email manager
                  <input type="email" name="affiliate_manager_email" value="<%= affiliate.affiliate_manager_email || '' %>" placeholder="manager@topstats.fr">
                </label>
                <label>Telegram manager
                  <input type="text" name="affiliate_manager_telegram" value="<%= affiliate.affiliate_manager_telegram || '' %>" placeholder="@manager">
                </label>
                <label>Note review
                  <input type="text" name="review_note" value="<%= affiliate.review_note || '' %>" placeholder="Note interne">
                </label>
                <button class="btn btn-soft btn-small" type="submit">Mettre à jour</button>
              </form>
            </td>
            <td>
              <% if (affiliate.payout_iban) { %>
                <small>
                  <%= affiliate.payout_account_holder || affiliate.name %><br>
                  <%= affiliate.payout_iban %><br>
                  <%= affiliate.payout_bic || '' %> <%= affiliate.payout_bank_name || '' %>
                </small>
              <% } else { %>
                <small>Coordonnées bancaires non renseignées</small>
              <% } %>
            </td>
            <td>
              <form method="post" action="/admin/affiliation/platform/affiliates/<%= affiliate.id %>/rate" class="inline-form">
                <input type="number" step="0.01" min="0" max="100" name="commission_rate_override" value="<%= rate(affiliate.commission_rate_override) %>" placeholder="Palier auto">
                <input type="text" name="commission_override_note" value="<%= affiliate.commission_override_note || '' %>" placeholder="Note interne">
                <button class="btn btn-soft btn-small" type="submit">Enregistrer</button>
              </form>
            </td>
          </tr>
        <% }) %>
      </tbody>
    </table>
  </section>

  <section class="glass-panel">
    <h2>Rattachement manuel</h2>
    <form method="post" action="/admin/affiliation/attach" class="form-grid">
      <label>Code affilié
        <input type="text" name="affiliate_code" placeholder="ALLAN" required>
      </label>
      <label>Usuario à rattacher
        <select name="referred_user_id" required>
          <% users.forEach((user) => { %>
            <option value="<%= user.id %>"><%= user.name %> · <%= user.email %></option>
          <% }) %>
        </select>
      </label>
      <button class="btn btn-soft" type="submit">Rattacher</button>
    </form>
  </section>

  <section class="table-card">
    <h2>Affiliés</h2>
    <table>
      <thead>
        <tr>
          <th>Affilié</th>
          <th>Lien</th>
          <th>Code promo</th>
          <th>Filleuls</th>
          <th>Total</th>
          <th>Coordonnées</th>
        </tr>
      </thead>
      <tbody>
        <% if (!affiliation.profiles.length) { %>
          <tr><td colspan="6">No hay ningún afiliado creado.</td></tr>
        <% } %>
        <% affiliation.profiles.forEach((profile) => { %>
          <tr>
            <td><strong><%= profile.name %></strong><br><small><%= profile.email %></small></td>
            <td>/r/<%= profile.slug %></td>
            <td><%= profile.promo_code %></td>
            <td><%= profile.total_referrals || 0 %></td>
            <td><strong><%= formatEuroCents(profile.total_commission_cents || 0) %></strong></td>
            <td>
              <% if (profile.iban) { %>
                <small><%= profile.account_holder || profile.name %><br><%= profile.iban %><br><%= profile.bic || '' %> <%= profile.country || '' %></small>
              <% } else { %>
                <small>Non renseignées</small>
              <% } %>
            </td>
          </tr>
        <% }) %>
      </tbody>
    </table>
  </section>

  <section class="table-card">
    <h2>Paiements mensuels</h2>
    <table>
      <thead>
        <tr>
          <th>Affilié</th>
          <th>Mois</th>
          <th>Montant</th>
          <th>Statut</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <% if (!affiliation.payouts.length) { %>
          <tr><td colspan="5">No hay pagos que mostrar.</td></tr>
        <% } %>
        <% affiliation.payouts.forEach((payout) => { %>
          <tr>
            <td><strong><%= payout.name %></strong><br><small><%= payout.email %></small></td>
            <td><%= payout.period_month %></td>
            <td><strong><%= formatEuroCents(payout.amount_cents || 0) %></strong></td>
            <td><span class="status-pill <%= payout.payout_status === 'paid' ? 'active' : '' %>"><%= payout.payout_status === 'paid' ? 'Payé' : 'À payer' %></span></td>
            <td>
              <% if (payout.payout_status !== 'paid') { %>
                <form method="post" action="/admin/affiliation/payouts/paid" class="inline-form" data-confirm="Confirmer le paiement manuel de cette période ?">
                  <input type="hidden" name="affiliate_profile_id" value="<%= payout.affiliate_profile_id %>">
                  <input type="hidden" name="period_month" value="<%= payout.period_month %>">
                  <button class="btn btn-soft btn-small" type="submit">Marquer payé</button>
                </form>
              <% } else { %>
                <small>Payé le <%= formatDate(payout.paid_at) %></small>
              <% } %>
            </td>
          </tr>
        <% }) %>
      </tbody>
    </table>
  </section>

  <section class="table-card">
    <h2>Dernières commissions</h2>
    <table>
      <thead>
        <tr>
          <th>Affilié</th>
          <th>Client</th>
          <th>Pack</th>
          <th>Net encaissé</th>
          <th>Commission</th>
          <th>Source</th>
        </tr>
      </thead>
      <tbody>
        <% if (!affiliation.commissions.length) { %>
          <tr><td colspan="6">No hay ninguna comisión guardada.</td></tr>
        <% } %>
        <% affiliation.commissions.forEach((commission) => { %>
          <tr>
            <td><%= commission.affiliate_name %></td>
            <td><%= commission.referred_name %><br><small><%= commission.referred_email %></small></td>
            <td><%= commission.plan || 'PRO' %></td>
            <td><%= formatEuroCents(commission.net_amount_cents) %></td>
            <td><strong><%= formatEuroCents(commission.commission_amount_cents) %></strong><br><small><%= Number(commission.commission_rate || 0).toFixed(0) %>%</small></td>
            <td><small><%= commission.period_month %><br><%= commission.provider_payment_id || commission.provider_event_id %></small></td>
          </tr>
        <% }) %>
      </tbody>
    </table>
  </section>
</main>

<%- include('../partials/bottom-nav') %>
<%- include('../partials/footer') %>
