<?php
require __DIR__ . '/lib.php';

if (!empty($_GET['logout'])) {
    logout_admin();
    header('Location: index.php');
    exit;
}

$loginError = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admin_password'])) {
    if (!attempt_login((string)$_POST['admin_password'])) {
        $loginError = 'Mot de passe incorrect.';
    } else {
        header('Location: index.php');
        exit;
    }
}

if (!is_authenticated()): ?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Admin sondages MyKollectOr</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="page-shell">
    <div class="wrap login-shell">
      <div class="brand-block">
        <div class="bhex"><span>★</span></div>
        <div>
          <div class="bname">MYKOLLECTOR</div>
          <div class="btag">Admin des sondages</div>
        </div>
        <div class="ds-mode-badge">Sécurisé</div>
      </div>
      <form method="post" class="card card-body">
        <div class="card-title">Connexion admin</div>
        <p class="card-subtitle">Mot de passe simple, stocké côté serveur. Pensez à le modifier via la variable d’environnement <strong>SURVEY_ADMIN_PASSWORD</strong>.</p>
        <div style="margin-top:18px">
          <label class="lbl">Mot de passe</label>
          <input class="input" type="password" name="admin_password" placeholder="Votre mot de passe" required>
        </div>
        <?php if ($loginError): ?><div class="error-box" style="margin-top:16px"><?= h($loginError) ?></div><?php endif; ?>
        <div class="actions" style="margin-top:18px">
          <button class="btn-primary" type="submit">Se connecter</button>
        </div>
        <div class="notice" style="margin-top:18px">Mot de passe par défaut : <strong><?= h(DEFAULT_ADMIN_PASSWORD) ?></strong></div>
      </form>
    </div>
  </div>
</body>
</html>
<?php exit; endif;

