<?php
include '_serveur.php';

// Get values (both GET and POST to persist data)
$userID   = $_POST['userID'] ?? $_GET['userID'] ?? '';
$lastname = $_POST['lastname'] ?? $_GET['lastname'] ?? '';
$username = $_POST['username'] ?? $_GET['username'] ?? '';
$father   = $_POST['father'] ?? $_GET['father'] ?? '';
$password = $_POST['password'] ?? $_GET['password'] ?? '';

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

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<title>Inscription Élèves</title>
<link rel="stylesheet" href="w3.css">
<style>
body, td, th { color:#000033; font-family: Arial, sans-serif; }
body { background-color:#FFF; padding: 10px; }
table { width:100%; border-spacing:10px; margin-top:15px; border-collapse: collapse; }
th, td { padding:8px; text-align:center; border:1px solid #ddd; }
tr:nth-child(even){background-color:#f2f2f2;}
tr:nth-child(odd){background-color:#ffffff;}
.center { text-align:center; margin-top:15px; }
fieldset { border-radius:10px; border:1px solid #ccc; padding:15px; }
legend { font-weight:bold; color:#003366; }
h3 { color:#003366; }
.success { color:green; text-align:center; font-weight:bold; }
.error { color:red; text-align:center; }
</style>
</head>
<body>

<div class="noprint">
  <button type="button" onclick="window.print()"><img src="imprimante.png" height="32" width="40" /></button>
  <button type="button" onclick="window.location.href='inscription_Fam.php'">Retour à l'inscription</button>
</div>

<form method="post" action="">
  <fieldset>
    <legend>Ajouter un élève à la famille <strong><?= htmlspecialchars($lastname) ?></strong></legend>

    <!-- Hidden data -->
    <input type="hidden" name="userID" value="<?= htmlspecialchars($userID) ?>">
    <input type="hidden" name="lastname" value="<?= htmlspecialchars($lastname) ?>">
    <input type="hidden" name="fathername" value="<?= htmlspecialchars($father) ?>">
    <input type="hidden" name="username" value="<?= htmlspecialchars($username) ?>">
    <input type="hidden" name="password" value="<?= htmlspecialchars($password) ?>">

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

    <div class="center">
      <input type="reset" value="Effacer" class="w3-button w3-light-grey">
      <input type="submit" name="envoyer" value="Enregistrer l'élève" class="w3-button w3-blue">
    </div>
  </fieldset>
</form>

<?php
// --- Handle submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['envoyer'])) {
    $userID     = $_POST['userID'];
    $lastname   = $_POST['lastname'];
    $classeid   = $_POST['class'];
    $firstname  = trim($_POST['first']);
    $username   = $_POST['username'];
    $password   = $_POST['password'];
    $fathername = $_POST['fathername'];
    $photo      = null;

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

            if (mysqli_stmt_execute($stmt)) {
                echo "<script>
                        alert('✅ Élève \"$firstname\" ajouté avec succès.');
                        window.location.href = '_continuerinsfam.php?userID=" . urlencode($userID) . 
                            "&father=" . urlencode($fathername) . 
                            "&lastname=" . urlencode($lastname) . 
                            "&username=" . urlencode($username) . 
                            "&password=" . urlencode($password) . "';
                      </script>";
            } else {
                echo "<p class='error'>❌ Erreur MySQL : " . mysqli_error($link) . "</p>";
            }
            mysqli_stmt_close($stmt);
        } else {
            echo "<p class='error'>Erreur préparation : " . mysqli_error($link) . "</p>";
        }
    }
}

// --- Show list of already added students for this family ---
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 = " . intval($userID) . "
            ORDER BY c.name, s.firstName";
    $res = mysqli_query($link, $sql);

    if ($res && mysqli_num_rows($res) > 0) {
        echo "<h3>Élèves déjà inscrits dans la famille « " . htmlspecialchars($lastname) . " » :</h3>";
        echo "<table>";
        echo "<tr style='background:#003366;color:white;'><th>Prénom</th><th>Nom</th><th>Classe</th></tr>";
        while ($row = mysqli_fetch_assoc($res)) {
            echo "<tr>
                    <td>" . htmlspecialchars($row['firstName']) . "</td>
                    <td>" . htmlspecialchars($row['lastName']) . "</td>
                    <td>" . htmlspecialchars($row['className']) . "</td>
                  </tr>";
        }
        echo "</table>";
    } else {
        echo "<p style='text-align:center;color:#666;'>Aucun élève enregistré pour cette famille pour l’instant.</p>";
    }
}

mysqli_close($link);
?>
</body>
</html>
