<?php
session_start();
include("_serveur.php");

// ── Sanitize helper ───────────────────────────────────────────────────────────
function esc($link, $v) { return mysqli_real_escape_string($link, trim($v)); }

$msg      = '';
$msgType  = '';
$editRow  = null;

// ── DELETE ────────────────────────────────────────────────────────────────────
if (isset($_POST['delete_id'])) {
    $id = (int)$_POST['delete_id'];
    if (mysqli_query($link, "DELETE FROM observations WHERE id=$id")) {
        $msg = 'Observation supprimée.';
        $msgType = 'success';
    } else {
        $msg = 'Erreur lors de la suppression : ' . mysqli_error($link);
        $msgType = 'error';
    }
}

// ── LOAD FOR EDIT ─────────────────────────────────────────────────────────────
if (isset($_GET['edit'])) {
    $id     = (int)$_GET['edit'];
    $res    = mysqli_query($link, "SELECT * FROM observations WHERE id=$id");
    $editRow = mysqli_fetch_assoc($res);
}

// ── UPDATE ────────────────────────────────────────────────────────────────────
if (isset($_POST['update'])) {
    $id  = (int)$_POST['id'];
    $obs = esc($link, $_POST['obs']);
    if ($obs === '') {
        $msg = "L'observation ne peut pas être vide.";
        $msgType = 'error';
    } else {
        // Check duplicate (excluding self)
        $res = mysqli_query($link, "SELECT id FROM observations WHERE observation='$obs' AND id<>$id");
        if (mysqli_num_rows($res) > 0) {
            $msg = 'Cette observation existe déjà.';
            $msgType = 'error';
        } elseif (mysqli_query($link, "UPDATE observations SET observation='$obs' WHERE id=$id")) {
            $msg = 'Observation mise à jour.';
            $msgType = 'success';
            $editRow = null;
        } else {
            $msg = 'Erreur : ' . mysqli_error($link);
            $msgType = 'error';
        }
    }
}

// ── INSERT ────────────────────────────────────────────────────────────────────
if (isset($_POST['save'])) {
    $obs = esc($link, $_POST['obs']);
    if ($obs === '') {
        $msg = "L'observation ne peut pas être vide.";
        $msgType = 'error';
    } else {
        $res = mysqli_query($link, "SELECT id FROM observations WHERE observation='$obs'");
        if (mysqli_num_rows($res) > 0) {
            $msg = 'Cette observation existe déjà.';
            $msgType = 'error';
        } elseif (mysqli_query($link, "INSERT INTO observations VALUES(DEFAULT,'$obs')")) {
            $msg = 'Observation ajoutée avec succès.';
            $msgType = 'success';
        } else {
            $msg = 'Erreur : ' . mysqli_error($link);
            $msgType = 'error';
        }
    }
}

