<?php
/**
 * Portail — Notes et bulletins (élève / parent)
 * Utilise : academic_periods, v_student_grades, v_student_period_averages
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';

checkRole(['student', 'parent']);

$userId   = (int)$_SESSION['user_id'];
$userRole = $_SESSION['user_role'];

function getAccessibleStudentIds(PDO $pdo, int $userId, string $role): array {
    if ($role === 'student') {
        $s = $pdo->prepare("SELECT id FROM students WHERE user_id=? LIMIT 1");
        $s->execute([$userId]); $row = $s->fetch();
        return $row ? [(int)$row['id']] : [];
    }
    $s = $pdo->prepare("SELECT student_id FROM parent_students WHERE user_id=?");
    $s->execute([$userId]);
    return array_column($s->fetchAll(), 'student_id');
}

$studentIds = getAccessibleStudentIds($pdo, $userId, $userRole);

$filterStudent = isset($_GET['student_id']) ? (int)$_GET['student_id'] : ($studentIds[0] ?? 0);
$filterPeriod  = isset($_GET['period_id'])  ? (int)$_GET['period_id']  : 0;

if ($filterStudent && !in_array($filterStudent, $studentIds)) {
    flashMessage('error', 'Accès non autorisé.'); header('Location: dashboard.php'); exit;
}

// Infos élèves
$studentsInfo = [];
if (!empty($studentIds)) {
    $in = implode(',', array_fill(0, count($studentIds), '?'));
    $stmt = $pdo->prepare("SELECT s.id, CONCAT(s.last_name,' ',s.first_name) AS full_name, c.name AS class_name
        FROM students s LEFT JOIN classes c ON s.class_id=c.id WHERE s.id IN ($in) ORDER BY s.last_name, s.first_name");
    $stmt->execute($studentIds); $studentsInfo = $stmt->fetchAll();
}

// Périodes disponibles pour cet élève
$periods = [];
if ($filterStudent) {
    $stmt = $pdo->prepare("SELECT DISTINCT ap.* FROM academic_periods ap
        JOIN grades g ON ap.trimestre=g.trimestre AND ap.academic_year=g.academic_year AND ap.school_id=COALESCE(g.school_id,0) WHERE g.student_id=?
        ORDER BY ap.academic_year DESC, ap.trimestre");
    $stmt->execute([$filterStudent]); $periods = $stmt->fetchAll();
    if (!$filterPeriod && !empty($periods)) $filterPeriod = (int)$periods[0]['id'];
}

// Notes + bulletin
$grades       = [];
$bulletinData = [];
$generalAvg   = null;
$selectedPeriodName = '';

if ($filterStudent && $filterPeriod) {
    // Détail des notes via la vue
    $stmt = $pdo->prepare("SELECT * FROM v_student_grades WHERE student_id=? AND period_id=? ORDER BY subject_name, grade_date");
    $stmt->execute([$filterStudent, $filterPeriod]); $grades = $stmt->fetchAll();

    // Moyenne générale via la vue
    $stmt = $pdo->prepare("SELECT * FROM v_student_period_averages WHERE student_id=? AND period_id=?");
    $stmt->execute([$filterStudent, $filterPeriod]); $bRow = $stmt->fetch();
    if ($bRow) $generalAvg = round((float)$bRow['weighted_average'], 2);

    // Détail par matière
    $stmt = $pdo->prepare("SELECT subject_name, subject_coefficient AS coefficient,
        AVG(score/score_max*20) AS avg_score, COUNT(*) AS nb_grades
        FROM v_student_grades WHERE student_id=? AND period_id=?
        GROUP BY subject_name, subject_coefficient ORDER BY subject_name");
    $stmt->execute([$filterStudent, $filterPeriod]); $bulletinData = $stmt->fetchAll();

    foreach ($periods as $p) { if ($p['id'] == $filterPeriod) { $selectedPeriodName = $p['name'].' '.$p['academic_year']; break; } }
}

$selectedStudentName = '';
foreach ($studentsInfo as $st) { if ($st['id'] == $filterStudent) { $selectedStudentName = $st['full_name']; break; } }

// ── Export CSV des notes de l'élève ──
if (isset($_GET['export']) && $filterStudent && $filterPeriod && !empty($grades)) {
    verifyCsrf();
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=notes_'.str_replace(' ','_',$selectedStudentName).'_T'.$filterPeriod.'.csv');
    header('Content-Encoding: UTF-8');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Matière', 'Note', 'Note /20', 'Date', 'Commentaire'], ';');
    foreach ($grades as $g) {
        $sc20 = $g['score_max']>0 ? round($g['score']/$g['score_max']*20, 2) : 0;
        fputcsv($out, [$g['subject_name'], $g['score'].'/'.$g['score_max'], $sc20, $g['grade_date'], $g['comment'] ?? ''], ';');
    }
    fclose($out);
    exit;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mes notes - Nukunu Mofiala</title>
    <link rel="stylesheet" href="<?= BASE_URL ?>assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>@media print{.sidebar,.header-bar,.no-print{display:none!important;}.main-content{margin-left:0!important;}.card{box-shadow:none;border:1px solid #ddd;}}</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/portal_sidebar.php'; ?>
    <div class="main-content">
        <div class="header-bar">
            <h1><i class="fas fa-star-half-alt"></i> Mes notes</h1>
            <?php if ($filterStudent && $filterPeriod && !empty($bulletinData)): ?>
            <button onclick="window.print()" class="btn-action btn-view no-print"><i class="fas fa-print"></i> Imprimer bulletin</button>
            <?php endif; ?>
        </div>
        <?= showFlash() ?>

        <?php if (empty($studentIds)): ?>
        <div class="card" style="text-align:center;padding:3rem;color:#718096;">
            <i class="fas fa-user-slash" style="font-size:3rem;margin-bottom:1rem;display:block;"></i>
            <p>Aucun profil élève lié à votre compte. Contactez l'administration.</p>
        </div>
        <?php else: ?>

        <!-- Filtres -->
        <div class="card no-print" style="margin-bottom:1rem;">
            <form method="GET" style="display:flex;gap:1rem;flex-wrap:wrap;align-items:flex-end;">
                <?php if ($userRole === 'parent' && count($studentsInfo) > 1): ?>
                <div class="form-group" style="margin:0;min-width:200px;">
                    <label>Enfant</label>
                    <select name="student_id" onchange="this.form.submit()">
                        <?php foreach ($studentsInfo as $st): ?><option value="<?= $st['id'] ?>" <?= $filterStudent==$st['id'] ? 'selected' : '' ?>><?= e($st['full_name']) ?></option><?php endforeach; ?>
                    </select>
                </div>
                <?php else: ?><input type="hidden" name="student_id" value="<?= $filterStudent ?>"><?php endif; ?>
                <div class="form-group" style="margin:0;min-width:220px;">
                    <label>Période</label>
                    <select name="period_id" onchange="this.form.submit()">
                        <option value="">— Choisir —</option>
                        <?php foreach ($periods as $p): ?><option value="<?= $p['id'] ?>" <?= $filterPeriod==$p['id'] ? 'selected' : '' ?>><?= e($p['name'].' '.$p['academic_year']) ?></option><?php endforeach; ?>
                    </select>
                </div>
            </form>
        </div>

        <?php if ($filterStudent && $filterPeriod && !empty($bulletinData)): ?>
        <div style="background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:.75rem 1.25rem;margin-bottom:1.5rem;display:flex;gap:.75rem;flex-wrap:wrap;align-items:center;" class="no-print">
            <span style="font-weight:600;font-size:.85rem;color:var(--text-muted);margin-right:.5rem;">
                <i class="fas fa-download"></i> Export
            </span>
            <a href="grades.php?student_id=<?= $filterStudent ?>&period_id=<?= $filterPeriod ?>&export=1&csrf_token=<?= csrfToken() ?>"
               class="btn-action" style="padding:.5rem 1rem;background:#38a169;color:white;">
                <i class="fas fa-download"></i> Exporter mes notes
            </a>
        </div>
        <?php endif; ?>

        <?php if (!empty($bulletinData)): ?>
        <!-- Bulletin -->
        <div class="card" style="border-left:4px solid #667eea;margin-bottom:1.5rem;">
            <div class="card-header">
                <span class="card-title"><i class="fas fa-file-alt"></i> Bulletin — <?= e($selectedStudentName) ?> — <?= e($selectedPeriodName) ?></span>
                <?php if (!is_null($generalAvg)): ?>
                <span style="font-size:1.2rem;font-weight:700;color:<?= $generalAvg>=10?'#22543d':'#c53030' ?>">Moy. générale : <?= $generalAvg ?>/20</span>
                <?php endif; ?>
            </div>
            <div class="data-table-wrapper">
            <table class="data-table">
                <thead><tr><th>Matière</th><th>Coeff.</th><th>Moyenne /20</th><th>Appréciation</th></tr></thead>
                <tbody>
                <?php foreach ($bulletinData as $b):
                    $avg = round((float)$b['avg_score'], 2);
                    $col = $avg>=10 ? '#22543d' : '#c53030';
                    $mention = $avg>=16?'Très Bien':($avg>=14?'Bien':($avg>=12?'Assez Bien':($avg>=10?'Passable':'Insuffisant')));
                ?>
                <tr>
                    <td><strong><?= e($b['subject_name']) ?></strong></td>
                    <td><?= e($b['coefficient']) ?></td>
                    <td><strong style="font-size:1.05rem;color:<?= $col ?>"><?= $avg ?></strong></td>
                    <td style="color:<?= $col ?>;font-weight:500;"><?= $mention ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
                <?php if (!is_null($generalAvg)): ?>
                <tfoot>
                    <tr style="background:#f7fafc;font-weight:700;font-size:1rem;">
                        <td colspan="2">Moyenne générale</td>
                        <td style="color:<?= $generalAvg>=10?'#22543d':'#c53030' ?>;font-size:1.15rem;"><?= $generalAvg ?> / 20</td>
                        <td><?= $generalAvg>=16?'Très Bien':($generalAvg>=14?'Bien':($generalAvg>=12?'Assez Bien':($generalAvg>=10?'Passable':'Insuffisant'))) ?></td>
                    </tr>
                </tfoot>
                <?php endif; ?>
            </table>
                </div>
        </div>

        <!-- Détail des notes -->
        <?php if (!empty($grades)): ?>
        <div class="card">
                <div class="card-header"><span class="card-title"><i class="fas fa-list"></i> Détail des notes</span></div>
            <div class="data-table-wrapper">
            <table class="data-table">
                <thead><tr><th>Matière</th><th>Note</th><th>Date</th><th>Commentaire</th></tr></thead>
                <tbody>
                <?php foreach ($grades as $g):
                    $sc20 = $g['score_max']>0 ? round($g['score']/$g['score_max']*20, 2) : 0;
                    $col  = $sc20 >= 10 ? '#22543d' : '#c53030';
                ?>
                <tr>
                    <td><?= e($g['subject_name']) ?></td>
                    <td><strong style="color:<?= $col ?>"><?= e($g['score']) ?>/<?= e($g['score_max']) ?></strong>
                        <?php if ($g['score_max'] != 20): ?><small style="color:#999;"> (<?= $sc20 ?>/20)</small><?php endif; ?></td>
                    <td><?= formatDate($g['grade_date']) ?></td>
                    <td style="color:#718096;font-size:.9rem;"><?= e($g['comment'] ?? '-') ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
                </div>
        </div>
        <?php endif; ?>

        <?php elseif ($filterStudent && $filterPeriod): ?>
        <div class="card" style="text-align:center;padding:2rem;color:#718096;">
            <i class="fas fa-inbox" style="font-size:2.5rem;margin-bottom:.75rem;display:block;"></i>
            <p>Aucune note disponible pour cette période.</p>
        </div>
        <?php elseif ($filterStudent && empty($periods)): ?>
        <div class="card" style="text-align:center;padding:2rem;color:#718096;">
            <i class="fas fa-inbox" style="font-size:2.5rem;margin-bottom:.75rem;display:block;"></i>
            <p>Aucune note enregistrée pour le moment.</p>
        </div>
        <?php endif; ?>

        <?php endif; ?>
    </div>
</div>
</body>
</html>
