<?php
$h=fn($v)=>htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');
$page=$template['page_config']??[];
$groups=[];
foreach($variables as $v){$token=(string)($v['token']??'');$clean=trim($token,'{} ');$parts=explode('.',$clean,2);$group=count($parts)>1?ucfirst($parts[0]):'Général';$groups[$group][]=$v;}
$templateId=(int)($template['id']??0);
?>
<main class="axiom-studio-page document-designer ax-studio-shell">
  <header class="ax-topbar">
    <div class="ax-brandline"><span class="ax-brandmark">AX</span><div><h1>Document Designer</h1><small>AXIOM Studio 9.5.2 · Éditeur visuel professionnel</small></div></div>
    <div class="ax-top-actions">
      <button type="button" class="ax-btn ax-btn-icon" id="ax-toggle-library" title="Afficher la bibliothèque">☰</button>
      <a class="ax-btn" href="/public/administration/axiom">← <span class="ax-btn-label">Studio</span></a>
      <button type="button" class="ax-btn" id="ax-open-preview">◉ <span class="ax-btn-label">Aperçu</span></button>
      <?php if($template):?><form method="post" action="/public/administration/axiom/document-designer/publier"><?= \App\Core\Csrf::field()?><input type="hidden" name="module_id" value="<?= $moduleId?>"><input type="hidden" name="template_id" value="<?= $templateId?>"><button class="ax-btn ax-btn-accent">✓ <span class="ax-btn-label">Publier</span></button></form><?php endif;?>
      <button type="submit" form="document-form" class="ax-btn ax-btn-primary">💾 <span class="ax-btn-label">Enregistrer</span></button>
    </div>
  </header>

  <section class="ax-contextbar">
    <form method="get" action="/public/administration/axiom/document-designer" class="ax-context-fields">
      <label>Module<select name="module_id" onchange="this.form.submit()"><?php foreach($modules as $m):?><option value="<?= (int)$m['id']?>" <?= $moduleId===(int)$m['id']?'selected':''?>><?= $h($m['name'])?></option><?php endforeach;?></select></label>
      <label>Modèle<select name="template_id" onchange="this.form.submit()"><option value="0">Nouveau modèle</option><?php foreach($templates as $t):?><option value="<?= (int)$t['id']?>" <?= $templateId===(int)$t['id']?'selected':''?>><?= $h($t['name'])?> · <?= $h($t['status'])?> · v<?= (int)$t['version_no']?></option><?php endforeach;?></select></label>
    </form>
    <div class="ax-badge"><span class="ax-status-dot"></span><span id="ax-save-status"><?= $template?'Modèle chargé · v'.(int)$template['version_no']:'Nouveau brouillon'?></span></div>
  </section>

  <form method="post" action="/public/administration/axiom/document-designer/enregistrer" id="document-form"><?= \App\Core\Csrf::field()?><input type="hidden" name="module_id" value="<?= $moduleId?>"><input type="hidden" name="template_id" value="<?= $templateId?>"><textarea name="body_html" id="body_html" hidden></textarea>
  <div class="ax-workbench">
    <aside class="ax-panel ax-left">
      <div class="ax-panel-head"><h2>Bibliothèque</h2><span class="ax-badge">Glisser-déposer</span></div>
      <div class="ax-tabs"><button type="button" class="ax-tab is-active" data-tab="variables">Variables</button><button type="button" class="ax-tab" data-tab="components">Composants</button></div>
      <div class="ax-panel-body ax-tabpane is-active" data-pane="variables">
        <div class="ax-search"><span>⌕</span><input type="search" id="ax-variable-search" placeholder="Rechercher une variable"></div>
        <?php foreach($groups as $group=>$items):?><details class="ax-variable-group" open><summary><?= $h($group)?></summary><div class="ax-variable-list"><?php foreach($items as $v):?><button type="button" class="ax-token" data-token="<?= $h($v['token'])?>"><span><?= $h($v['label']??$v['token'])?></span><code><?= $h($v['token'])?></code></button><?php endforeach;?></div></details><?php endforeach;?>
      </div>
      <div class="ax-panel-body ax-tabpane" data-pane="components" id="ax-components"><div class="ax-component-grid">
        <button type="button" class="ax-component" data-insert-html="<h2>Nouveau titre</h2>"><span>H</span>Titre</button>
        <button type="button" class="ax-component" data-insert-html="<p>Nouveau paragraphe</p>"><span>¶</span>Texte</button>
        <button type="button" class="ax-component" data-insert-html="<table><thead><tr><th>Colonne 1</th><th>Colonne 2</th></tr></thead><tbody><tr><td>{{valeur1}}</td><td>{{valeur2}}</td></tr></tbody></table>"><span>▦</span>Tableau</button>
        <button type="button" class="ax-component" data-insert-html="<div class='signature-zone'><strong>Signature</strong><br><small>Date et signature précédée de la mention Lu et approuvé</small></div>"><span>✎</span>Signature</button>
        <button type="button" class="ax-component" data-insert-html="<hr>"><span>—</span>Ligne</button>
        <button type="button" class="ax-component" data-insert-html="<div class='page-break'></div>"><span>↧</span>Saut page</button>
      </div></div>
    </aside>

    <section class="ax-panel ax-canvas-panel">
      <div class="ax-editor-meta"><div class="ax-meta-grid">
        <label class="ax-field"><span>Nom du modèle</span><input name="name" required value="<?= $h($template['name']??'')?>" placeholder="Ex. Attestation d'inscription"></label>
        <label class="ax-field"><span>Code</span><input name="code" value="<?= $h($template['code']??'')?>" placeholder="Automatique"></label>
        <label class="ax-field"><span>Catégorie</span><select name="category_id"><option value="0">Sans catégorie</option><?php foreach($categories as $c):?><option value="<?= (int)$c['id']?>" <?= (int)($template['category_id']??0)===(int)$c['id']?'selected':''?>><?= $h($c['name'])?></option><?php endforeach;?></select></label>
      </div></div>
      <div class="ax-toolbar" role="toolbar" aria-label="Mise en forme">
        <button type="button" class="ax-tool" data-cmd="bold" title="Gras (Ctrl+B)"><b>G</b></button><button type="button" class="ax-tool" data-cmd="italic" title="Italique"><i>I</i></button><button type="button" class="ax-tool" data-cmd="underline" title="Souligné"><u>S</u></button><span class="ax-tool-separator"></span>
        <button type="button" class="ax-tool" data-cmd="formatBlock" data-value="h1">H1</button><button type="button" class="ax-tool" data-cmd="formatBlock" data-value="h2">H2</button><button type="button" class="ax-tool" data-cmd="formatBlock" data-value="p">¶</button><span class="ax-tool-separator"></span>
        <button type="button" class="ax-tool" data-cmd="justifyLeft">≡</button><button type="button" class="ax-tool" data-cmd="justifyCenter">≣</button><button type="button" class="ax-tool" data-cmd="justifyRight">≡</button><button type="button" class="ax-tool" data-cmd="insertUnorderedList">• Liste</button><button type="button" class="ax-tool" data-cmd="insertOrderedList">1. Liste</button>
      </div>
      <div class="ax-canvas-viewport"><div id="ax-page" class="ax-page <?= ($page['orientation']??'portrait')==='landscape'?'is-landscape':''?>"><div id="document-editor" class="ax-document-editor" contenteditable="true" data-template-id="<?= $templateId?>"><?= $template['body_html']??'<h1>Votre document</h1><p>Bonjour {{prenom}} {{nom}},</p><p>Commencez votre mise en page ou glissez un composant depuis la bibliothèque.</p>'?></div></div></div>
      <div class="ax-canvas-footer"><span>Canvas A4 · Marges sécurisées · Sauvegarde locale automatique</span><div class="ax-zoom"><span>−</span><input id="ax-zoom" type="range" min="40" max="120" value="85"><strong id="ax-zoom-label">85%</strong><span>+</span></div></div>
    </section>

    <aside class="ax-panel ax-right">
      <div class="ax-panel-head"><h2>Inspecteur</h2><span class="ax-badge">Document</span></div>
      <section class="ax-inspector-section"><h3>Source et sortie</h3><div class="ax-inspector">
        <label class="ax-field"><span>Entité source</span><select name="entity_id" onchange="location.href='/public/administration/axiom/document-designer?module_id=<?= $moduleId?>&entity_id='+this.value+'<?= $template?'&template_id='.$templateId:''?>'"><option value="0">Variables générales</option><?php foreach($entities as $e):?><option value="<?= (int)$e['id']?>" <?= $entityId===(int)$e['id']?'selected':''?>><?= $h($e['name'])?></option><?php endforeach;?></select></label>
        <label class="ax-field"><span>Format</span><select name="output_format"><option value="pdf">PDF / impression</option><option value="html" <?= ($template['output_format']??'')==='html'?'selected':''?>>HTML</option><option value="email" <?= ($template['output_format']??'')==='email'?'selected':''?>>E-mail</option></select></label>
        <label class="ax-field"><span>Objet e-mail</span><input name="subject_template" value="<?= $h($template['subject_template']??'')?>" placeholder="Convocation de {{date}}"></label>
      </div></section>
      <section class="ax-inspector-section"><h3>Page</h3><div class="ax-inspector"><div class="ax-two"><label class="ax-field"><span>Format</span><select name="page_size"><option>A4</option><option <?= ($page['size']??'')==='A3'?'selected':''?>>A3</option><option <?= ($page['size']??'')==='Letter'?'selected':''?>>Letter</option></select></label><label class="ax-field"><span>Orientation</span><select name="orientation"><option value="portrait">Portrait</option><option value="landscape" <?= ($page['orientation']??'')==='landscape'?'selected':''?>>Paysage</option></select></label></div>
      <div class="ax-two"><?php foreach(['top'=>'Haut','right'=>'Droite','bottom'=>'Bas','left'=>'Gauche'] as $k=>$label):?><label class="ax-field"><span>Marge <?= $label?></span><input type="number" min="0" max="80" name="margin_<?= $k?>" value="<?= (int)($page['margin_'.$k]??15)?>"></label><?php endforeach;?></div></div></section>
      <section class="ax-inspector-section"><h3>Informations</h3><div class="ax-inspector"><label class="ax-field"><span>Description</span><textarea name="description" rows="3"><?= $h($template['description']??'')?></textarea></label><details><summary>En-tête et pied de page</summary><label class="ax-field"><span>En-tête HTML</span><textarea name="header_html" rows="3"><?= $h($page['header_html']??'')?></textarea></label><label class="ax-field"><span>Pied de page HTML</span><textarea name="footer_html" rows="3"><?= $h($page['footer_html']??'')?></textarea></label></details></div></section>
      <section class="ax-inspector-section"><h3>Données de test</h3><div class="ax-inspector"><label class="ax-field"><span>JSON de prévisualisation</span><textarea id="sample-json" rows="8"><?= $h(json_encode($sampleData,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES))?></textarea></label><button type="button" class="ax-btn" id="refresh-preview">↻ Actualiser l'aperçu</button></div></section>
    </aside>
  </div></form>

  <?php if($template):?><div class="ax-bottom-grid"><section class="ax-panel"><div class="ax-panel-head"><h2>Historique des versions</h2></div><div class="ax-panel-body ax-list"><?php foreach($versions as $v):?><article><div><strong>Version <?= (int)$v['version_no']?></strong><small><?= $h($v['status'])?> · <?= $h($v['created_at'])?></small></div><form method="post" action="/public/administration/axiom/document-designer/restaurer"><?= \App\Core\Csrf::field()?><input type="hidden" name="module_id" value="<?= $moduleId?>"><input type="hidden" name="template_id" value="<?= $templateId?>"><input type="hidden" name="version_id" value="<?= (int)$v['id']?>"><button class="ax-btn">Restaurer</button></form></article><?php endforeach;?><?php if(!$versions):?><p>Aucune version antérieure.</p><?php endif;?></div></section>
  <section class="ax-panel"><div class="ax-panel-head"><h2>Registre documentaire</h2></div><div class="ax-panel-body ax-list"><?php foreach($generated as $g):?><article><div><strong><?= $h($g['reference'])?></strong><small><?= $h($g['output_format'])?> · <?= $h($g['created_at'])?></small></div><span class="ax-badge"><?= $h($g['status'])?></span></article><?php endforeach;?><?php if(!$generated):?><p>Aucun document généré.</p><?php endif;?></div><form method="post" action="/public/administration/axiom/document-designer/generer" id="generate-form"><?= \App\Core\Csrf::field()?><input type="hidden" name="module_id" value="<?= $moduleId?>"><input type="hidden" name="template_id" value="<?= $templateId?>"><input type="hidden" name="data_json" id="generate-json"><button class="ax-btn ax-btn-primary" style="width:100%">Générer et inscrire au registre</button></form></section></div><?php endif;?>

  <div class="ax-preview-modal" id="ax-preview-modal" aria-hidden="true"><div class="ax-preview-frame"><div class="ax-preview-head"><strong>Aperçu du document</strong><div><button type="button" class="ax-btn" id="ax-print">Imprimer / PDF</button> <button type="button" class="ax-btn" id="ax-close-preview">Fermer</button></div></div><div class="ax-preview-body"><div class="ax-preview-paper" id="document-preview"><?= $rendered['html']??($template['body_html']??'<p>Aperçu du document</p>')?></div></div></div></div>
</main>
