<?php
session_start();
include 'header.php';
include '_serveur_json.php';
mysqli_set_charset($link, "utf8");
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Liste Élèves</title>
<link rel="stylesheet" href="w3.css">
<style>
body, td, th {
	color: #000033;
	font-family: Arial, sans-serif;
}
body { background-color: #FFF; }
.editable { cursor: text; }

@media print {
	.noprint { display: none; }
	@page { size: A4; margin: 2mm; }
}
</style>
<!-- XLSX JS library -->
<script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>
</head>
<body>

<form method="post" action="" class="w3-container">
<fieldset>
<?php
echo '<div class="noprint">';
echo '<table width="90%" align="left"><tr><td>Classe : ';

// --- Load classes ---
$sql = "SELECT * FROM classes ORDER BY id ASC";
$req = mysqli_query($link, $sql);
if (!$req) die("❌ ERROR: " . mysqli_error($link));

echo '<select name="cont" class="w3-select w3-border w3-light-grey">';
while ($data = mysqli_fetch_assoc($req)) {
    $classe = strtoupper($data['name']);
    $selected = (isset($_POST['cont']) && $_POST['cont'] == $data['id'].';'.$classe) ? 'selected' : '';
    echo '<option value="'.$data['id'].';'.$classe.'" '.$selected.'>'.$classe.'</option>';
}
echo '</select>';
?>
</td>
<td colspan="2">
<label>Date:
<input class="w3-input w3-border w3-light-grey" type="date" name="date1"
value="<?php echo isset($_POST['date1']) ? $_POST['date1'] : date('Y-m-d'); ?>" />
</label>
<button type="button" class="noprint" onclick="window.print()">
<img src="imprimante.png" height="32" width="40" />
</button>
</td></tr>

<tr><td colspan="2">
<input class="w3-btn w3-blue w3-round-medium" type="reset" value="Effacer" /> 
&nbsp;&nbsp;
<input class="w3-btn w3-blue w3-round-medium" type="submit" name="envoyer" value="Envoyer" /> 
&nbsp;&nbsp;
<input class="w3-btn w3-blue w3-round-medium" type="submit" name="quitter" value="Quitter" /> 
</td></tr>
</table></div>
</fieldset>
</form>

<?php
if (isset($_POST['envoyer'])) {
    $cellm = explode(";", $_POST['cont']);
    $classeid = $cellm[0];
    $classe1 = $cellm[1];
    $date1 = $_POST['date1'];

    $sql = "
        SELECT 
            students.id AS studentId,
            students.firstName AS studentFirstName,
            students.lastName AS studentLastName,
            users.firstName AS fatherFirstName,
            users.lastName AS fatherLastName,
            users.username,
            users.password
        FROM students
        JOIN users ON users.id = students.userID
        WHERE students.classID='$classeid'
        ORDER BY students.lastName, students.firstName
    ";
    $req = mysqli_query($link, $sql);
    if (!$req) die("❌ ERROR: " . mysqli_error($link));

    echo "<h3 class='w3-center'>$classe1 — $date1</h3>";

    echo "<table id='tbl_exporttable_to_xls' border='1' cellpadding='5' cellspacing='0' style='width:95%;'>";
    echo "<tr class='w3-light-grey'>
            <th>#</th><th>Nom</th><th>Prénom</th><th>Prénom du père</th>
            <th>Nom d’utilisateur</th><th>Mot de passe</th>
            <th>Actions</th>
          </tr>";

    $num = 1;
    while ($data = mysqli_fetch_assoc($req)) {
        echo "<tr data-studentid='{$data['studentId']}'>
                <td align='center'>{$num}</td>
                <td class='editable' data-field='studentLastName'>".strtoupper($data['studentLastName'])."</td>
                <td class='editable' data-field='studentFirstName'>".strtoupper($data['studentFirstName'])."</td>
                <td class='editable' data-field='fatherFirstName'>".strtoupper($data['fatherFirstName'])."</td>
                <td class='editable' data-field='username'>".htmlspecialchars($data['username'])."</td>
                <td class='editable' data-field='password'>".htmlspecialchars($data['password'])."</td>
                <td>
                    <button class='editBtn'>✏️</button>
                    <button class='saveBtn' style='display:none;'>💾</button>
                </td>
              </tr>";
        $num++;
    }
    echo "</table>";

    echo '<br><button class="w3-btn w3-green w3-round-medium noprint" onclick="ExportToExcel(\'xlsx\')">Exporter en Excel</button>';
}
?>

<script>
// Export table to Excel
function ExportToExcel(type, fn, dl) {
    var elt = document.getElementById('tbl_exporttable_to_xls');
    if (!elt) { alert("Aucune donnée à exporter !"); return; }
    var wb = XLSX.utils.table_to_book(elt, { sheet: "Feuille1" });
    return dl ?
        XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }) :
        XLSX.writeFile(wb, fn || ('Liste_Eleves.' + (type || 'xlsx')));
}

// Edit/Save functionality
document.addEventListener("DOMContentLoaded", function() {
    document.querySelectorAll('.editBtn').forEach(btn => {
        btn.addEventListener('click', function() {
            let row = this.closest('tr');
            row.querySelectorAll('.editable').forEach(td => {
                td.contentEditable = "true";
                td.style.backgroundColor = "#ffffcc";
            });
            row.querySelector('.editBtn').style.display = 'none';
            row.querySelector('.saveBtn').style.display = 'inline';
        });
    });

    document.querySelectorAll('.saveBtn').forEach(btn => {
        btn.addEventListener('click', function() {
            let row = this.closest('tr');
            let studentId = row.dataset.studentid;
            let data = {};
            row.querySelectorAll('.editable').forEach(td => {
                data[td.dataset.field] = td.innerText.trim();
                td.contentEditable = "false";
                td.style.backgroundColor = "";
            });
            row.querySelector('.editBtn').style.display = 'inline';
            row.querySelector('.saveBtn').style.display = 'none';

            // AJAX POST
            let xhr = new XMLHttpRequest();
            xhr.open("POST", "update_student.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            let params = "studentId=" + encodeURIComponent(studentId);
            for (let key in data) {
                params += "&" + key + "=" + encodeURIComponent(data[key]);
            }
            xhr.onload = function() {
                if (xhr.status === 200) {
                    alert(xhr.responseText);
                } else {
                    alert("Erreur lors de la sauvegarde !");
                }
            };
            xhr.send(params);
        });
    });
});
</script>

</body>
</html>
