<?php
require __DIR__ . '/lib.php';
require_auth();

$slug = slugify($_GET['form'] ?? '');
$form = $slug ? load_form($slug) : null;
if (!$form) {
    http_response_code(404);
    echo 'Sondage introuvable';
    exit;
}

function rrmdir(string $dir): void {
    foreach (array_diff(scandir($dir) ?: [], ['.', '..']) as $file) {
        $path = $dir . DIRECTORY_SEPARATOR . $file;
        if (is_dir($path)) {
            rrmdir($path);
        } else {
            unlink($path);
        }
    }
    rmdir($dir);
}

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['delete_form'])) {
        rrmdir(form_dir($slug));
        header('Location: index.php?tab=create&deleted=1');
        exit;
    }
    $payload = json_decode((string)($_POST['payload_json'] ?? ''), true);
    if (!is_array($payload)) {
        $errors[] = 'Configuration invalide.';
    } else {
        $newSlug = slugify((string)($payload['meta']['slug'] ?? $slug));
        if ($newSlug !== $slug && is_dir(form_dir($newSlug))) {
            $errors[] = 'Ce slug est déjà utilisé.';
        } else {
            if ($newSlug !== $slug) {
                rename(form_dir($slug), form_dir($newSlug));
                $slug = $newSlug;
            }
            save_form($slug, $payload);
            $form = load_form($slug);
            header('Location: edit.php?form=' . rawurlencode($slug) . '&saved=1');
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Éditer <?= h($form['meta']['name']) ?></title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="page-shell">
    <div class="wrap">
      <div class="brand-block">
        <div class="bhex"><span>★</span></div>
        <div>
          <div class="bname">MYKOLLECTOR</div>
          <div class="btag">Édition du sondage</div>
        </div>
        <div class="ds-mode-badge"><?= h($form['meta']['slug']) ?></div>
      </div>

      <?php if (!empty($_GET['saved'])): ?>
        <div class="card card-body" style="margin-bottom:18px"><div class="success-box">Le sondage a bien été mis à jour.</div></div>
      <?php endif; ?>
      <?php if ($errors): ?>
        <div class="card card-body" style="margin-bottom:18px"><div class="error-box"><?= h(implode(' ', $errors)) ?></div></div>
      <?php endif; ?>

      <form method="post" id="builderForm" class="card card-body">
        <div class="actions" style="justify-content:space-between;margin-bottom:18px">
          <div>
            <div class="card-title"><?= h($form['meta']['name']) ?></div>
            <div class="card-subtitle">Vous pouvez modifier l’introduction, les questions, les options et le mode <strong>Une réponse</strong> / <strong>Plusieurs réponses</strong>.</div>
          </div>
          <div class="actions">
            <a class="btn-secondary" href="index.php?tab=create">Retour</a>
            <a class="btn-outline" href="survey.php?form=<?= h($slug) ?>" target="_blank" rel="noopener">Voir le sondage</a>
            <button class="btn-primary" type="submit">Enregistrer</button>
          </div>
        </div>

        <div class="form-grid">
          <div>
            <label class="lbl">Nom du sondage</label>
            <input class="input" id="meta_name">
          </div>
          <div>
            <label class="lbl">Slug / URL</label>
            <input class="input" id="meta_slug">
          </div>
          <div class="full">
            <label class="lbl">Description courte</label>
            <textarea class="textarea" id="meta_description"></textarea>
          </div>
          <div>
            <label class="lbl">Limite de réponses</label>
            <input class="input" id="meta_maxResponses" type="number" min="1">
          </div>
          <div>
            <label class="lbl">Date de fin</label>
            <input class="input" id="meta_endDate" type="date">
          </div>
          <div class="full">
            <label class="lbl">Image de fond (URL optionnelle)</label>
            <input class="input" id="meta_background">
          </div>
          <div class="full">
            <label class="lbl">Texte de partage</label>
            <textarea class="textarea" id="meta_shareText"></textarea>
          </div>
        </div>

        <div class="card" style="margin-top:20px">
          <div class="card-body">
            <div class="badge">Étape fixe · Introduction</div>
            <div class="form-grid" style="margin-top:16px">
              <div>
                <label class="lbl">Titre intro</label>
                <input class="input" id="intro_title">
              </div>
              <div>
                <label class="lbl">Bouton intro</label>
                <input class="input" id="intro_button">
              </div>
              <div class="full">
                <label class="lbl">Texte intro</label>
                <textarea class="textarea" id="intro_text"></textarea>
              </div>
            </div>
          </div>
        </div>

        <div class="card" style="margin-top:20px">
          <div class="card-body">
            <div class="badge">Étape fixe · Identité</div>
            <p class="hint" style="margin-top:12px">Prénom + nom obligatoires avant les réponses.</p>
          </div>
        </div>

        <div class="card" style="margin-top:20px">
          <div class="card-body">
            <div class="question-head">
              <div>
                <div class="card-title">Questions</div>
                <div class="card-subtitle">Les questions à choix disposent désormais de l’option <strong>Une réponse</strong>.</div>
              </div>
              <div class="actions">
                <button class="btn-outline" type="button" id="addMultiple">+ Question à choix</button>
                <button class="btn-secondary" type="button" id="addText">+ Question texte</button>
              </div>
            </div>
            <div id="questionList" class="builder-list"></div>
          </div>
        </div>

        <div class="actions" style="justify-content:space-between;margin-top:20px">
          <button class="btn-danger" type="submit" name="delete_form" value="1" onclick="return confirm('Supprimer définitivement ce sondage ?')">Supprimer le sondage</button>
          <div class="actions">
            <a class="btn-secondary" href="index.php?tab=analyse&form=<?= h($slug) ?>">Voir l’analyse</a>
            <button class="btn-primary" type="submit">Enregistrer</button>
          </div>
        </div>

        <input type="hidden" name="payload_json" id="payload_json">
      </form>
    </div>
  </div>

  <script>
    const initialData = <?= json_encode($form, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const list = document.getElementById('questionList');
    const form = document.getElementById('builderForm');

    function questionTemplate(data = {}) {
      const type = data.type || 'multiple';
      const selection = data.selection === 'multiple' ? 'multiple' : 'single';
      const options = Array.isArray(data.options) ? data.options.join('\n') : '';
      return `
        <div class="question-block">
          <div class="question-head">
            <div class="question-type">${type === 'multiple' ? 'Question à choix' : 'Question texte'}</div>
            <button class="btn-danger remove-question" type="button">Supprimer</button>
          </div>
          <div class="form-grid">
            <div>
              <label class="lbl">Type</label>
              <select class="select q_type">
                <option value="multiple" ${type === 'multiple' ? 'selected' : ''}>Choix</option>
                <option value="text" ${type === 'text' ? 'selected' : ''}>Texte libre</option>
              </select>
            </div>
            <div class="q_selection_wrap" style="display:${type === 'multiple' ? 'block' : 'none'}">
              <label class="lbl">Réglage de réponse</label>
              <select class="select q_selection">
                <option value="single" ${selection === 'single' ? 'selected' : ''}>Une réponse</option>
                <option value="multiple" ${selection === 'multiple' ? 'selected' : ''}>Plusieurs réponses</option>
              </select>
            </div>
            <div class="full">
              <label class="lbl">Question</label>
              <input class="input q_question" value="${data.question || ''}">
            </div>
            <div class="full q_options_wrap" style="display:${type === 'multiple' ? 'block' : 'none'}">
              <label class="lbl">Options (1 ligne = 1 option)</label>
              <textarea class="textarea q_options">${options}</textarea>
            </div>
            <div class="full q_placeholder_wrap" style="display:${type === 'text' ? 'block' : 'none'}">
              <label class="lbl">Placeholder</label>
              <input class="input q_placeholder" value="${data.placeholder || 'Votre réponse...'}">
            </div>
          </div>
        </div>
      `;
    }

    function hydrateMeta(data) {
      document.getElementById('meta_name').value = data.meta.name || '';
      document.getElementById('meta_slug').value = data.meta.slug || '';
      document.getElementById('meta_description').value = data.meta.description || '';
      document.getElementById('meta_maxResponses').value = data.meta.maxResponses || '';
      document.getElementById('meta_endDate').value = data.meta.endDate || '';
      document.getElementById('meta_background').value = data.meta.background || '';
      document.getElementById('meta_shareText').value = data.meta.shareText || '';
      const intro = data.steps.find(step => step.type === 'intro') || {};
      document.getElementById('intro_title').value = intro.title || '';
      document.getElementById('intro_text').value = intro.text || '';
      document.getElementById('intro_button').value = intro.button || 'Commencer';
      const questions = data.steps.filter(step => step.type === 'multiple' || step.type === 'text');
      list.innerHTML = questions.map(q => questionTemplate(q)).join('');
      bindBlocks();
    }

    function bindBlocks() {
      list.querySelectorAll('.question-block').forEach((block) => {
        block.querySelector('.remove-question').onclick = () => block.remove();
        block.querySelector('.q_type').onchange = (event) => {
          const type = event.target.value;
          block.querySelector('.q_selection_wrap').style.display = type === 'multiple' ? 'block' : 'none';
          block.querySelector('.q_options_wrap').style.display = type === 'multiple' ? 'block' : 'none';
          block.querySelector('.q_placeholder_wrap').style.display = type === 'text' ? 'block' : 'none';
          block.querySelector('.question-type').textContent = type === 'multiple' ? 'Question à choix' : 'Question texte';
        };
      });
    }

    function addQuestion(type) {
      list.insertAdjacentHTML('beforeend', questionTemplate({ type }));
      bindBlocks();
    }

    document.getElementById('addMultiple').onclick = () => addQuestion('multiple');
    document.getElementById('addText').onclick = () => addQuestion('text');

    form.addEventListener('submit', (event) => {
      if (event.submitter && event.submitter.name === 'delete_form') {
        return;
      }
      const blocks = Array.from(list.querySelectorAll('.question-block'));
      if (!blocks.length) {
        event.preventDefault();
        alert('Ajoutez au moins une question.');
        return;
      }
      const steps = [
        {
          type: 'intro',
          title: document.getElementById('intro_title').value.trim(),
          text: document.getElementById('intro_text').value.trim(),
          button: document.getElementById('intro_button').value.trim() || 'Commencer'
        },
        { type: 'identity' }
      ];
      blocks.forEach((block) => {
        const type = block.querySelector('.q_type').value;
        if (type === 'multiple') {
          steps.push({
            type: 'multiple',
            question: block.querySelector('.q_question').value.trim(),
            selection: block.querySelector('.q_selection').value,
            options: block.querySelector('.q_options').value.split(/\r?\n/).map(v => v.trim()).filter(Boolean)
          });
        } else {
          steps.push({
            type: 'text',
            question: block.querySelector('.q_question').value.trim(),
            placeholder: block.querySelector('.q_placeholder').value.trim() || 'Votre réponse...'
          });
        }
      });
      document.getElementById('payload_json').value = JSON.stringify({
        meta: {
          name: document.getElementById('meta_name').value.trim(),
          slug: document.getElementById('meta_slug').value.trim(),
          description: document.getElementById('meta_description').value.trim(),
          maxResponses: document.getElementById('meta_maxResponses').value.trim(),
          endDate: document.getElementById('meta_endDate').value.trim(),
          background: document.getElementById('meta_background').value.trim(),
          shareText: document.getElementById('meta_shareText').value.trim(),
        },
        steps
      });
    });

    hydrateMeta(initialData);
  </script>
</body>
</html>