// ── Fetch all observations ────────────────────────────────────────────────────
$search  = esc($link, $_GET['q'] ?? '');
$where   = $search ? "WHERE observation LIKE '%$search%'" : '';
$allObs  = mysqli_query($link, "SELECT * FROM observations $where ORDER BY id ASC");
$total   = mysqli_num_rows($allObs);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Gestion des Observations</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg:        #f5f4f1;
      --surface:   #ffffff;
      --border:    #e2dfd8;
      --navy:      #1a2942;
      --gold:      #c9a84c;
      --gold-lt:   #f5ecd4;
      --success:   #1a7a4a;
      --success-bg:#eaf7f0;
      --error:     #b83232;
      --error-bg:  #fdf0f0;
      --text:      #1e1e1e;
      --muted:     #7a7570;
      --radius:    10px;
      --shadow:    0 2px 16px rgba(0,0,0,.07);
    }

    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

    body {
      font-family: 'DM Sans', sans-serif;
      background: var(--bg);
      color: var(--text);
      min-height: 100vh;
      padding-bottom: 60px;
    }

    /* ── Header ── */
    .page-header {
      background: var(--navy);
      padding: 18px 28px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 3px solid var(--gold);
    }
    .header-left h1 {
      font-size: 1.15rem;
      font-weight: 600;
      color: #fff;
      letter-spacing: .02em;
    }
    .header-left p {
      font-size: .75rem;
      color: rgba(255,255,255,.5);
      margin-top: 2px;
    }
    .badge-count {
      background: var(--gold);
      color: var(--navy);
      font-size: .72rem;
      font-weight: 700;
      padding: 3px 10px;
      border-radius: 20px;
    }

    /* ── Layout ── */
    .layout {
      max-width: 960px;
      margin: 32px auto;
      padding: 0 18px;
      display: grid;
      grid-template-columns: 340px 1fr;
      gap: 22px;
      align-items: start;
    }
    @media (max-width: 700px) {
      .layout { grid-template-columns: 1fr; }
    }

    /* ── Card ── */
    .card {
      background: var(--surface);
      border-radius: var(--radius);
      box-shadow: var(--shadow);
      border: 1px solid var(--border);
      overflow: hidden;
    }
    .card-header {
      background: var(--navy);
      padding: 13px 18px;
      display: flex;
      align-items: center;
      gap: 9px;
    }
    .card-header svg {
      width: 16px; height: 16px;
      stroke: var(--gold); fill: none; stroke-width: 2;
      flex-shrink: 0;
    }
    .card-header span {
      font-size: .8rem;
      font-weight: 600;
      color: #fff;
      letter-spacing: .06em;
      text-transform: uppercase;
    }
    .card-body { padding: 20px 18px; }

    /* ── Form ── */
    .form-group { margin-bottom: 14px; }
    .form-group label {
      display: block;
      font-size: .72rem;
      font-weight: 600;
      color: var(--navy);
      text-transform: uppercase;
      letter-spacing: .06em;
      margin-bottom: 6px;
    }
    textarea {
      width: 100%;
      border: 1.5px solid var(--border);
      border-radius: 7px;
      padding: 10px 12px;
      font-family: 'DM Sans', sans-serif;
      font-size: .9rem;
      color: var(--text);
      background: #fafaf8;
      resize: vertical;
      min-height: 90px;
      outline: none;
      transition: border-color .2s;
    }
    textarea:focus { border-color: var(--navy); background: #fff; }

    .btn {
      display: inline-flex;
      align-items: center;
      gap: 7px;
      padding: 10px 20px;
      border: none;
      border-radius: 7px;
      font-family: 'DM Sans', sans-serif;
      font-size: .88rem;
      font-weight: 600;
      cursor: pointer;
      text-decoration: none;
      transition: opacity .2s, transform .15s;
    }
    .btn:active { transform: scale(.97); }
    .btn svg { width:14px; height:14px; stroke:currentColor; fill:none; stroke-width:2.2; }

    .btn-primary   { background: var(--navy); color: #fff; width: 100%; justify-content: center; }
    .btn-primary:hover { opacity: .88; }
    .btn-gold      { background: var(--gold); color: var(--navy); width: 100%; justify-content: center; }
    .btn-gold:hover { opacity: .88; }
    .btn-ghost     { background: transparent; border: 1.5px solid var(--border); color: var(--muted); padding: 7px 14px; font-size: .8rem; }
    .btn-ghost:hover { border-color: var(--navy); color: var(--navy); }
    .btn-icon      { padding: 6px 10px; border-radius: 6px; font-size: .78rem; }
    .btn-edit      { background: var(--gold-lt); color: #7a5a10; border: 1px solid #e8d49a; }
    .btn-edit:hover { background: #ecdfa8; }
    .btn-delete    { background: #fdf0f0; color: var(--error); border: 1px solid #f5c6c6; }
    .btn-delete:hover { background: #f9d5d5; }

    .btn-row { display: flex; gap: 8px; margin-top: 4px; }

    /* ── Toast ── */
    .toast {
      border-radius: 8px;
      padding: 11px 15px;
      font-size: .85rem;
      font-weight: 500;
      display: flex;
      align-items: center;
      gap: 9px;
      margin-bottom: 18px;
    }
    .toast svg { width:17px; height:17px; fill:currentColor; flex-shrink:0; }
    .toast.success { background: var(--success-bg); color: var(--success); border: 1px solid #b0e8cc; }
    .toast.error   { background: var(--error-bg);   color: var(--error);   border: 1px solid #f0baba; }

    /* ── Edit banner ── */
    .edit-banner {
      background: var(--gold-lt);
      border: 1.5px solid var(--gold);
      border-radius: 8px;
      padding: 10px 14px;
      font-size: .8rem;
      color: #7a5a10;
      font-weight: 600;
      margin-bottom: 14px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 8px;
    }
    .edit-banner svg { width:15px; height:15px; stroke:#c9a84c; fill:none; stroke-width:2; flex-shrink:0; }

    /* ── Search ── */
    .search-wrap {
      display: flex;
      gap: 8px;
      margin-bottom: 16px;
    }
    .search-wrap input {
      flex: 1;
      border: 1.5px solid var(--border);
      border-radius: 7px;
      padding: 8px 12px;
      font-family: 'DM Sans', sans-serif;
      font-size: .88rem;
      background: #fafaf8;
      outline: none;
      transition: border-color .2s;
    }
    .search-wrap input:focus { border-color: var(--navy); }

    /* ── Observation list ── */
    .obs-list { display: flex; flex-direction: column; gap: 0; }
    .obs-item {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      padding: 13px 0;
      border-bottom: 1px solid var(--border);
    }
    .obs-item:last-child { border-bottom: none; }
    .obs-num {
      font-family: 'DM Mono', monospace;
      font-size: .72rem;
      font-weight: 500;
      color: var(--muted);
      background: var(--bg);
      border: 1px solid var(--border);
      border-radius: 5px;
      padding: 2px 7px;
      flex-shrink: 0;
      margin-top: 2px;
    }
    .obs-text {
      flex: 1;
      font-size: .9rem;
      line-height: 1.5;
      color: var(--text);
      word-break: break-word;
    }
    .obs-actions {
      display: flex;
      gap: 5px;
      flex-shrink: 0;
    }

    /* ── Empty state ── */
    .empty {
      text-align: center;
      padding: 40px 20px;
      color: var(--muted);
    }
    .empty svg { width: 40px; height: 40px; stroke: var(--muted); opacity: .4; margin-bottom: 10px; }
    .empty p { font-size: .88rem; }

    /* ── Confirm modal ── */
    .modal-overlay {
      visibility: hidden;
      opacity: 0;
      pointer-events: none;
      position: fixed; inset: 0;
      background: rgba(0,0,0,.45);
      z-index: 9999;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: opacity .15s, visibility .15s;
    }
    .modal-overlay.open {
      visibility: visible;
      opacity: 1;
      pointer-events: auto;
    }
    .modal {
      background: #fff;
      border-radius: 12px;
      padding: 28px 24px;
      max-width: 360px;
      width: 90%;
      box-shadow: 0 20px 60px rgba(0,0,0,.2);
      text-align: center;
    }
    .modal-icon {
      width: 48px; height: 48px;
      background: var(--error-bg);
      border-radius: 50%;
      display: flex; align-items: center; justify-content: center;
      margin: 0 auto 14px;
    }
    .modal-icon svg { width:22px; height:22px; stroke:var(--error); fill:none; stroke-width:2; }
    .modal h2 { font-size: 1rem; font-weight: 700; margin-bottom: 8px; }
    .modal p  { font-size: .85rem; color: var(--muted); margin-bottom: 20px; }
    .modal-btns { display: flex; gap: 10px; justify-content: center; }
    .btn-cancel { background: var(--bg); border: 1.5px solid var(--border); color: var(--text); padding: 9px 22px; border-radius: 7px; font-family: 'DM Sans', sans-serif; font-size: .88rem; font-weight: 600; cursor: pointer; }
    .btn-confirm-del { background: var(--error); color: #fff; padding: 9px 22px; border-radius: 7px; font-family: 'DM Sans', sans-serif; font-size: .88rem; font-weight: 600; cursor: pointer; border: none; }
  </style>
</head>
<body>

<!-- Header -->
<div class="page-header">
  <div class="header-left">
    <h1>Gestion des Observations</h1>
    <p>Ajouter, modifier ou supprimer des observations</p>
  </div>
  <span class="badge-count"><?= $total ?> observation<?= $total > 1 ? 's' : '' ?></span>
</div>

<div class="layout">

  <!-- ── LEFT: Add / Edit form ── -->
  <div>
    <div class="card">
      <div class="card-header">
        <svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" stroke-linecap="round"/></svg>
        <span><?= $editRow ? 'Modifier' : 'Nouvelle' ?> observation</span>
      </div>
      <div class="card-body">

        <?php if ($msg): ?>
        <div class="toast <?= $msgType ?>">
          <?php if ($msgType === 'success'): ?>
          <svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10S22 17.52 22 12 17.52 2 12 2zm-2 14l-4-4 1.41-1.41L10 13.17l6.59-6.59L18 8l-8 8z"/></svg>
          <?php else: ?>
          <svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10S22 17.52 22 12 17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/></svg>
          <?php endif; ?>
          <?= htmlspecialchars($msg) ?>
        </div>
        <?php endif; ?>

        <?php if ($editRow): ?>
        <!-- Edit mode -->
        <div class="edit-banner">
          <svg viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
          Mode modification — ID #<?= (int)$editRow['id'] ?>
          <a href="remplirtableobservations.php" class="btn btn-ghost" style="padding:3px 10px;font-size:.75rem;">✕ Annuler</a>
        </div>
        <form method="post" action="remplirtableobservations.php">
          <input type="hidden" name="id" value="<?= (int)$editRow['id'] ?>">
          <div class="form-group">
            <label>Texte de l'observation</label>
            <textarea name="obs" placeholder="Saisir l'observation…" autofocus><?= htmlspecialchars($editRow['observation']) ?></textarea>
          </div>
          <div class="btn-row">
            <button type="submit" name="update" class="btn btn-gold">
              <svg viewBox="0 0 24 24"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
              Enregistrer
            </button>
          </div>
        </form>

        <?php else: ?>
        <!-- Add mode -->
        <form method="post" action="remplirtableobservations.php">
          <div class="form-group">
            <label>Texte de l'observation</label>
            <textarea name="obs" placeholder="Ex : Élève perturbateur en classe…"></textarea>
          </div>
          <button type="submit" name="save" class="btn btn-primary">
            <svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" stroke-linecap="round"/></svg>
            Ajouter l'observation
          </button>
        </form>
        <?php endif; ?>

      </div>
    </div>
  </div>

  <!-- ── RIGHT: Observations list ── -->
  <div>
    <div class="card">
      <div class="card-header">
        <svg viewBox="0 0 24 24"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
        <span>Liste des observations</span>
      </div>
      <div class="card-body">

        <!-- Search -->
        <form method="get" action="remplirtableobservations.php" class="search-wrap">
          <input type="text" name="q" value="<?= htmlspecialchars($search) ?>"
                 placeholder="Rechercher une observation…">
          <button type="submit" class="btn btn-ghost">Chercher</button>
          <?php if ($search): ?>
          <a href="remplirtableobservations.php" class="btn btn-ghost">✕</a>
          <?php endif; ?>
        </form>

        <?php if ($total === 0): ?>
        <div class="empty">
          <svg viewBox="0 0 24 24" fill="none"><path d="M9 11l3 3L22 4" stroke-linecap="round" stroke-linejoin="round"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" stroke-linecap="round"/></svg>
          <p><?= $search ? 'Aucun résultat pour «&nbsp;' . htmlspecialchars($search) . '&nbsp;».' : 'Aucune observation enregistrée.' ?></p>
        </div>
        <?php else: ?>
        <div class="obs-list">
          <?php $n = 1; while ($row = mysqli_fetch_assoc($allObs)): ?>
          <div class="obs-item">
            <span class="obs-num"><?= $n++ ?></span>
            <div class="obs-text"><?= nl2br(htmlspecialchars($row['observation'])) ?></div>
            <div class="obs-actions">
              <a href="remplirtableobservations.php?edit=<?= (int)$row['id'] ?>"
                 class="btn btn-icon btn-edit" title="Modifier">
                <svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" fill="none" stroke-width="2">
                  <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                  <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                </svg>
              </a>
              <button type="button" class="btn btn-icon btn-delete"
                      onclick="confirmDelete(<?= (int)$row['id'] ?>, <?= json_encode($row['observation']) ?>)"
                      title="Supprimer">
                <svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" fill="none" stroke-width="2">
                  <polyline points="3 6 5 6 21 6"/>
                  <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>
                  <path d="M10 11v6M14 11v6"/>
                  <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>
                </svg>
              </button>
            </div>
          </div>
          <?php endwhile; ?>
        </div>
        <?php endif; ?>

      </div>
    </div>
  </div>

</div>

<!-- ── Delete confirmation modal ── -->
<div class="modal-overlay" id="delModal">
  <div class="modal">
    <div class="modal-icon">
      <svg viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/></svg>
    </div>
    <h2>Supprimer l'observation ?</h2>
    <p id="delText" style="word-break:break-word;"></p>
    <div class="modal-btns">
      <button type="button" class="btn-cancel" onclick="closeModal()">Annuler</button>
      <form method="post" action="remplirtableobservations.php" style="display:inline;">
        <input type="hidden" name="delete_id" id="delId" value="">
        <button type="submit" class="btn-confirm-del">Supprimer</button>
      </form>
    </div>
  </div>
</div>

<script>
function confirmDelete(id, text) {
  document.getElementById('delText').textContent =
    '"' + text.substring(0, 80) + (text.length > 80 ? '…' : '') + '"';
  document.getElementById('delId').value = id;
  document.getElementById('delModal').classList.add('open');
}
function closeModal() {
  document.getElementById('delModal').classList.remove('open');
}
document.getElementById('delModal').addEventListener('click', function(e) {
  if (e.target === this) closeModal();
});
</script>
</body>
</html>
