<% layout('layouts/main') %>
<% const pricingValues = typeof pricing !== 'undefined' ? pricing : {
  quote_price_end_room: 55,
  quote_price_end_kitchen: 150,
  quote_price_end_bathroom: 70,
  quote_price_end_windows: 120,
  quote_price_end_blinds: 90,
  quote_price_end_balcony: 60,
  quote_price_end_cellar_garage: 50,
  quote_price_window_inside: 10,
  quote_price_window_inside_outside: 15,
  quote_price_blind: 8,
  quote_price_difficult_access: 40,
  quote_price_regular_hourly: 40
}; %>
<% const settingMap = Object.fromEntries(settingRows.map((row) => [row.name, row.value || ''])); %>
<% const currentCompanySettings = typeof company !== 'undefined' ? company : currentCompany; %>
<% const adminBase = typeof adminBaseUrl !== 'undefined' ? adminBaseUrl : '/admin'; %>
<% const clientBase = typeof clientBaseUrl !== 'undefined' ? clientBaseUrl : '/client'; %>
<% const staffBase = typeof staffBaseUrl !== 'undefined' ? staffBaseUrl : '/agenda'; %>
<% const companySlug = currentCompanySettings?.slug || 'saas-demo'; %>
<% const publicSiteUrl = companySlug === 'saas-demo' ? '/demo/saas-demo' : `/site/${companySlug}`; %>
<% const domainRows = typeof domains !== 'undefined' ? domains : []; %>
<% const assistantItems = typeof assistantCatalog !== 'undefined' ? assistantCatalog : []; %>
<% const profiles = typeof accessProfiles !== 'undefined' ? accessProfiles : []; %>
<% const customProfiles = typeof customAccessProfiles !== 'undefined' ? customAccessProfiles : []; %>
<% const capabilityRows = typeof capabilityLabels !== 'undefined' ? capabilityLabels : []; %>
<div class="app-shell">
  <%- partial('partials/admin-nav') %>
  <section class="content settings-hub-page">
    <div class="page-head compact-page-head">
      <div>
        <p class="eyebrow">Configuration</p>
        <h1>Paramètres entreprise</h1>
        <p class="muted">Uniquement les réglages structurels. Les textes, pages, photos et blocs du site se gèrent dans le Studio.</p>
      </div>
      <div class="actions">
        <a class="button secondary" href="<%= adminBase %>/studio">Studio</a>
        <a class="button secondary" href="<%= publicSiteUrl %>" target="_blank" rel="noopener">Voir le site</a>
      </div>
    </div>

    <section class="settings-quick-grid settings-hub-nav">
      <a href="#identite"><span><%- ui.navIcon('home') %></span><strong>Identité</strong><small>Marque, TVA, zones</small></a>
      <a href="#acces"><span><%- ui.navIcon('lock') %></span><strong>Liens</strong><small>Espaces et domaines</small></a>
      <a href="#banque"><span><%- ui.navIcon('bank') %></span><strong>Banque</strong><small>QR-factures</small></a>
      <a href="#devis"><span><%- ui.navIcon('receipt') %></span><strong>Assistant devis</strong><small>Lignes et prix</small></a>
      <a href="#droits"><span><%- ui.navIcon('team') %></span><strong>Rangs</strong><small>Droits d’accès</small></a>
      <a href="#avis-google"><span><%- ui.navIcon('star') %></span><strong>Avis Google</strong><small>Lien public</small></a>
      <a href="<%= adminBase %>/parametres/abonnement"><span><%- ui.navIcon('wallet') %></span><strong>Abonnement</strong><small>Plan et sièges</small></a>
    </section>

    <details id="identite" class="panel settings-drawer settings-section-panel">
      <summary><span><strong>Identité & légal</strong><small>Informations utilisées sur les documents, emails et espaces connectés</small></span><span class="badge">Entreprise</span></summary>
      <form method="post" action="<%= adminBase %>/parametres/identite" enctype="multipart/form-data" class="form-grid settings-inner-form">
        <input type="hidden" name="_csrf" value="<%= csrfToken %>">
        <input type="hidden" name="current_logo_path" value="<%= currentCompanySettings.logo_path || '' %>">
        <div class="form-grid two">
          <label>Nom commercial<input name="business_name" value="<%= currentCompanySettings.name || settingMap.business_name || '' %>" required></label>
          <label>Raison sociale<input name="legal_name" value="<%= currentCompanySettings.legal_name || currentCompanySettings.name || '' %>"></label>
        </div>
        <div class="form-grid two">
          <label>Email public<input type="email" name="business_email" value="<%= currentCompanySettings.email || settingMap.business_email || '' %>"></label>
          <label>Téléphone public<input name="business_phone" value="<%= currentCompanySettings.phone || settingMap.business_phone || '' %>"></label>
        </div>
        <label>Adresse publique<textarea name="business_address"><%= currentCompanySettings.address || settingMap.business_address || '' %></textarea></label>
        <div class="form-grid four">
          <label>Couleur principale<input type="color" name="primary_color" value="<%= currentCompanySettings.primary_color || '#0b6b88' %>"></label>
          <label>Couleur secondaire<input type="color" name="secondary_color" value="<%= currentCompanySettings.secondary_color || '#20b86c' %>"></label>
          <label>TVA<input name="vat_rate" value="<%= currentCompanySettings.vat_rate || settingMap.vat_rate || '' %>" inputmode="decimal"></label>
          <label>Libellé TVA<input name="vat_label" value="<%= currentCompanySettings.vat_label || settingMap.vat_label || 'TVA non applicable' %>"></label>
        </div>
        <div class="form-grid two">
          <label>Logo<% if (currentCompanySettings.logo_path) { %><span class="muted">Logo actuel configuré</span><% } %><input type="file" name="logo" accept="image/png,image/jpeg,image/webp"></label>
          <label>Site externe<input name="website_url" value="<%= currentCompanySettings.website_url || '' %>" placeholder="https://..."></label>
        </div>
        <label>Zones desservies<textarea name="service_zones" placeholder="Lausanne, Morges, Nyon"><%= settingMap.service_zones || '' %></textarea></label>
        <label class="check auth-check"><input type="checkbox" name="vat_enabled" <%= currentCompanySettings.vat_enabled || settingMap.vat_enabled === 'true' ? 'checked' : '' %>><span>Entreprise assujettie à la TVA</span></label>
        <label>IBAN principal<input name="iban" value="<%= currentCompanySettings.iban || settingMap.business_iban || '' %>"></label>
        <button>Enregistrer l’identité</button>
      </form>
    </details>

    <details id="acces" class="panel settings-drawer settings-section-panel">
      <summary><span><strong>Domaines & liens</strong><small>Site, administration, espace client, espace employé et domaines personnalisés</small></span><span class="badge">Accès</span></summary>
      <div class="settings-inner-form">
        <div class="domain-link-grid">
          <a href="<%= publicSiteUrl %>" target="_blank" rel="noopener"><span>Site public</span><strong><%= publicSiteUrl %></strong></a>
          <a href="<%= adminBase %>"><span>Administration</span><strong><%= adminBase %></strong></a>
          <a href="<%= clientBase %>"><span>Espace client</span><strong><%= clientBase %></strong></a>
          <a href="<%= staffBase %>"><span>Espace employé</span><strong><%= staffBase %></strong></a>
        </div>
        <form method="post" action="<%= adminBase %>/parametres/domaines" class="form-grid domain-form">
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <label>Domaine personnalisé<input name="hostname" placeholder="www.votre-domaine.ch" autocomplete="off"></label>
          <button>Ajouter le domaine</button>
        </form>
        <p class="field-help">Configuration attendue: CNAME vers la plateforme SaaS, puis validation du statut depuis l’administration SaaS.</p>
        <div class="mobile-list compact-list domain-list">
          <% domainRows.forEach((domain) => { %>
            <article class="list-card">
              <div class="list-card-head">
                <div><strong><%= domain.hostname %></strong><span><%= domain.type === 'custom' ? 'Domaine personnalisé' : 'Sous-domaine SaaS' %></span></div>
                <span class="badge"><%= domain.status === 'active' ? 'Actif' : (domain.status === 'disabled' ? 'Désactivé' : 'En attente') %></span>
              </div>
              <% if (domain.status !== 'disabled') { %>
                <form method="post" action="<%= adminBase %>/parametres/domaines/<%= domain.id %>/desactiver" data-confirm="Désactiver ce domaine ?">
                  <input type="hidden" name="_csrf" value="<%= csrfToken %>">
                  <button class="secondary">Désactiver</button>
                </form>
              <% } %>
            </article>
          <% }) %>
          <% if (!domainRows.length) { %><div class="empty-state slim"><strong>Aucun domaine personnalisé</strong><span>Le lien SaaS est utilisable immédiatement. Le domaine client peut être ajouté plus tard.</span></div><% } %>
        </div>
      </div>
    </details>

    <details id="banque" class="panel settings-drawer settings-section-panel">
      <summary><span><strong>Banque & QR-facture</strong><small>Comptes bancaires utilisés pour les factures et QR-factures</small></span><span class="badge"><%= bankAccounts.length %></span></summary>
      <section class="settings-two-column settings-inner-form">
        <section class="panel compact-panel">
          <div class="compact-heading"><p class="eyebrow">Comptes</p><h2>Comptes actifs</h2></div>
          <div class="mobile-list compact-list">
            <% bankAccounts.forEach(account => { %>
              <article class="list-card">
                <div class="list-card-head">
                  <div><strong><%= account.label %></strong><span><%= account.holder_name %> · <%= account.iban %></span></div>
                  <span class="badge"><%= account.is_active ? (account.is_default ? 'Par défaut' : 'Actif') : 'Désactivé' %></span>
                </div>
                <p><%= account.holder_street %> <%= account.holder_building_no || '' %>, <%= account.holder_postal_code %> <%= account.holder_city %></p>
                <% if (account.is_active) { %>
                  <form method="post" action="<%= adminBase %>/parametres/comptes-bancaires/<%= account.id %>/desactiver">
                    <input type="hidden" name="_csrf" value="<%= csrfToken %>">
                    <button class="secondary">Désactiver</button>
                  </form>
                <% } %>
              </article>
            <% }) %>
            <% if (!bankAccounts.length) { %><div class="empty-state slim"><strong>Aucun compte bancaire</strong><span>Ajoutez le compte utilisé pour vos QR-factures.</span></div><% } %>
          </div>
        </section>
        <form method="post" action="<%= adminBase %>/parametres/comptes-bancaires" class="panel compact-panel form-grid">
          <div class="compact-heading"><p class="eyebrow">Nouveau</p><h2>Ajouter un compte</h2></div>
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <div class="form-grid two"><label>Libellé interne<input name="label" placeholder="Compte principal" required></label><label>Banque<input name="bank_name" placeholder="Nom de la banque"></label></div>
          <label>Titulaire du compte<input name="holder_name" placeholder="<%= currentCompanySettings.name || 'Votre entreprise' %>" required></label>
          <div class="form-grid two"><label>Rue<input name="holder_street" required></label><label>N°<input name="holder_building_no"></label></div>
          <div class="form-grid two"><label>NPA<input name="holder_postal_code" required></label><label>Ville<input name="holder_city" required></label></div>
          <div class="form-grid two"><label>Pays<input name="holder_country" value="CH" maxlength="2" required></label><label>IBAN<input name="iban" placeholder="CH..." required></label></div>
          <label class="check premium-check"><input type="checkbox" name="is_default" checked><span><strong>Compte par défaut</strong><small>Choisi automatiquement pour les prochaines factures.</small></span></label>
          <button>Ajouter</button>
        </form>
      </section>
    </details>

    <details id="devis" class="panel settings-drawer settings-section-panel">
      <summary><span><strong>Assistant devis</strong><small>Éléments, unités et prix propres à cette entreprise</small></span><span class="badge"><%= assistantItems.length %></span></summary>
      <div class="settings-inner-form settings-two-column wide-left">
        <section class="panel compact-panel">
          <div class="compact-heading"><p class="eyebrow">Bibliothèque</p><h2>Éléments disponibles dans les devis</h2></div>
          <div class="settings-list-table">
            <% assistantItems.forEach((item) => { %>
              <article>
                <div>
                  <strong><%= item.label %></strong>
                  <span><%= item.service_type %> · <%= item.unit %> · CHF <%= Number(item.price || 0).toFixed(2) %></span>
                  <small>Quantité: <%= item.quantity_field || 'fixe' %><%= item.condition_field ? ` · Condition: ${item.condition_field}` : '' %></small>
                </div>
                <form method="post" action="<%= adminBase %>/parametres/assistant-elements/<%= item.id %>/supprimer" data-confirm="Supprimer cet élément de l’assistant devis ?">
                  <input type="hidden" name="_csrf" value="<%= csrfToken %>">
                  <button class="secondary small">Supprimer</button>
                </form>
              </article>
            <% }) %>
          </div>
        </section>
        <section class="panel compact-panel">
          <div class="compact-heading"><p class="eyebrow">Ajouter</p><h2>Nouvel élément</h2></div>
          <form method="post" action="<%= adminBase %>/parametres/assistant-elements" class="form-grid compact">
            <input type="hidden" name="_csrf" value="<%= csrfToken %>">
            <div class="form-grid two"><label>Nom<input name="label" placeholder="Fenêtre, cuisine, surface m²..." required></label><label>Service<select name="service_type"><option>Tous les services</option><option>Nettoyage régulier</option><option>Nettoyage fin de bail</option><option>Nettoyage de vitres</option><option>Nettoyage après travaux</option><option>Conciergerie</option></select></label></div>
            <div class="form-grid three"><label>Unité<select name="unit"><option value="forfait">Forfait</option><option value="heure">Heure</option><option value="m2">m²</option><option value="piece">Pièce</option><option value="fenetre">Fenêtre</option><option value="store">Store</option><option value="deplacement">Déplacement</option></select></label><label>Prix CHF<input name="price" inputmode="decimal" required></label><label>Quantité par défaut<input name="default_quantity" value="1" inputmode="decimal"></label></div>
            <div class="form-grid two"><label>Champ quantité optionnel<input name="quantity_field" placeholder="rooms, surface, windows_count..."></label><label>Champ condition optionnel<input name="condition_field" placeholder="end_windows, blinds..."></label></div>
            <label class="check premium-check small"><input type="checkbox" name="enabled" checked><span><strong>Actif</strong><small>Disponible dans les devis et suggestions automatiques.</small></span></label>
            <button>Ajouter l’élément</button>
          </form>
        </section>
      </div>
      <form method="post" class="settings-inner-form form-grid pricing-settings">
        <input type="hidden" name="_csrf" value="<%= csrfToken %>">
        <div class="settings-group">
          <h3>Prix par défaut historiques</h3>
          <p class="muted">Ces valeurs restent utilisées par les modèles existants et les éléments par défaut.</p>
          <div class="form-grid four">
            <label>Pièce / zone<input name="quote_price_end_room" value="<%= pricingValues.quote_price_end_room %>" inputmode="decimal"></label>
            <label>Cuisine<input name="quote_price_end_kitchen" value="<%= pricingValues.quote_price_end_kitchen %>" inputmode="decimal"></label>
            <label>Sanitaire<input name="quote_price_end_bathroom" value="<%= pricingValues.quote_price_end_bathroom %>" inputmode="decimal"></label>
            <label>Vitres forfait<input name="quote_price_end_windows" value="<%= pricingValues.quote_price_end_windows %>" inputmode="decimal"></label>
            <label>Stores forfait<input name="quote_price_end_blinds" value="<%= pricingValues.quote_price_end_blinds %>" inputmode="decimal"></label>
            <label>Balcon<input name="quote_price_end_balcony" value="<%= pricingValues.quote_price_end_balcony %>" inputmode="decimal"></label>
            <label>Cave / garage<input name="quote_price_end_cellar_garage" value="<%= pricingValues.quote_price_end_cellar_garage %>" inputmode="decimal"></label>
            <label>Tarif horaire<input name="quote_price_regular_hourly" value="<%= pricingValues.quote_price_regular_hourly %>" inputmode="decimal"></label>
          </div>
        </div>
        <button>Enregistrer les prix</button>
      </form>
    </details>

    <details id="droits" class="panel settings-drawer settings-section-panel">
      <summary><span><strong>Rangs & droits d’accès</strong><small>Créer des profils comme RH, comptable, chef d’équipe ou sous-direction</small></span><span class="badge"><%= profiles.length %></span></summary>
      <div class="settings-inner-form settings-two-column">
        <section class="panel compact-panel">
          <div class="compact-heading"><p class="eyebrow">Profils</p><h2>Rangs disponibles</h2></div>
          <div class="settings-list-table access-profile-list">
            <% profiles.forEach((profile) => { %>
              <article>
                <div>
                  <strong><%= profile.label %></strong>
                  <span><%= profile.detail %></span>
                  <small><%= (profile.capabilities || []).map((cap) => (capabilityRows.find(([key]) => key === cap) || [cap, cap])[1]).join(', ') || 'Aucun droit' %></small>
                </div>
                <% if (profile.custom) { %>
                  <form method="post" action="<%= adminBase %>/parametres/rangs/<%= profile.id %>/supprimer" data-confirm="Supprimer ce rang personnalisé ?">
                    <input type="hidden" name="_csrf" value="<%= csrfToken %>">
                    <button class="secondary small">Supprimer</button>
                  </form>
                <% } else { %><span class="badge">Standard</span><% } %>
              </article>
            <% }) %>
          </div>
        </section>
        <form method="post" action="<%= adminBase %>/parametres/rangs" class="panel compact-panel form-grid">
          <div class="compact-heading"><p class="eyebrow">Nouveau rang</p><h2>Créer un profil d’accès</h2></div>
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <div class="form-grid two"><label>Nom du rang<input name="label" placeholder="Sous-direction" required></label><label>Description<input name="detail" placeholder="Accès complet hors réglages sensibles"></label></div>
          <div class="permission-check-grid">
            <% capabilityRows.forEach(([key, label]) => { %>
              <label class="check"><input type="checkbox" name="capabilities" value="<%= key %>"><span><%= label %></span></label>
            <% }) %>
          </div>
          <button>Créer le rang</button>
        </form>
      </div>
    </details>

    <details id="avis-google" class="panel settings-drawer settings-section-panel">
      <summary><span><strong>Avis Google</strong><small>Lien utilisé quand la demande d’avis est cochée à l’envoi d’une facture</small></span><span class="badge">Email</span></summary>
      <form method="post" class="settings-inner-form form-grid">
        <input type="hidden" name="_csrf" value="<%= csrfToken %>">
        <label>Lien de la page Google Avis<input name="google_review_url" value="<%= settingMap.google_review_url || '' %>" placeholder="https://g.page/r/.../review"></label>
        <p class="field-help">La demande d’avis n’est pas automatique sur toutes les factures. Elle part uniquement si l’option est cochée au moment de l’envoi.</p>
        <button>Enregistrer le lien Google Avis</button>
      </form>
    </details>

    <script>
      (() => {
        const openFromHash = () => {
          const id = decodeURIComponent(window.location.hash || '').replace('#', '');
          if (!id) return;
          const panel = document.getElementById(id);
          if (panel && panel.tagName === 'DETAILS') panel.open = true;
        };
        document.querySelectorAll('.settings-quick-grid a[href^="#"]').forEach((link) => {
          link.addEventListener('click', () => {
            const panel = document.querySelector(link.getAttribute('href'));
            if (panel && panel.tagName === 'DETAILS') panel.open = true;
          });
        });
        window.addEventListener('hashchange', openFromHash);
        openFromHash();
      })();
    </script>
  </section>
</div>
