<?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;
$notes = [];
$moyenne_generale = null;
$total_coefficients = 0;
$total_ponderees = 0;
$matricule = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search'])) {
    $matricule = trim($_POST['matricule']);

    // Récupération des infos de l'étudiant + classe + niveau
    $stmt = $conn->prepare("
        SELECT 
            e.id, 
            e.matricule, 
            e.noms, 
            e.prenom, 
            e.classe_id, 
            c.nom AS classe, 
            n.nom_niveau AS niveau
        FROM etudiants e
        JOIN classes c ON e.classe_id = c.id
        JOIN niveaux n ON c.niveau_id = n.id
        WHERE e.matricule = ?
    ");
    $stmt->bind_param("s", $matricule);
    $stmt->execute();
    $etudiant = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($etudiant) {
        $stmt = $conn->prepare("
            SELECT
                m.id,
                m.nom AS module,
                m.coefficient,
                MAX(CASE WHEN n.type_note = 'Devoir 1' THEN n.note END) AS devoir1,
                MAX(CASE WHEN n.type_note = 'Devoir 2' THEN n.note END) AS devoir2,
                MAX(CASE WHEN n.type_note = 'Examen' THEN n.note END) AS examen
            FROM modules m
            LEFT JOIN notes n ON m.id = n.module_id AND n.etudiant_id = ?
            WHERE m.classe_id = ?
            GROUP BY m.id, m.nom, m.coefficient
            ORDER BY m.nom
        ");
        $stmt->bind_param("ii", $etudiant['id'], $etudiant['classe_id']);
        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $d1 = is_numeric($row['devoir1']) ? $row['devoir1'] : null;
            $d2 = is_numeric($row['devoir2']) ? $row['devoir2'] : null;
            $ex = is_numeric($row['examen']) ? $row['examen'] : null;

            $coef = $row['coefficient'];
            $total_coefficients += $coef;

            if ($d1 !== null || $d2 !== null || $ex !== null) {
                $notes_dispo = array_filter([$d1, $d2, $ex], fn($n) => $n !== null);
                $moyenne = array_sum($notes_dispo) / count($notes_dispo);
                $ponderee = round($moyenne * $coef, 2);
                $total_ponderees += $ponderee;
                $row['note_ponderee'] = $ponderee;
            } else {
                $row['note_ponderee'] = 0;
            }

            $notes[] = $row;
        }

        if ($total_coefficients > 0) {
            $moyenne_generale = round($total_ponderees / $total_coefficients, 2);
        }

        $stmt->close();
    } else {
        $message = "<div class='alert alert-danger'>Aucun étudiant trouvé avec ce matricule.</div>";
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8" />
    <title>Relevé de Notes</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <style>
        body {
            background-color: #f8f9fa;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .container {
            padding: 0;
            max-width: 100%;
        }
        .header-section {
            background-color: #800000;
            color: white;
            padding: 20px 0;
            margin-bottom: 20px;
        }
        h3 {
            color: white;
            margin: 0;
            padding: 0 15px;
        }
        .btn-success {
            background-color: #800000;
            border-color: #700000;
        }
        .btn-success:hover {
            background-color: #900000;
            border-color: #800000;
        }
        .table-success {
            background-color: #800000;
            color: white;
        }
        .table-success th {
            border-color: #700000;
        }
        .alert-info {
            background-color: #e6c7c7;
            border-color: #d9b3b3;
            color: #800000;
        }
        .form-control:focus {
            border-color: #800000;
            box-shadow: 0 0 0 0.25rem rgba(128, 0, 0, 0.25);
        }
        .table-bordered {
            border-color: #dee2e6;
        }
        .table-bordered th, 
        .table-bordered td {
            border-color: #dee2e6;
        }
        .table-striped tbody tr:nth-of-type(odd) {
            background-color: rgba(128, 0, 0, 0.05);
        }
    </style>
</head>
<body>
<div class="header-section">
    <div class="container">
        <h3>Relevé de Notes individuel</h3>
    </div>
</div>

<div class="container px-3">
    <?= $message ?>

    <form method="POST" class="row g-3 mb-4 align-items-center justify-content-start">
        <div class="col-md-4">
            <input type="text" name="matricule" class="form-control" placeholder="Matricule" required value="<?= htmlspecialchars($matricule) ?>" />
        </div>
        <div class="col-md-auto">
            <button type="submit" name="search" class="btn btn-success">Rechercher</button>
        </div>
    </form>

    <?php if ($etudiant): ?>
        <div class="mb-4">
            <strong>Étudiant :</strong> <?= htmlspecialchars($etudiant['noms'] . ' ' . $etudiant['prenom']) ?><br />
            <strong>Matricule :</strong> <?= htmlspecialchars($etudiant['matricule']) ?><br />
            <strong>Classe :</strong> <?= htmlspecialchars($etudiant['classe']) ?><br />
            <strong>Niveau :</strong> <?= htmlspecialchars($etudiant['niveau']) ?>
        </div>

        <div class="table-responsive">
            <table class="table table-bordered table-striped">
                <thead class="table-success">
                    <tr>
                        <th>#</th>
                        <th>Module</th>
                        <th>Coef.</th>
                        <th>Devoir 1</th>
                        <th>Devoir 2</th>
                        <th>Examen</th>
                        <th>Note Pondérée</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($notes)): ?>
                        <?php foreach ($notes as $i => $row): ?>
                            <tr>
                                <td><?= $i + 1 ?></td>
                                <td><?= htmlspecialchars($row['module']) ?></td>
                                <td><?= $row['coefficient'] ?></td>
                                <td><?= $row['devoir1'] ?? '-' ?></td>
                                <td><?= $row['devoir2'] ?? '-' ?></td>
                                <td><?= $row['examen'] ?? '-' ?></td>
                                <td><?= is_numeric($row['note_ponderee']) ? $row['note_ponderee'] : '-' ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="7" class="text-center">Aucune note trouvée</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($moyenne_generale !== null): ?>
            <div class="alert alert-info mt-3">
                <strong>🎓 Moyenne Générale Pondérée :</strong> <?= $moyenne_generale ?>/20
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<?php include('includes/footer.php'); ?>
</body>
</html>