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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $studentId = intval($_POST['studentId'] ?? 0);

    // Get posted values
    $studentFirstName = mysqli_real_escape_string($link, $_POST['studentFirstName'] ?? '');
    $studentLastName  = mysqli_real_escape_string($link, $_POST['studentLastName'] ?? '');
    $fatherFirstName  = mysqli_real_escape_string($link, $_POST['fatherFirstName'] ?? '');
    $username         = mysqli_real_escape_string($link, $_POST['username'] ?? '');
    $password         = mysqli_real_escape_string($link, $_POST['password'] ?? '');

    if ($studentId) {
        // Get the userID linked to this student
        $res = mysqli_query($link, "SELECT userID FROM students WHERE id=$studentId");
        if (!$res || mysqli_num_rows($res) == 0) {
            die("❌ Élève introuvable !");
        }
        $row = mysqli_fetch_assoc($res);
        $userID = $row['userID'];

        // ✅ Synchronize lastName in both tables
        $commonLastName = $studentLastName;

        // Update students table
        $sql1 = "UPDATE students 
                 SET firstName='$studentFirstName', lastName='$commonLastName' 
                 WHERE id=$studentId";

        // Update users table
        $sql2 = "UPDATE users 
                 SET firstName='$fatherFirstName', lastName='$commonLastName', 
                     username='$username', password='$password' 
                 WHERE id=$userID";

        $ok1 = mysqli_query($link, $sql1);
        $ok2 = mysqli_query($link, $sql2);

        if ($ok1 && $ok2) {
            echo "✅ Sauvegarde réussie ! (Nom synchronisé)";
        } else {
            echo "❌ Erreur SQL : " . mysqli_error($link);
        }
    } else {
        echo "❌ ID de l'élève manquant !";
    }
}
?>
