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

/* -------------------------
   GET parameters
-------------------------- */
$classID   = intval($_GET['classID'] ?? 0);
$studentID = intval($_GET['studentID'] ?? 0);

/* -------------------------
   Fetch classes
-------------------------- */
$classes = mysqli_query($link, "SELECT * FROM classes ORDER BY name");

/* -------------------------
   Fetch students
-------------------------- */
$students = null;
if ($classID > 0) {
    $students = mysqli_query(
        $link,
        "SELECT * FROM students WHERE classID=$classID ORDER BY lastName, firstName"
    );
}

/* -------------------------
   Fetch selected student
-------------------------- */
$student = null;
if ($studentID > 0) {
    $res = mysqli_query($link, "
        SELECT s.*, c.name AS className,
               u.firstName AS fatherFirst, u.lastName AS fatherLast
        FROM students s
        JOIN classes c ON s.classID = c.id
        LEFT JOIN users u ON s.userID = u.id
        WHERE s.id=$studentID
    ");
    $student = mysqli_fetch_assoc($res);
}

/* -------------------------
   Fetch fiche if exists
-------------------------- */
$fiche = null;
if ($classID && $studentID) {
    $r = mysqli_query($link,
        "SELECT * FROM fiche_suivi
         WHERE classID=$classID AND studentID=$studentID"
    );
    if ($r && mysqli_num_rows($r) > 0) {
        $fiche = mysqli_fetch_assoc($r);
    }
}

/* -------------------------
   Helpers
-------------------------- */
function f($fiche, $k){ return htmlspecialchars($fiche[$k] ?? ''); }
function chk($fiche,$k,$v){ return (isset($fiche[$k]) && $fiche[$k]==$v)?'checked':''; }
function sel($fiche,$k,$v){ return (isset($fiche[$k]) && $fiche[$k]==$v)?'selected':''; }
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fiche de suivi élève</title>

<link rel="stylesheet" href="w3.css">

<style>
body{
    background:#f2f2f2;
}
.container{
    max-width:1000px;
    margin:auto;
}
.card{
    background:#fff;
    border-radius:8px;
    padding:20px;
    margin-bottom:25px;
}
h2,h3{
    margin-top:0;
}
.section-title{
    border-left:5px solid #4CAF50;
    padding-left:10px;
    margin:30px 0 15px;
}
label{
    font-weight:600;
    display:block;
    margin-top:10px;
}
input, select, textarea{
    width:100%;
}
.radio-group label{
    display:inline-block;
    margin-right:20px;
    font-weight:normal;
}
.table-wrap{
    overflow-x:auto;
}
small{
    color:#666;
}

/* -------------------------
   Custom dropdown for students
-------------------------- */
.custom-select {
    position: relative;
    width: 100%;
    font-size: 16px;
}

.custom-select-trigger {
    display: block;
    padding: 10px;
    background: #fff;
    border-radius: 5px;
    border: 1px solid #ccc;
    cursor: pointer;
}

.custom-options {
    display: none;
    position: absolute;
    background: #fff;
    border: 1px solid #ccc;
    width: 100%;
    max-height: 200px;
    overflow-y: auto;
    border-radius: 5px;
    z-index: 10;
}

.custom-options li {
    padding: 10px;
    cursor: pointer;
}

.custom-options li:hover {
    background: #f2f2f2;
}

.custom-options li .red-star {
    color: red;
    font-weight: bold;
    margin-left: 5px;
}
</style>
</head>

<body class="w3-padding">

<div class="container">

<div class="card">
<h2 class="w3-center">📘 Fiche de suivi – Élève</h2>

<!-- SELECT CLASS -->
<form method="get">
<label>Classe</label>
<select name="classID" class="w3-select" onchange="this.form.submit()">
<option value="">-- Sélectionner une classe --</option>
<?php while($c=mysqli_fetch_assoc($classes)): ?>
<option value="<?= $c['id'] ?>" <?= ($c['id']==$classID)?'selected':'' ?>>
<?= htmlspecialchars($c['name']) ?>
</option>
<?php endwhile; ?>
</select>
</form>

<!-- SELECT STUDENT -->
<?php if($classID && $students): ?>

<?php
// Get IDs of students who already have a fiche in this class
$fiche_ids = [];
$res_fiche_ids = mysqli_query($link, "SELECT studentID FROM fiche_suivi WHERE classID=$classID");
while($row=mysqli_fetch_assoc($res_fiche_ids)){
    $fiche_ids[] = $row['studentID'];
}
?>

<form method="get" class="w3-margin-top">
<input type="hidden" name="classID" value="<?= $classID ?>">

<div class="custom-select">
    <div class="custom-select-trigger">
        <?= $studentID ? htmlspecialchars($student['lastName']." ".$student['firstName']) : '-- Sélectionner un élève --' ?>
    </div>
    <ul class="custom-options">
        <?php
        // Reset students pointer
        mysqli_data_seek($students, 0);
        while($s=mysqli_fetch_assoc($students)):
        ?>
        <li data-value="<?= $s['id'] ?>">
            <?= htmlspecialchars($s['lastName']." ".$s['firstName']) ?>
            <?php if(in_array($s['id'],$fiche_ids)): ?>
                <span class="red-star">*</span>
            <?php endif; ?>
        </li>
        <?php endwhile; ?>
    </ul>
</div>

<input type="hidden" name="studentID" id="studentIDHidden" value="<?= $studentID ?>">
</form>

<?php endif; ?>
</div>

<?php if($student): ?>
<form method="post" action="save_fiche.php">

<input type="hidden" name="classID" value="<?= $classID ?>">
<input type="hidden" name="studentID" value="<?= $studentID ?>">

<div class="card w3-light-grey">
<p><b>Nom :</b> <?= $student['lastName']." ".$student['firstName'] ?></p>
<p><b>Classe :</b> <?= $student['className'] ?></p>
<p><b>Père :</b> <?= $student['fatherFirst']." ".$student['fatherLast'] ?></p>
</div>

<div class="card">
<h3 class="section-title">Informations générales</h3>

<label>Date de naissance</label>
<input type="date" name="date_naissance" value="<?= f($fiche,'date_naissance') ?>">

<label>Sexe</label>
<select name="sexe">
<option value="">-- Choisir --</option>
<option value="Female" <?= sel($fiche,'sexe','Female') ?>>Female</option>
<option value="Male" <?= sel($fiche,'sexe','Male') ?>>Male</option>
</select>
</div>

<div class="card">
<h3 class="section-title">1. Famille et environnement</h3>

<label>Adresse</label>
<textarea name="adresse"><?= f($fiche,'adresse') ?></textarea>

<label>Email</label>
<input type="email" name="email" value="<?= f($fiche,'email') ?>">

<h4>Parents / Tuteur</h4>

<div class="table-wrap">
<table class="w3-table w3-bordered w3-small">
<tr class="w3-light-grey">
<th>Relation</th>
<th>Nom</th>
<th>Naissance</th>
<th>Nationalité</th>
<th>Santé</th>
<th>Profession</th>
<th>Téléphone</th>
</tr>

<?php
$rows = ['pere'=>'Père','mere'=>'Mère','tuteur'=>'Tuteur'];
foreach($rows as $k=>$label):
?>
<tr>
<td><?= $label ?></td>
<td><input type="text" name="<?= $k ?>_nom" value="<?= f($fiche,$k.'_nom') ?>"></td>
<td><input type="date" name="<?= $k ?>_naissance" value="<?= f($fiche,$k.'_naissance') ?>"></td>
<td><input type="text" name="<?= $k ?>_nat" value="<?= f($fiche,$k.'_nat') ?>"></td>
<td><input type="text" name="<?= $k ?>_sante" value="<?= f($fiche,$k.'_sante') ?>"></td>
<td><input type="text" name="<?= $k ?>_prof" value="<?= f($fiche,$k.'_prof') ?>"></td>
<td><input type="text" name="<?= $k ?>_tel" value="<?= f($fiche,$k.'_tel') ?>"></td>
</tr>
<?php endforeach; ?>
</table>
</div>

<label>Autres membres vivant avec l’élève</label>
<textarea name="autres_membres"><?= f($fiche,'autres_membres') ?></textarea>
</div>

<div class="card">
<h3 class="section-title">2. Scolarité et vie sociale</h3>

<label>Enseignant(e) principal(e)</label>
<input type="text" name="enseignant" value="<?= f($fiche,'enseignant') ?>">

<label>Assiduité</label>
<div class="radio-group">
<label><input type="radio" name="assiduite" value="Très régulière" <?= chk($fiche,'assiduite','Très régulière') ?>> Très régulière</label>
<label><input type="radio" name="assiduite" value="Moyenne" <?= chk($fiche,'assiduite','Moyenne') ?>> Moyenne</label>
<label><input type="radio" name="assiduite" value="Irrégulière" <?= chk($fiche,'assiduite','Irrégulière') ?>> Irrégulière</label>
</div>

<label>Retards fréquents</label>
<div class="radio-group">
<label><input type="radio" name="retards" value="Oui" <?= chk($fiche,'retards','Oui') ?>> Oui</label>
<label><input type="radio" name="retards" value="Non" <?= chk($fiche,'retards','Non') ?>> Non</label>
</div>

<label>Matières fortes</label>
<input type="text" name="matieres_fortes" value="<?= f($fiche,'matieres_fortes') ?>">

<label>Matières en difficulté</label>
<input type="text" name="matieres_difficiles" value="<?= f($fiche,'matieres_difficiles') ?>">

<label>Appréciation</label>
<textarea name="appreciation"><?= f($fiche,'appreciation') ?></textarea>
</div>

<div class="card">
<h3 class="section-title">3. État émotionnel</h3>

<div class="radio-group">
<label><input type="radio" name="etat_emotionnel" value="Stable" <?= chk($fiche,'etat_emotionnel','Stable') ?>> Stable</label>
<label><input type="radio" name="etat_emotionnel" value="Variable" <?= chk($fiche,'etat_emotionnel','Variable') ?>> Variable</label>
<label><input type="radio" name="etat_emotionnel" value="Fragile" <?= chk($fiche,'etat_emotionnel','Fragile') ?>> Fragile</label>
</div>

<label>Observations</label>
<textarea name="observations"><?= f($fiche,'observations') ?></textarea>
</div>

<div class="card">
<h3 class="section-title">4. Santé et suivi médical</h3>

<label>Allergies</label>
<div class="radio-group">
<label><input type="radio" name="allergies" value="Oui" <?= chk($fiche,'allergies','Oui') ?>> Oui</label>
<label><input type="radio" name="allergies" value="Non" <?= chk($fiche,'allergies','Non') ?>> Non</label>
</div>

<input type="text" name="allergies_details" value="<?= f($fiche,'allergies_details') ?>">

<label>Problèmes de santé</label>
<input type="text" name="problemes_sante" value="<?= f($fiche,'problemes_sante') ?>">

<label>Traitements / suivi médical</label>
<textarea name="traitements"><?= f($fiche,'traitements') ?></textarea>

<label>Vaccinations à jour</label>
<div class="radio-group">
<label><input type="radio" name="vaccins" value="Oui" <?= chk($fiche,'vaccins','Oui') ?>> Oui</label>
<label><input type="radio" name="vaccins" value="Non" <?= chk($fiche,'vaccins','Non') ?>> Non</label>
</div>
</div>

<button type="submit"
        name="save"
        value="1"
        class="w3-button w3-green w3-block w3-large">
    <?= $fiche ? 'Mettre à jour la fiche' : 'Enregistrer la fiche' ?>
</button>
</form>
<?php endif; ?>

</div>

<!-- -------------------------
     JavaScript for custom dropdown
-------------------------- -->
<script>
document.querySelectorAll('.custom-select').forEach(function(select){
    const trigger = select.querySelector('.custom-select-trigger');
    const options = select.querySelector('.custom-options');
    const hiddenInput = document.getElementById('studentIDHidden');

    // Toggle options
    trigger.addEventListener('click', function(){
        options.style.display = options.style.display === 'block' ? 'none' : 'block';
    });

    // Click option
    options.querySelectorAll('li').forEach(function(option){
        option.addEventListener('click', function(){
            trigger.textContent = option.textContent;
            hiddenInput.value = option.getAttribute('data-value');
            options.style.display = 'none';
            // auto-submit form
            trigger.closest('form').submit();
        });
    });

    // Close dropdown when clicking outside
    document.addEventListener('click', function(e){
        if(!select.contains(e.target)){
            options.style.display = 'none';
        }
    });
});
</script>

</body>
</html>
