<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Rapport d'opération — <%= programme.nom_commercial %></title>
  <style>
    @page {
      size: A4 portrait;
      margin: 14mm 14mm 16mm;
    }

    :root {
      --ink: #111;
      --muted: #555;
      --line: #c8c8c8;
      --soft: #f3f3f3;
      --accent: #111;
    }

    * { box-sizing: border-box; }

    html, body {
      margin: 0;
      padding: 0;
      background: #ececec;
      color: var(--ink);
      font-family: Helvetica, Arial, sans-serif;
      font-size: 9.5pt;
      line-height: 1.45;
    }

    .page {
      width: 210mm;
      min-height: 297mm;
      margin: 0 auto;
      padding: 14mm;
      background: #fff;
      box-shadow: 0 0 0 1px #ccc;
    }

    .toolbar {
      display: flex;
      justify-content: flex-end;
      gap: 0.4rem;
      margin-bottom: 8mm;
    }

    .btn {
      border: 1px solid #333;
      background: #111;
      color: #fff;
      padding: 0.4rem 0.75rem;
      font: inherit;
      font-size: 9pt;
      cursor: pointer;
      text-decoration: none;
      white-space: nowrap;
    }

    .btn-ghost {
      background: #fff;
      color: #111;
    }

    .cover {
      border-bottom: 2px solid var(--ink);
      padding-bottom: 6mm;
      margin-bottom: 7mm;
    }

    .cover-kicker {
      margin: 0 0 2mm;
      font-size: 8pt;
      letter-spacing: 0.18em;
      text-transform: uppercase;
      color: var(--muted);
    }

    .cover h1 {
      margin: 0;
      font-size: 22pt;
      font-weight: 700;
      letter-spacing: -0.02em;
      line-height: 1.05;
    }

    .cover h2 {
      margin: 1.5mm 0 0;
      font-size: 14pt;
      font-weight: 400;
    }

    .cover-meta {
      margin: 4mm 0 0;
      color: var(--muted);
      font-size: 9pt;
    }

    .cover-meta strong {
      color: var(--ink);
      font-weight: 600;
    }

    h3 {
      margin: 7mm 0 2.5mm;
      font-size: 11pt;
      font-weight: 700;
      border-bottom: 1px solid var(--line);
      padding-bottom: 1.5mm;
      page-break-after: avoid;
    }

    h4 {
      margin: 4mm 0 1.5mm;
      font-size: 9.5pt;
      font-weight: 700;
    }

    p {
      margin: 0 0 2.5mm;
      text-align: justify;
    }

    .lead {
      font-size: 10pt;
    }

    .kpis {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 2mm;
      margin: 3mm 0 5mm;
    }

    .kpi {
      border: 1px solid var(--line);
      padding: 2.5mm 3mm;
      background: var(--soft);
    }

    .kpi span {
      display: block;
      font-size: 7pt;
      text-transform: uppercase;
      letter-spacing: 0.06em;
      color: var(--muted);
      margin-bottom: 1mm;
    }

    .kpi strong {
      font-size: 11pt;
      font-variant-numeric: tabular-nums;
    }

    .comm-layout {
      display: grid;
      grid-template-columns: 42mm 1fr;
      gap: 5mm;
      align-items: center;
      margin: 3mm 0 4mm;
      page-break-inside: avoid;
    }

    .donut-wrap {
      position: relative;
      width: 40mm;
      height: 40mm;
      margin: 0 auto;
    }

    .donut {
      width: 100%;
      height: 100%;
      transform: rotate(-90deg);
    }

    .donut-track,
    .donut-seg {
      fill: none;
      stroke-width: 14;
    }

    .donut-track {
      stroke: #ececec;
    }

    .donut-seg {
      stroke-linecap: butt;
    }

    .donut-center {
      position: absolute;
      inset: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      text-align: center;
    }

    .donut-center strong {
      font-size: 12pt;
      font-weight: 700;
      line-height: 1.05;
      letter-spacing: -0.02em;
    }

    .donut-center span {
      font-size: 6.5pt;
      text-transform: uppercase;
      letter-spacing: 0.06em;
      color: var(--muted);
      margin-top: 0.8mm;
    }

    .donut-legend {
      list-style: none;
      margin: 0;
      padding: 0;
      display: flex;
      flex-direction: column;
      gap: 2mm;
    }

    .donut-legend li {
      display: grid;
      grid-template-columns: 3.5mm 1fr auto;
      gap: 2.5mm;
      align-items: center;
      font-size: 8.5pt;
    }

    .donut-swatch {
      width: 3.5mm;
      height: 3.5mm;
      display: block;
    }

    .donut-legend strong {
      font-variant-numeric: tabular-nums;
      white-space: nowrap;
    }

    .donut-pct {
      color: var(--muted);
      font-size: 8pt;
      margin-left: 1.5mm;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      table-layout: fixed;
      font-size: 8.5pt;
      margin: 0 0 3mm;
    }

    thead { display: table-header-group; }

    th, td {
      border: 0.4pt solid var(--line);
      padding: 1.4mm 2mm;
      vertical-align: middle;
      line-height: 1.25;
    }

    th {
      background: var(--soft);
      text-align: left;
      font-size: 7.5pt;
      text-transform: uppercase;
      letter-spacing: 0.04em;
    }

    tr {
      page-break-inside: avoid;
      break-inside: avoid;
    }

    .num {
      text-align: right;
      font-variant-numeric: tabular-nums;
      white-space: nowrap;
    }

    .row-total td {
      background: var(--soft);
      font-weight: 700;
    }

    .facts {
      width: 100%;
      margin: 0 0 3mm;
    }

    .facts td {
      border: none;
      border-bottom: 1px solid var(--line);
      padding: 1.6mm 0;
    }

    .facts td:first-child {
      color: var(--muted);
      width: 42%;
    }

    .facts td:last-child {
      font-weight: 600;
    }

    .statut-dispo { color: #b91c1c; }
    .statut-reserve { color: #b45309; }
    .statut-vendu { color: #15803d; }

    .footer-note {
      margin-top: 8mm;
      padding-top: 3mm;
      border-top: 1px solid var(--line);
      color: var(--muted);
      font-size: 7.5pt;
    }

    .section-block {
      page-break-inside: avoid;
    }

    @media print {
      html, body { background: #fff; }

      .page {
        width: auto;
        min-height: auto;
        margin: 0;
        padding: 0;
        box-shadow: none;
      }

      .toolbar { display: none; }

      a {
        color: inherit;
        text-decoration: none;
      }
    }

    @media screen and (max-width: 900px) {
      .page {
        width: 100%;
        min-height: auto;
        box-shadow: none;
      }

      .kpis { grid-template-columns: repeat(2, 1fr); }
    }
  </style>
</head>
<body>
  <%
    const adresse = [
      [programme.numero, programme.rue].filter(Boolean).join(' '),
      [programme.code_postal, programme.ville].filter(Boolean).join(' ')
    ].filter(Boolean).join(', ');
    const responsable = [programme.responsable_prenom, programme.responsable_nom]
      .filter(Boolean).join(' ');
    const moisNoms = [
      'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
      'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'
    ];
    const now = new Date();
    const edition = moisNoms[now.getMonth()] + ' ' + now.getFullYear();
    const byStatut = summary.byStatut || {};
    const nDispo = byStatut.dispo || 0;
    const nReserve = byStatut.reserve || 0;
    const nVendu = byStatut.vendu || 0;
    const labelStatut = { dispo: 'Dispo', reserve: 'Réservé', vendu: 'Vendu' };
  %>

  <div class="page">
    <div class="toolbar">
      <button type="button" class="btn" onclick="window.print()">Imprimer / PDF</button>
      <a class="btn btn-ghost" href="/programmes/<%= programme.id %>">Retour</a>
    </div>

    <header class="cover">
      <p class="cover-kicker">Rapport d'opération · Promotion immobilière</p>
      <h1><%= programme.nom_commercial %></h1>
      <h2>
        Programme de <%= formatInteger(summary.totalLots) %> lot<%= summary.totalLots > 1 ? 's' : '' %>
        <% if (programme.ville) { %> — <%= programme.ville %><% if (programme.code_postal) { %> (<%= String(programme.code_postal).slice(0, 2) %>)<% } %><% } %>
      </h2>
      <p class="cover-meta">
        <strong>Code</strong> <%= programme.code_interne %>
        <% if (responsable) { %> · <strong>Responsable</strong> <%= responsable %><% } %>
        · Document à usage interne
        · Édition : <%= edition %>
      </p>
    </header>

    <section class="section-block">
      <h3>1. Synthèse de l'opération</h3>
      <p class="lead">
        STOA présente l'opération <strong>« <%= programme.nom_commercial %> »</strong>,
        programme de <strong><%= formatInteger(summary.totalLots) %> lot<%= summary.totalLots > 1 ? 's' : '' %></strong>
        <% if (programme.ville) { %>situé à <strong><%= programme.ville %></strong><% } %><% if (adresse) { %>
        (<%= adresse %>)<% } %>.
        <% if (programme.surface_plancher != null) { %>
          La surface de plancher s'élève à
          <strong><%= formatNumber(programme.surface_plancher, { digits: 2 }) %> m²</strong><% if (programme.surface_terrain != null) { %>,
          pour un terrain de
          <strong><%= formatNumber(programme.surface_terrain, { digits: 2 }) %> m²</strong><% } %>.
        <% } else if (programme.surface_terrain != null) { %>
          Le terrain d'assiette représente
          <strong><%= formatNumber(programme.surface_terrain, { digits: 2 }) %> m²</strong>.
        <% } %>
      </p>
      <p>
        Le coût de revient prévisionnel s'élève à
        <strong><%= formatMoney(finances.prixRevientHt) %> € HT</strong>
        pour un chiffre d'affaires prévisionnel de
        <strong><%= formatMoney(finances.prixVenteHt) %> € HT</strong>
        (<%= formatMoney(finances.prixVenteTtc) %> € TTC),
        dégageant une marge de
        <strong><%= formatMoney(finances.margeHt) %> €</strong>
        <% if (finances.margePctCa != null) { %>
          (<%= formatNumber(finances.margePctCa, { digits: 1 }) %> % du CA HT)
        <% } %>.
        À la date du présent rapport, l'avancement commercial est de
        <strong><%= formatNumber(summary.avancementPct, { digits: 0 }) %> %</strong>
        (<%= formatInteger(summary.commercialises) %> lot<%= summary.commercialises > 1 ? 's' : '' %>
        réservé<%= summary.commercialises > 1 ? 's' : '' %> / vendu<%= summary.commercialises > 1 ? 's' : '' %>
        sur <%= formatInteger(summary.totalLots) %>).
      </p>

      <div class="kpis">
        <div class="kpi">
          <span>Lots</span>
          <strong><%= formatInteger(summary.totalLots) %></strong>
        </div>
        <div class="kpi">
          <span>CA HT</span>
          <strong><%= formatMoney(finances.prixVenteHt) %> €</strong>
        </div>
        <div class="kpi">
          <span>Marge HT</span>
          <strong><%= formatMoney(finances.margeHt) %> €</strong>
        </div>
        <div class="kpi">
          <span>Avancement</span>
          <strong><%= formatNumber(summary.avancementPct, { digits: 0 }) %> %</strong>
        </div>
      </div>
    </section>

    <section class="section-block">
      <h3>2. Présentation de l'opération</h3>
      <h4>2.1 Identification</h4>
      <table class="facts">
        <tr>
          <td>Nom commercial</td>
          <td><%= programme.nom_commercial %></td>
        </tr>
        <tr>
          <td>Code interne</td>
          <td><%= programme.code_interne %></td>
        </tr>
        <tr>
          <td>Adresse</td>
          <td><%= adresse || '—' %></td>
        </tr>
        <tr>
          <td>Responsable d'opération</td>
          <td><%= responsable || '—' %></td>
        </tr>
        <tr>
          <td>Nombre de lots</td>
          <td><%= formatInteger(summary.totalLots) %></td>
        </tr>
        <tr>
          <td>Surface de plancher</td>
          <td><%= programme.surface_plancher != null ? formatNumber(programme.surface_plancher, { digits: 2 }) + ' m²' : '—' %></td>
        </tr>
        <tr>
          <td>Surface terrain</td>
          <td><%= programme.surface_terrain != null ? formatNumber(programme.surface_terrain, { digits: 2 }) + ' m²' : '—' %></td>
        </tr>
        <tr>
          <td>Surface lots commercialisés</td>
          <td><%= formatNumber(summary.surface, { digits: 2 }) %> m²</td>
        </tr>
        <tr>
          <td>Prix moyen €/m² HT</td>
          <td><%= formatNumber(summary.prixM2, { digits: 2 }) %> €</td>
        </tr>
      </table>
    </section>

    <section class="section-block">
      <h3>3. Commercialisation</h3>
      <p>
        Répartition des lots par statut à la date du rapport.
        Objectif de suivi : lots disponibles, réservés et vendus.
      </p>

      <div class="comm-layout">
        <div class="donut-wrap" aria-hidden="true">
          <svg class="donut" viewBox="0 0 120 120">
            <circle class="donut-track" cx="60" cy="60" r="42"></circle>
            <%
              const circumference = 2 * Math.PI * 42;
              const gap = 2.5;
              let offset = 0;
              const totalLotsDonut = Math.max(summary.totalLots, 1);
              const activeCount = segments.filter(function(s) { return s.count > 0; }).length;
              segments.forEach(function(seg) {
                const length = (seg.count / totalLotsDonut) * circumference;
                const draw = (seg.count > 0 && activeCount > 1)
                  ? Math.max(0, length - gap)
                  : length;
            %>
              <circle
                class="donut-seg"
                cx="60"
                cy="60"
                r="42"
                stroke="<%= seg.color %>"
                stroke-dasharray="<%= draw.toFixed(2) %> <%= (circumference - draw).toFixed(2) %>"
                stroke-dashoffset="<%= (-offset).toFixed(2) %>"
              ></circle>
            <%
                offset += length;
              });
            %>
          </svg>
          <div class="donut-center">
            <strong><%= formatNumber(summary.avancementPct, { digits: 0 }) %>%</strong>
            <span>avancé</span>
          </div>
        </div>

        <ul class="donut-legend">
          <% segments.forEach(function(seg) { %>
            <li>
              <span class="donut-swatch" style="background: <%= seg.color %>"></span>
              <span><%= seg.label %></span>
              <span>
                <strong><%= formatInteger(seg.count) %> / <%= formatInteger(summary.totalLots) %></strong>
                <span class="donut-pct"><%= formatNumber(seg.pct, { digits: 0 }) %>%</span>
              </span>
            </li>
          <% }) %>
          <li>
            <span class="donut-swatch" style="background: #111"></span>
            <span>Taux de commercialisation</span>
            <span>
              <strong><%= formatNumber(summary.avancementPct, { digits: 0 }) %>%</strong>
              <span class="donut-pct">(réservé + vendu)</span>
            </span>
          </li>
        </ul>
      </div>

      <table>
        <thead>
          <tr>
            <th>Statut</th>
            <th class="num">Nombre</th>
            <th class="num">Part</th>
            <th class="num">Surface (m²)</th>
            <th class="num">CA HT</th>
          </tr>
        </thead>
        <tbody>
          <% segments.forEach(function(seg) { %>
            <tr>
              <td class="statut-<%= seg.value %>"><%= seg.label %></td>
              <td class="num"><%= formatInteger(seg.count) %> / <%= formatInteger(summary.totalLots) %></td>
              <td class="num"><%= formatNumber(seg.pct, { digits: 0 }) %> %</td>
              <td class="num"><%= formatNumber(seg.surface, { digits: 2 }) %></td>
              <td class="num"><%= formatMoney(seg.ca) %> €</td>
            </tr>
          <% }) %>
          <tr class="row-total">
            <td>Total</td>
            <td class="num"><%= formatInteger(summary.totalLots) %></td>
            <td class="num">100 %</td>
            <td class="num"><%= formatNumber(summary.surface, { digits: 2 }) %></td>
            <td class="num"><%= formatMoney(summary.prixHt) %> €</td>
          </tr>
        </tbody>
      </table>
      <p>
        Dont <strong><%= formatInteger(nDispo) %></strong> dispo,
        <strong><%= formatInteger(nReserve) %></strong> réservé<%= nReserve > 1 ? 's' : '' %>,
        <strong><%= formatInteger(nVendu) %></strong> vendu<%= nVendu > 1 ? 's' : '' %>.
      </p>
    </section>

    <section class="section-block">
      <h3>4. Bilan financier prévisionnel</h3>
      <h4>4.1 Coût de revient</h4>
      <table>
        <thead>
          <tr>
            <th>Poste</th>
            <th class="num">Montant HT</th>
            <th class="num">% du total</th>
          </tr>
        </thead>
        <tbody>
          <% finances.couts.forEach(function(row) { %>
            <tr class="<%= row.isTotal ? 'row-total' : '' %>">
              <td><%= row.label %></td>
              <td class="num"><%= formatMoney(row.ht) %> €</td>
              <td class="num">
                <%= row.pct != null ? formatNumber(row.pct, { digits: 1 }) + ' %' : '—' %>
              </td>
            </tr>
          <% }) %>
        </tbody>
      </table>

      <h4>4.2 Compte de résultat prévisionnel</h4>
      <table>
        <thead>
          <tr>
            <th>Indicateur</th>
            <th class="num">Montant</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Chiffre d'affaires prévisionnel TTC</td>
            <td class="num"><%= formatMoney(finances.prixVenteTtc) %> €</td>
          </tr>
          <tr>
            <td>Chiffre d'affaires HT</td>
            <td class="num"><%= formatMoney(finances.prixVenteHt) %> €</td>
          </tr>
          <tr>
            <td>Coût de revient total HT</td>
            <td class="num"><%= formatMoney(finances.prixRevientHt) %> €</td>
          </tr>
          <tr class="row-total">
            <td>Marge brute HT</td>
            <td class="num"><%= formatMoney(finances.margeHt) %> €</td>
          </tr>
          <tr>
            <td>Taux de marge / CA HT</td>
            <td class="num">
              <%= finances.margePctCa != null ? formatNumber(finances.margePctCa, { digits: 1 }) + ' %' : '—' %>
            </td>
          </tr>
          <tr>
            <td>Taux de marge / prix de revient</td>
            <td class="num">
              <%= finances.margePctRevient != null ? formatNumber(finances.margePctRevient, { digits: 1 }) + ' %' : '—' %>
            </td>
          </tr>
          <tr>
            <td>TVA résiduelle</td>
            <td class="num"><%= formatMoney(finances.tvaResiduelle) %> €</td>
          </tr>
        </tbody>
      </table>
    </section>

    <section>
      <h3>5. Détail des lots</h3>
      <% if (!lots.length) { %>
        <p>Aucun lot paramétré pour cette opération.</p>
      <% } else { %>
        <table>
          <thead>
            <tr>
              <th style="width:10%">Lot</th>
              <th>Désignation</th>
              <th style="width:14%">Statut</th>
              <th class="num" style="width:16%">Surface</th>
              <th class="num" style="width:18%">Prix HT</th>
              <th class="num" style="width:14%">€/m²</th>
            </tr>
          </thead>
          <tbody>
            <% lots.forEach(function(lot) { %>
              <tr>
                <td><%= lot.numero %></td>
                <td><%= lot.designation || '—' %></td>
                <td class="statut-<%= lot.statut %>"><%= labelStatut[lot.statut] || lot.statut %></td>
                <td class="num"><%= formatNumber(lot.surface, { digits: 2 }) %></td>
                <td class="num"><%= formatMoney(lot.prix_ht) %></td>
                <td class="num"><%= formatNumber(lot.prix_m2, { digits: 2 }) %></td>
              </tr>
            <% }) %>
            <tr class="row-total">
              <td colspan="3">Total</td>
              <td class="num"><%= formatNumber(summary.surface, { digits: 2 }) %></td>
              <td class="num"><%= formatMoney(summary.prixHt) %></td>
              <td class="num"><%= formatNumber(summary.prixM2, { digits: 2 }) %></td>
            </tr>
          </tbody>
        </table>
      <% } %>
    </section>

    <p class="footer-note">
      Rapport d'opération généré automatiquement par STOA — <%= edition %>.
      Document à usage interne. Les montants sont issus du bilan prévisionnel et du détail des lots.
    </p>
  </div>
</body>
</html>
