<?php
session_start();

// ── Auth check (no DB needed for already-logged-in users) ──────
$isAuth     = isset($_SESSION['user_type']) && (int)$_SESSION['user_type'] === 1;
$loginError = '';

// ── Logout ─────────────────────────────────────────────────────
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// ── Handle login POST (DB only touched here) ───────────────────
if (!$isAuth && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'login') {

    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if ($username && $password) {

        // ── DB connection ──────────────────────────────────────
       $host    = 'localhost';
$dbName  = 'stjoseph_miniara';
$dbUser  = 'stjoseph_john';
$dbPass  = 'John521889!';

        try {
            $pdo = new PDO(
                "mysql:host=$host;dbname=$dbName;charset=utf8mb4",
                $dbUser, $dbPass,
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                 PDO::ATTR_EMULATE_PREPARES   => false]
            );
        } catch (\PDOException $e) {
            $loginError = 'Erreur de connexion à la base de données.';
            $pdo = null;
        }

        if ($pdo) {
            $stmt = $pdo->prepare(
                "SELECT id, firstName, lastName, type, active, password
                 FROM users WHERE username = ? LIMIT 1"
            );
            $stmt->execute([$username]);
            $row = $stmt->fetch();

            if ($row && $row['password'] === $password) {
                if ((int)$row['active'] !== 1) {
                    $loginError = 'Ce compte est désactivé.';
                } elseif ((int)$row['type'] !== 1) {
                    $loginError = 'Accès refusé. Ce menu est réservé aux administrateurs.';
                } else {
                    // ✅ type=1 AND active=1 → store session and redirect
                    $_SESSION['user_id']        = $row['id'];
                    $_SESSION['user_firstName'] = $row['firstName'];
                    $_SESSION['user_lastName']  = $row['lastName'];
                    $_SESSION['user_type']      = (int)$row['type'];
                    header('Location: ' . $_SERVER['PHP_SELF']);
                    exit;
                }
            } else {
                $loginError = 'Nom d\'utilisateur ou mot de passe incorrect.';
            }
        }

    } else {
        $loginError = 'Veuillez remplir tous les champs.';
    }
}

// Re-check after possible POST processing
$isAuth = isset($_SESSION['user_type']) && (int)$_SESSION['user_type'] === 1;
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Médical — Collège Saints Joseph Miniara</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600&family=Playfair+Display:wght@600&display=swap" rel="stylesheet">
<style>
/* ═══════════════════════════════════════════ TOKENS */
:root {
  --navy:      #0d2158;
  --navy2:     #1a4aad;
  --blue:      #2a6dd9;
  --accent:    #93c5fd;
  --gold:      #f0b429;
  --sidebar-w: 270px;
  --header-h:  58px;
  --bg:        #f1f5fb;
  --panel:     #ffffff;
  --text:      #0f172a;
  --muted:     #64748b;
  --border:    rgba(0,0,0,.07);
  --radius:    10px;
  --trans:     .22s ease;
}
body.dark {
  --bg:     #0c1a3a;
  --panel:  #122044;
  --text:   #e2eaf8;
  --muted:  #7a95b8;
  --border: rgba(255,255,255,.06);
}

/* ═══════════════════════════════════════════ RESET */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
  font-family: 'DM Sans', sans-serif;
  background: var(--bg);
  color: var(--text);
  height: 100vh;
  overflow: hidden;
}

