<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Inscriptions des Nouveaux Élèves</title>
<link rel="stylesheet" href="w3.css">
<style>
body, td, th { color: #000033; }
body { background-color: #FFF; }

table {
  width: 100%;
  margin-top: 15px;
  border-spacing: 10px;
}
th, td {
  padding: 10px;
}
tr { line-height: 1.8; }
table tr:nth-child(even) { background-color: #f2f2f2; }
table tr:nth-child(odd) { background-color: #ffffff; }

.center {
  text-align: center;
  margin-top: 15px;
}
fieldset { margin-top: 15px; }
</style>
</head>

<body>
<?php
include '_serveur.php';
mysqli_set_charset($link, "utf8");

$studentID = htmlspecialchars($_GET['studentID'] ?? '');
$userID    = htmlspecialchars($_GET['userID'] ?? '');
$first     = htmlspecialchars($_GET['first'] ?? '');
$father    = htmlspecialchars($_GET['father'] ?? '');
$last      = htmlspecialchars($_GET['last'] ?? '');
$user      = htmlspecialchars($_GET['user'] ?? '');
$pass      = htmlspecialchars($_GET['pass'] ?? '');

$sql = 'SELECT id, name FROM classes ORDER BY name';
$req = mysqli_query($link, $sql);
if (!$req) { die("Erreur SQL : " . mysqli_error($link)); }
?>

<form method="post" action="">
  <div class="noprint">
    <button type="button" onclick="window.print()"><img src="imprimante.png" height="32" width="40" /></button>
    <a href="javascript:history.go(-2)"><button type="button">Retourner</button></a>
  </div>

  <input type="hidden" name="userID" value="<?= $userID ?>">
  <input type="hidden" name="lastname" value="<?= $last ?>">

  <?php include 'header.php'; ?>

  <fieldset>
    <legend>Inscription</legend>
    <table>
      <tr>
        <th>Classe</th>
        <th>Prénom</th>
      </tr>
      <tr>
        <td>
          <select name="class" class="w3-select w3-border w3-pale-blue" required>
            <option value="">-- Choisir --</option>
            <?php while ($data = mysqli_fetch_array($req)): ?>
              <option value="<?= htmlspecialchars($data['id']) ?>"><?= htmlspecialchars($data['name']) ?></option>
            <?php endwhile; ?>
          </select>
        </td>
        <td><input type="text" name="first" placeholder="Taper le prénom" required /></td>
      </tr>

      <tr>
        <th>Nom du Père</th>
        <th>Famille</th>
      </tr>
      <tr>
        <td><?= htmlspecialchars($father) ?></td>
        <td><?= htmlspecialchars($last) ?></td>
      </tr>

      <tr>
        <th>Nom de l'utilisateur</th>
        <th>Mot de passe</th>
      </tr>
      <tr>
        <td><?= htmlspecialchars($user) ?></td>
        <td><?= htmlspecialchars($pass) ?></td>
      </tr>
    </table>

    <div class="center">
      <input type="reset" value="Effacer" class="w3-button w3-gray">
      <input type="submit" name="envoyer" value="Envoyer" class="w3-button w3-blue">
    </div>
  </fieldset>
</form>

<?php
// --- Insert new student ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['envoyer'])) {
    $classeid  = trim($_POST['class']);
    $firstname = trim($_POST['first']);
    $userID    = trim($_POST['userID']);
    $lastname  = trim($_POST['lastname']);
    $photo     = null;

    if ($firstname === '' || $classeid === '') {
        echo "<script>alert('Veuillez remplir tous les champs obligatoires.');</script>";
    } else {
        $stmt = mysqli_prepare($link,
            "INSERT INTO students (userID, firstName, lastName, classID, photo)
             VALUES (?, ?, ?, ?, ?)"
        );

        if (!$stmt) {
            die("<p style='color:red'>Erreur de préparation : " . mysqli_error($link) . "</p>");
        }

        mysqli_stmt_bind_param($stmt, 'sssis', $userID, $firstname, $lastname, $classeid, $photo);

        if (mysqli_stmt_execute($stmt)) {
            echo "<script>alert('✅ Élève enregistré avec succès.');</script>";
        } else {
            echo "<p style='color:red; text-align:center;'>❌ Erreur lors de l’enregistrement : " . mysqli_stmt_error($stmt) . "</p>";
        }

        mysqli_stmt_close($stmt);
    }
}
?>

<!-- ✅ Family members listing -->
<?php
if (!empty($userID)) {
    $sql = "
        SELECT s.firstName, s.lastName, c.name AS className
        FROM students s
        LEFT JOIN classes c ON s.classID = c.id
        WHERE s.userID = '".mysqli_real_escape_string($link, $userID)."'
        ORDER BY c.name, s.firstName
    ";
    $result = mysqli_query($link, $sql);
    if ($result && mysqli_num_rows($result) > 0) {
        echo "<fieldset><legend>Famille: ".htmlspecialchars($last)."</legend>";
        echo "<table border='1' cellpadding='8' cellspacing='0'>";
        echo "<tr style='background:#CCE5FF;'><th>Prénom</th><th>Nom</th><th>Classe</th></tr>";
        while ($row = mysqli_fetch_assoc($result)) {
            echo "<tr>
                    <td>".htmlspecialchars($row['firstName'])."</td>
                    <td>".htmlspecialchars($row['lastName'])."</td>
                    <td>".htmlspecialchars($row['className'])."</td>
                  </tr>";
        }
        echo "</table></fieldset>";
    }
}
mysqli_close($link);
?>
</body>
</html>
