<?php 
session_start();
$userprofil = $_SESSION['user'];
if ($userprofil == true) {
    include('includes/header.php');
    require_once "includes/dbconn.php";
} else {
    header("Location: login.php");
    exit();
}

$message = '';
$etudiant = null;
$modules = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['search'])) {
        $matricule = trim($_POST['matricule']);
        $stmt = $conn->prepare("SELECT e.*, c.nom AS nom_classe FROM etudiants e JOIN classes c ON e.classe_id = c.id WHERE e.matricule = ?");
        $stmt->bind_param("s", $matricule);
        $stmt->execute();
        $result = $stmt->get_result();
        $etudiant = $result->fetch_assoc();

        if ($etudiant) {
            $stmtModules = $conn->prepare("SELECT * FROM modules WHERE classe_id = ?");
            $stmtModules->bind_param("i", $etudiant['classe_id']);
            $stmtModules->execute();
            $modules = $stmtModules->get_result()->fetch_all(MYSQLI_ASSOC);
        } else {
            $message = "<div class='alert alert-danger'>Aucun étudiant trouvé avec ce matricule.</div>";
        }
    }

    if (isset($_POST['save_note'])) {
        $etudiant_id = intval($_POST['etudiant_id']);
        $module_id = intval($_POST['module_id']);
        $note = floatval($_POST['note']);
        $session = $_POST['session'];
        $type_note = $_POST['type_note'];

        if ($etudiant_id && $module_id && $note >= 0 && $note <= 20 && in_array($session, ['Normale', 'Rattrapage']) && in_array($type_note, ['Devoir 1', 'Devoir 2', 'Examen'])) {
           $stmt = $conn->prepare("INSERT INTO notes (etudiant_id, module_id, note, session, type_note) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("iidss", $etudiant_id, $module_id, $note, $session, $type_note);

            if ($stmt->execute()) {
                $message = "<div class='alert alert-success'>✅ Note enregistrée avec succès.</div>";
            } else {
                $message = "<div class='alert alert-danger'>❌ Erreur lors de l'enregistrement.</div>";
            }
        } else {
            $message = "<div class='alert alert-warning'>Veuillez remplir correctement tous les champs.</div>";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Ajout de Note</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <style>
        body {
            background-color: #f4f4f4;
        }

        .teal {
            background-color: #008080 !important;
            color: white;
        }

        .teal-light {
            background-color: #e6f2f2;
            border-left: 5px solid #008080;
        }

        .form-section {
            background: white;
            border-radius: 12px;
            box-shadow: 0 0 15px rgba(0, 128, 128, 0.1);
            padding: 25px;
        }

        .form-title {
            color: #008080;
            font-weight: 600;
        }

        .btn-teal {
            background-color: #008080;
            border: none;
            color: white;
        }

        .btn-teal:hover {
            background-color: #006666;
            color: white;
        }
    </style>
</head>
<body class="py-5">

<div class="container">
    <h3 class="form-title mb-4 text-center">Ajouter une Note Étudiant</h3>

    <?= $message ?>

    <!-- Recherche par matricule -->
    <form method="POST" class="row g-3 align-items-end mb-4 form-section">
        <div class="col-md-6">
            <label for="matricule" class="form-label">Matricule Étudiant</label>
            <input type="text" class="form-control" name="matricule" id="matricule" placeholder="Ex: 17188N20" required>
        </div>
        <div class="col-md-3 d-grid">
            <button type="submit" name="search" class="btn btn-teal">🔍 Rechercher</button>
        </div>
    </form>

    <?php if ($etudiant): ?>
        <form method="POST" class="form-section teal-light">
            <input type="hidden" name="etudiant_id" value="<?= $etudiant['id'] ?>">

            <div class="row mb-3">
                <div class="col-md-4">
                    <label class="form-label">Nom</label>
                    <input type="text" class="form-control" value="<?= htmlspecialchars($etudiant['noms']) ?>" disabled>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Prénom</label>
                    <input type="text" class="form-control" value="<?= htmlspecialchars($etudiant['prenom']) ?>" disabled>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Classe</label>
                    <input type="text" class="form-control" value="<?= htmlspecialchars($etudiant['nom_classe']) ?>" disabled>
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-md-4">
                    <label class="form-label">Module</label>
                    <select name="module_id" class="form-select" required>
                        <option value="">-- Sélectionner un module --</option>
                        <?php foreach ($modules as $module): ?>
                            <option value="<?= $module['id'] ?>"><?= htmlspecialchars($module['nom']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Note (/20)</label>
                    <input type="number" name="note" step="0.01" min="0" max="20" class="form-control" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Session</label>
                    <select name="session" class="form-select" required>
                        <option value="Normale">Normale</option>
                        <option value="Rattrapage">Rattrapage</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Type de Note</label>
                    <select name="type_note" class="form-select" required>
                        <option value="">-- Choisir --</option>
                        <option value="Devoir 1">Devoir 1</option>
                        <option value="Devoir 2">Devoir 2</option>
                        <option value="Examen">Examen</option>
                    </select>
                </div>
            </div>

            <div class="d-grid">
                <button type="submit" name="save_note" class="btn btn-teal">💾 Enregistrer la Note</button>
            </div>
        </form>
    <?php endif; ?>
</div>

<!-- Scripts Bootstrap -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>