<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include("_serveur.php");

// Resize and compress to ≤100KB
function resizeImage($sourcePath, $targetPath, $ext, $maxSize = 100 * 1024) {
    list($w, $h) = getimagesize($sourcePath);
    $ratio = $w / $h;
    $newW = $w;
    $newH = $h;
    $quality = 85;

    while (filesize($sourcePath) > $maxSize && $quality > 10) {
        $newW = $newW * 0.9;
        $newH = $newW / $ratio;
        $dst = imagecreatetruecolor($newW, $newH);

        switch ($ext) {
            case 'jpg':
            case 'jpeg':
                $src = imagecreatefromjpeg($sourcePath);
                break;
            case 'png':
                $src = imagecreatefrompng($sourcePath);
                imagealphablending($dst, false);
                imagesavealpha($dst, true);
                break;
            case 'gif':
                $src = imagecreatefromgif($sourcePath);
                break;
            default:
                return false;
        }

        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newW, $newH, $w, $h);
        imagejpeg($dst, $targetPath, $quality);
        imagedestroy($dst);
        imagedestroy($src);

        clearstatcache();
        $quality -= 5;
    }

    return filesize($targetPath) <= $maxSize;
}

// Fetch all classes for dropdown
$class_result = $link->query("SELECT id, name FROM classes ORDER BY id");

// Get selected class ID from GET, or null if none selected
$selected_class_id = isset($_GET['class_id']) ? intval($_GET['class_id']) : null;

// Handle multiple photo uploads at once
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['class_id']) && isset($_FILES['photos'])) {
    $class_id = intval($_POST['class_id']);
    foreach ($_FILES['photos']['name'] as $student_id_str => $name) {
        $student_id = intval($student_id_str);
        if ($_FILES['photos']['error'][$student_id_str] === 0) {
            $tmp_name = $_FILES['photos']['tmp_name'][$student_id_str];
            $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'gif'];
            if (in_array($ext, $allowed)) {
                $filename = "student_" . $student_id . "." . $ext;
                $target = "img/" . $filename;
                if ($_FILES['photos']['size'][$student_id_str] > 100 * 1024) {
                    copy($tmp_name, $target);
                    if (!resizeImage($target, $target, $ext)) {
                        echo "<p style='color:red;'>✘ Resize failed for student $student_id.</p>";
                        unlink($target);
                        continue;
                    }
                } else {
                    move_uploaded_file($tmp_name, $target);
                }
                if (file_exists($target) && filesize($target) <= 100 * 1024) {
                    $stmt = $link->prepare("UPDATE students SET photo = ? WHERE id = ?");
                    $stmt->bind_param("si", $target, $student_id);
                    $stmt->execute();
                    echo "<p style='color:green;'>✔ Photo uploaded for student ID $student_id.</p>";
                }
            } else {
                echo "<p style='color:red;'>✘ Invalid file type for student ID $student_id.</p>";
            }
        }
    }
}

// If a class is selected, fetch its students only
$students = [];
if ($selected_class_id) {
    $stmt = $link->prepare("SELECT id, firstName, lastName, photo FROM students WHERE classID = ? ORDER BY firstName,lastName ");
    $stmt->bind_param("i", $selected_class_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $students[] = $row;
    }
}
?>

<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title>Upload Student Photos</title>
<style>
    table { border-collapse: collapse; width: 100%; margin-top: 20px; }
    th, td { border: 1px solid #ccc; padding: 6px; text-align: center; }
    img { width: 50px; border-radius: 4px; }
    input[type=file] { width: 100%; }
</style>
</head>
<body>
<h1>Importer des Photos par Classe</h1>

<form method="GET" action="">
    <label for="class_id">Choisir class:</label>
    <select id="class_id" name="class_id" onchange="this.form.submit()" required>
        <option value="">-- Choisir Classe --</option>
        <?php while ($class = $class_result->fetch_assoc()): ?>
            <option value="<?= $class['id'] ?>" <?= ($class['id'] == $selected_class_id) ? 'selected' : '' ?>>
                <?= htmlspecialchars($class['name']) ?>
            </option>
        <?php endwhile; ?>
    </select>
</form>

<?php if ($selected_class_id): ?>
<form method="POST" enctype="multipart/form-data">
    <input type="hidden" name="class_id" value="<?= $selected_class_id ?>">
    <table>
        <tr><th>Numero</th><th>Nom</th><th>Photo</th><th>Importer Nouveau Photo</th></tr>
        <?php foreach ($students as $student):
            $photo = ($student['photo'] && file_exists($student['photo'])) ? $student['photo'] : 'img/default.jpg';
            $name = htmlspecialchars($student['firstName'] . ' ' . $student['lastName']);
        ?>
        <tr>
            <td><?= $student['id'] ?></td>
            <td><?= $name ?></td>
            <td><img src="<?= $photo ?>" alt="photo"></td>
            <td><input type="file" name="photos[<?= $student['id'] ?>]" accept=".jpg,.jpeg,.png,.gif"></td>
        </tr>
        <?php endforeach; ?>
    </table>
    <button type="submit">Importer Photos Selectionner</button>
</form>
<?php endif; ?>

</body>
</html>

<?php $link->close(); ?>