/* ═══════════════════════════════════════════ LOGIN SCREEN */
.login-wrap {
  height: 100vh;
  display: flex; align-items: center; justify-content: center;
  background: linear-gradient(135deg, #0d2158 0%, #1a4aad 100%);
}
.login-card {
  background: #fff; border-radius: 18px;
  padding: 40px 36px; width: 100%; max-width: 380px;
  box-shadow: 0 24px 60px rgba(0,0,0,.3);
}
.login-logo { display: flex; align-items: center; gap: 12px; margin-bottom: 28px; }
.login-logo img {
  width: 48px; height: 48px; border-radius: 50%;
  object-fit: cover; border: 2px solid #0d2158;
}
.login-logo-text { font-family: 'Playfair Display', serif; font-size: 1rem; color: #0d2158; line-height: 1.3; }
.login-logo-text small {
  display: block; font-family: 'DM Sans', sans-serif;
  font-size: .68rem; color: #64748b; font-weight: 400;
  text-transform: uppercase; letter-spacing: .08em;
}
.login-title { font-family: 'Playfair Display', serif; font-size: 1.4rem; color: #0d2158; margin-bottom: 6px; }
.login-sub { font-size: .8rem; color: #64748b; margin-bottom: 28px; }
.login-field { margin-bottom: 16px; }
.login-field label { display: block; font-size: .78rem; font-weight: 600; color: #0d2158; margin-bottom: 6px; }
.login-field input {
  width: 100%; padding: 10px 14px;
  border: 1.5px solid #cbd5e1; border-radius: 8px;
  font-size: .88rem; font-family: 'DM Sans', sans-serif;
  color: #0f172a; transition: border-color .2s; outline: none;
}
.login-field input:focus { border-color: #2a6dd9; }
.login-btn {
  width: 100%; padding: 12px;
  background: #0d2158; color: #fff;
  border: none; border-radius: 8px;
  font-size: .9rem; font-weight: 600;
  font-family: 'DM Sans', sans-serif;
  cursor: pointer; transition: background .2s; margin-top: 6px;
}
.login-btn:hover { background: #1a4aad; }
.login-error {
  background: #fee2e2; color: #b91c1c;
  border-radius: 8px; padding: 10px 14px;
  font-size: .8rem; margin-bottom: 18px;
  border: 1px solid #fecaca;
}

/* ═══════════════════════════════════════════ HEADER */
header {
  position: fixed; top: 0; left: 0; right: 0;
  height: var(--header-h); background: #0d2158;
  display: flex; align-items: center; justify-content: space-between;
  padding: 0 18px; z-index: 200;
  box-shadow: 0 2px 16px rgba(0,0,0,.35);
}
.h-left { display: flex; align-items: center; gap: 12px; }
.burger {
  width: 36px; height: 36px; border-radius: 8px;
  background: rgba(255,255,255,.08); border: none; cursor: pointer;
  display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 5px;
  transition: background var(--trans);
}
.burger:hover { background: rgba(255,255,255,.16); }
.burger span { display: block; width: 18px; height: 2px; background: #fff; border-radius: 2px; transition: var(--trans); }
.school-logo { height: 36px; width: 36px; border-radius: 50%; object-fit: cover; border: 2px solid rgba(255,255,255,.2); }
.school-name { font-family: 'Playfair Display', serif; font-size: .95rem; color: #fff; letter-spacing: .02em; line-height: 1.2; }
.school-name small { display: block; font-family: 'DM Sans', sans-serif; font-size: .7rem; color: var(--accent); font-weight: 400; letter-spacing: .08em; text-transform: uppercase; }
.h-right { display: flex; align-items: center; gap: 8px; }
.h-btn {
  height: 36px; border-radius: 8px; background: rgba(255,255,255,.08);
  border: none; color: #fff; font-size: .78rem; font-weight: 500;
  cursor: pointer; display: flex; align-items: center; justify-content: center;
  padding: 0 12px; gap: 6px; transition: background var(--trans);
  font-family: 'DM Sans', sans-serif; white-space: nowrap; text-decoration: none;
}
.h-btn:hover { background: rgba(255,255,255,.18); }
.user-chip {
  background: rgba(147,197,253,.15); border: 1px solid rgba(147,197,253,.3);
  border-radius: 8px; padding: 0 12px; height: 36px;
  display: flex; align-items: center; gap: 6px;
  color: #fff; font-size: .78rem; font-weight: 500;
}

/* ═══════════════════════════════════════════ LAYOUT */
.wrapper {
  display: flex;
  height: calc(100vh - var(--header-h));
  margin-top: var(--header-h);
  overflow: hidden;
}

/* ═══════════════════════════════════════════ SIDEBAR */
aside {
  width: var(--sidebar-w); background: #0d2158;
  overflow-y: auto; overflow-x: hidden; flex-shrink: 0;
  transition: transform var(--trans);
  scrollbar-width: thin; scrollbar-color: rgba(255,255,255,.12) transparent;
  border-right: 1px solid rgba(255,255,255,.06);
  height: 100%;
}
aside::-webkit-scrollbar { width: 4px; }
aside::-webkit-scrollbar-thumb { background: rgba(255,255,255,.14); border-radius: 2px; }
.nav-section { padding: 20px 16px 6px; font-size: .65rem; font-weight: 600; letter-spacing: .12em; text-transform: uppercase; color: rgba(255,255,255,.32); }
aside ul { list-style: none; }
aside > ul > li { position: relative; }
aside > ul > li > a {
  display: flex; align-items: center; gap: 10px;
  padding: 10px 16px; background: #0d2158; color: rgba(255,255,255,.88);
  text-decoration: none; font-size: .83rem; font-weight: 600; cursor: pointer;
  transition: color var(--trans), background var(--trans);
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
aside > ul > li > a:hover { background: #162e72; color: #fff; }
.nav-icon { font-size: 1rem; width: 20px; text-align: center; flex-shrink: 0; }
aside li.active > a { background: #0b47c9 !important; color: #fff !important; border-left: 3px solid #93c5fd; }
.nav-divider { height: 1px; background: rgba(255,255,255,.06); margin: 4px 16px; }

/* ═══════════════════════════════════════════ MAIN */
main {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-width: 0;
  height: calc(100vh - var(--header-h));
}
#content-frame { width: 100%; flex: 1; border: none; display: none; height: 100%; }

/* ═══════════════════════════════════════════ DASHBOARD */
#dashboard {
  flex: 1;
  padding: 32px 28px;
  overflow-y: auto;
  overflow-x: hidden;
  background: var(--bg);
  display: block;
  min-height: 0;
}
.dash-greeting { font-family: 'Playfair Display', serif; font-size: 1.6rem; color: var(--text); margin-bottom: 6px; }
.dash-sub { font-size: .82rem; color: var(--muted); margin-bottom: 36px; }
.icon-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 16px; max-width: 720px; }
.icon-card {
  background: var(--panel); border: 1px solid var(--border);
  border-radius: 14px; padding: 22px 12px 18px;
  display: flex; flex-direction: column; align-items: center; gap: 10px;
  cursor: pointer; transition: transform var(--trans), box-shadow var(--trans), border-color var(--trans);
  text-align: center;
}
.icon-card:hover { transform: translateY(-4px); box-shadow: 0 10px 28px rgba(0,0,0,.12); border-color: var(--accent); }
.icon-card .ic-emoji { font-size: 2rem; line-height: 1; }
.icon-card .ic-label { font-size: .75rem; font-weight: 600; color: var(--muted); letter-spacing: .02em; }
body.dark .icon-card { box-shadow: 0 4px 18px rgba(0,0,0,.4); }

/* ═══════════════════════════════════════════ MOBILE */
@media (max-width: 768px) {
  aside { position: fixed; height: calc(100vh - var(--header-h)); top: var(--header-h); z-index: 150; transform: translateX(-100%); box-shadow: 6px 0 24px rgba(0,0,0,.4); }
  aside.open { transform: translateX(0); }
}
</style>
</head>
<body>

<?php if (!$isAuth): ?>
<!-- ══════════════════════════════ LOGIN SCREEN -->
<div class="login-wrap">
  <div class="login-card">
    <div class="login-logo">
      <img src="Logo.jpg" alt="Logo">
      <div class="login-logo-text">
        Collège Saint Joseph
        <small>Miniara — Médical</small>
      </div>
    </div>
    <p class="login-title">Connexion</p>
    <p class="login-sub">Accès réservé aux administrateurs</p>

    <?php if ($loginError): ?>
      <div class="login-error">⚠️ <?= htmlspecialchars($loginError) ?></div>
    <?php endif; ?>

    <form method="POST">
      <input type="hidden" name="action" value="login">
      <div class="login-field">
        <label for="username">Nom d'utilisateur</label>
        <input type="text" id="username" name="username" autocomplete="username" required
               value="<?= htmlspecialchars($_POST['username'] ?? '') ?>">
      </div>
      <div class="login-field">
        <label for="password">Mot de passe</label>
        <input type="password" id="password" name="password" autocomplete="current-password" required>
      </div>
      <button type="submit" class="login-btn">Se connecter</button>
    </form>
  </div>
</div>

<?php else: ?>
<!-- ══════════════════════════════ AUTHENTICATED LAYOUT -->

<header>
  <div class="h-left">
    <button class="burger" onclick="toggleMenu()" aria-label="Menu">
      <span></span><span></span><span></span>
    </button>
    <img src="Logo.jpg" class="school-logo" alt="Logo">
    <div class="school-name">
      Collège Saint Joseph
      <small>Miniara — Médical</small>
    </div>
  </div>
  <div class="h-right">
    <span class="user-chip">
      👤 <?= htmlspecialchars($_SESSION['user_firstName'] . ' ' . $_SESSION['user_lastName']) ?>
    </span>
    <button class="h-btn" onclick="toggleTheme()" title="Thème">🌙</button>
    <a href="?logout=1" class="h-btn" title="Déconnexion">🚪 Déconnexion</a>
  </div>
</header>

<div class="wrapper">

<aside id="sidebar">
<ul>

<li><div class="nav-section">Médical</div></li>
<li><a onclick="loadPage('fiche_suivi.php')">
  <span class="nav-icon">🩺</span>Fiche Médicale
</a></li>

<li><div class="nav-divider"></div></li>

<li><div class="nav-section">Absences</div></li>
<li><a onclick="loadPage('_listeabsenceclassedateka.php')">
  <span class="nav-icon">📋</span>Liste Absence
</a></li>
<li><a onclick="loadPage('_listeabsencecycle.php')">
  <span class="nav-icon">🔄</span>Liste Absence par Cycle
</a></li>
<li><a onclick="loadPage('_listeabsenceEcole.php')">
  <span class="nav-icon">🏫</span>Liste Absence École
</a></li>

<div style="height:24px"></div>
</ul>
</aside>

<main>
  <div id="dashboard">
    <p class="dash-greeting">Menu Médical</p>
    <p class="dash-sub">Notre Dame de la Paix — Dora</p>
    <div class="icon-grid">
      <div class="icon-card" onclick="loadPage('fiche_suivi.php')">
        <span class="ic-emoji">🩺</span>
        <span class="ic-label">Fiche Médicale</span>
      </div>
      <div class="icon-card" onclick="loadPage('_listeabsenceclassedateka.php')">
        <span class="ic-emoji">📋</span>
        <span class="ic-label">Liste Absence</span>
      </div>
      <div class="icon-card" onclick="loadPage('_listeabsencecycle.php')">
        <span class="ic-emoji">🔄</span>
        <span class="ic-label">Absence par Cycle</span>
      </div>
      <div class="icon-card" onclick="loadPage('_listeabsenceEcole.php')">
        <span class="ic-emoji">🏫</span>
        <span class="ic-label">Absence École</span>
      </div>
    </div>
  </div>

  <iframe id="content-frame" name="john1"></iframe>
</main>

</div><!-- .wrapper -->

<script>
function loadPage(url) {
  var frame = document.getElementById('content-frame');
  var dash  = document.getElementById('dashboard');
  frame.src = url;
  frame.style.display = 'block';
  dash.style.display  = 'none';
  document.getElementById('sidebar').classList.remove('open');
  document.querySelectorAll('aside a').forEach(a => a.closest('li').classList.remove('active'));
  event && event.currentTarget && event.currentTarget.closest('li').classList.add('active');
}
function toggleMenu() {
  document.getElementById('sidebar').classList.toggle('open');
}
function toggleTheme() {
  document.body.classList.toggle('dark');
  localStorage.setItem('theme', document.body.classList.contains('dark') ? 'dark' : 'light');
}
if (localStorage.getItem('theme') === 'dark') document.body.classList.add('dark');
</script>

<?php endif; ?>
</body>
</html>