$forms = list_forms();
$tab = ($_GET['tab'] ?? 'create') === 'analyse' ? 'analyse' : 'create';
$selectedSlug = slugify($_GET['form'] ?? ($forms[0]['meta']['slug'] ?? ''));
$selectedForm = $selectedSlug ? load_form($selectedSlug) : null;
$rows = $selectedForm ? array_reverse(response_rows($selectedSlug)) : [];
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Plateforme de sondages MyKollectOr</title>
  <link rel="stylesheet" href="style.css">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</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">Dashboard sondages · création + analyse</div>
        </div>
        <a class="ds-mode-badge" href="?logout=1">Déconnexion</a>
      </div>

      <?php if (!empty($_GET['deleted'])): ?>
        <div class="card card-body" style="margin-bottom:18px"><div class="success-box">Le sondage a été supprimé.</div></div>
      <?php endif; ?>

      <div class="tabs">
        <a class="tab-link <?= $tab === 'create' ? 'active' : '' ?>" href="?tab=create">Création</a>
        <a class="tab-link <?= $tab === 'analyse' ? 'active' : '' ?>" href="?tab=analyse<?= $selectedSlug ? '&form=' . rawurlencode($selectedSlug) : '' ?>">Analyse</a>
      </div>

      <?php if ($tab === 'create'): ?>
        <section class="grid grid-2">
          <div class="card card-body">
            <div class="card-title">Créer un nouveau sondage</div>
            <p class="card-subtitle">Compatible avec votre design sombre MyKollectOr, multi-sondages, overlay bleu, widget toast et questions avec option <strong>Une réponse</strong>.</p>
            <div class="actions" style="margin-top:18px">
              <a class="btn-primary" href="create.php">Nouveau sondage</a>
              <a class="btn-secondary" href="survey.php?form=demo" target="_blank" rel="noopener">Voir la démo</a>
            </div>
            <div class="notice" style="margin-top:18px">URL publique d’un sondage : <strong>survey.php?form=slug</strong></div>
          </div>
          <div class="card card-body">
            <div class="card-title">Widget d’intégration</div>
            <p class="card-subtitle">Ajoutez le script sur votre site ou landing page. Au clic, il ouvre une carte toast puis le sondage en overlay fullscreen.</p>
            <div class="table-wrap" style="margin-top:16px">
              <table>
                <tbody>
                  <tr><th>Exemple</th></tr>
                  <tr><td><code>&lt;script src="/survey-platform/embed.js" data-form="demo" data-title="Répondre au sondage" data-description="Donnez votre avis"&gt;&lt;/script&gt;</code></td></tr>
                </tbody>
              </table>
            </div>
          </div>
        </section>

        <section class="card card-body" style="margin-top:20px">
          <div class="question-head">
            <div>
              <div class="card-title">Sondages existants</div>
              <div class="card-subtitle">Éditez, ouvrez l’URL publique ou consultez les statistiques.</div>
            </div>
            <div class="badge"><?= count($forms) ?> sondage(s)</div>
          </div>

          <?php if (!$forms): ?>
            <div class="empty-state">Aucun sondage pour le moment.</div>
          <?php else: ?>
            <div class="grid grid-3">
              <?php foreach ($forms as $item): ?>
                <article class="card">
                  <div class="card-body">
                    <div class="badge"><?= $item['closed'] ? 'Fermé' : 'Actif' ?></div>
                    <div class="card-title" style="margin-top:14px"><?= h($item['meta']['name']) ?></div>
                    <p class="card-subtitle"><?= h($item['meta']['description']) ?></p>
                    <div class="inline" style="margin:14px 0 10px">
                      <span class="pill"><?= (int)$item['responseCount'] ?> réponse(s)</span>
                      <?php if ($item['meta']['endDate']): ?><span class="pill">Fin : <?= h($item['meta']['endDate']) ?></span><?php endif; ?>
                    </div>
                    <div class="actions">
                      <a class="btn-secondary" href="edit.php?form=<?= h($item['meta']['slug']) ?>">Éditer</a>
                      <a class="btn-outline" href="survey.php?form=<?= h($item['meta']['slug']) ?>" target="_blank" rel="noopener">Ouvrir</a>
                      <a class="btn-primary" href="?tab=analyse&form=<?= h($item['meta']['slug']) ?>">Analyser</a>
                    </div>
                  </div>
                </article>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </section>
      <?php else: ?>
        <section class="grid grid-3">
          <div class="card metric"><strong><?= count($forms) ?></strong><span>Sondages configurés</span></div>
          <div class="card metric"><strong><?= $selectedForm ? response_count($selectedSlug) : 0 ?></strong><span>Réponses sur le sondage sélectionné</span></div>
          <div class="card metric"><strong><?= $selectedForm && is_form_closed($selectedForm) ? 'Fermé' : 'Ouvert' ?></strong><span>Statut actuel</span></div>
        </section>

        <section class="card card-body" style="margin-top:20px">
          <div class="question-head">
            <div>
              <div class="card-title">Analyse des réponses</div>
              <div class="card-subtitle">Diagrammes Chart.js, tableau complet et export CSV.</div>
            </div>
            <div class="actions">
              <form method="get" class="inline">
                <input type="hidden" name="tab" value="analyse">
                <select class="select" name="form" onchange="this.form.submit()">
                  <?php foreach ($forms as $item): ?>
                    <option value="<?= h($item['meta']['slug']) ?>" <?= $selectedSlug === $item['meta']['slug'] ? 'selected' : '' ?>><?= h($item['meta']['name']) ?></option>
                  <?php endforeach; ?>
                </select>
              </form>
              <?php if ($selectedForm): ?>
                <a class="btn-outline" href="edit.php?form=<?= h($selectedSlug) ?>">Éditer</a>
                <a class="btn-secondary" href="export.php?form=<?= h($selectedSlug) ?>">Télécharger CSV</a>
              <?php endif; ?>
            </div>
          </div>

          <?php if (!$selectedForm): ?>
            <div class="empty-state">Aucun sondage disponible pour l’analyse.</div>
          <?php else: ?>
            <div id="chartGrid" class="chart-grid" style="margin-top:18px"></div>

            <div class="table-wrap" style="margin-top:20px">
              <table>
                <thead>
                  <tr>
                    <?php if ($rows): ?>
                      <?php foreach (array_keys($rows[0]) as $header): ?>
                        <th><?= h($header) ?></th>
                      <?php endforeach; ?>
                    <?php else: ?>
                      <th>Aucune donnée</th>
                    <?php endif; ?>
                  </tr>
                </thead>
                <tbody>
                  <?php if (!$rows): ?>
                    <tr><td>Aucune réponse enregistrée pour le moment.</td></tr>
                  <?php else: ?>
                    <?php foreach ($rows as $row): ?>
                      <tr>
                        <?php foreach ($row as $key => $value): ?>
                          <td><?= h($value) ?></td>
                        <?php endforeach; ?>
                      </tr>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </section>
      <?php endif; ?>
    </div>
  </div>

  <?php if ($tab === 'analyse' && $selectedForm): ?>
  <script>
    fetch('stats.php?form=<?= rawurlencode($selectedSlug) ?>')
      .then(r => r.json())
      .then((data) => {
        const chartGrid = document.getElementById('chartGrid');
        if (!data.ok || !data.charts?.length) {
          chartGrid.innerHTML = '<div class="empty-state" style="grid-column:1/-1">Aucun graphique disponible pour ce sondage.</div>';
          return;
        }
        chartGrid.innerHTML = data.charts.map((chart, idx) => `
          <div class="chart-card">
            <h3>${chart.question}</h3>
            <canvas id="chart_${idx}" height="220"></canvas>
          </div>
        `).join('');

        data.charts.forEach((chart, idx) => {
          const ctx = document.getElementById(`chart_${idx}`);
          new Chart(ctx, {
            type: chart.chartType || 'bar',
            data: {
              labels: chart.labels,
              datasets: [{
                label: chart.question,
                data: chart.data,
                backgroundColor: ['#c8a84b','#e8c870','#1a5580','#3ecf8e','#ff5a6b','#7c5cbf','#0e3e5f','#f0b429'],
                borderColor: 'rgba(255,255,255,.08)',
                borderWidth: 1,
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: { legend: { labels: { color: '#ffffff' } } },
              scales: chart.chartType === 'bar' ? {
                x: { ticks: { color: 'rgba(255,255,255,.72)' }, grid: { color: 'rgba(255,255,255,.06)' } },
                y: { ticks: { color: 'rgba(255,255,255,.72)' }, grid: { color: 'rgba(255,255,255,.06)' }, beginAtZero: true }
              } : {}
            }
          });
        });
      });
  </script>
  <?php endif; ?>
</body>
</html>
