<?php
session_start();
require_once __DIR__ . '/../includes/db_connect.php';

/* ===== Доступ лише для студента ===== */
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'student') {
    header("Location: ../index.php");
    exit();
}

$user_id   = (int)$_SESSION['user_id'];
$full_name = $_SESSION['full_name'] ?? 'Студент';

/* ===== Вхідні ===== */
$subject_id = isset($_GET['subject_id']) ? (int)$_GET['subject_id'] : 0;
if ($subject_id <= 0) {
    http_response_code(400);
    die("Предмет не обрано! Поверніться до списку предметів.");
}

/* ===== Перевіряємо, що в цього студента є оцінки по предмету ===== */
$subject_stmt = $conn->prepare("
    SELECT s.subject_name
    FROM subjects s
    WHERE s.id = ?
      AND EXISTS (
          SELECT 1 FROM grades g
          WHERE g.subject_id = s.id AND g.student_id = ?
      )
");
$subject_stmt->bind_param("ii", $subject_id, $user_id);
$subject_stmt->execute();
$subject_res = $subject_stmt->get_result();
if ($subject_res->num_rows === 0) {
    die("Жодних оцінок для цього предмету не знайдено!");
}
$subject = $subject_res->fetch_assoc();
$subject_stmt->close();

/* ===== Усі уроки предмету (відсортовані за датою) ===== */
$lessons = [];
$less_stmt = $conn->prepare("
    SELECT id, lesson_date, topic
    FROM lessons
    WHERE subject_id = ?
    ORDER BY lesson_date ASC, id ASC
");
$less_stmt->bind_param("i", $subject_id);
$less_stmt->execute();
$less_res = $less_stmt->get_result();
while ($row = $less_res->fetch_assoc()) {
    $lessons[] = $row;
}
$less_stmt->close();

$total_lessons = count($lessons);
if ($total_lessons === 0) {
    die("Для цього предмету ще немає уроків.");
}

/* Поточний індекс уроку: якщо не передано — показуємо останній (найсвіжіший) */
$default_idx = $total_lessons - 1;
$lesson_idx  = isset($_GET['lesson_idx']) ? (int)$_GET['lesson_idx'] : $default_idx;
if ($lesson_idx < 0) $lesson_idx = 0;
if ($lesson_idx > $total_lessons - 1) $lesson_idx = $total_lessons - 1;

$current_lesson     = $lessons[$lesson_idx];
$current_lesson_id  = (int)$current_lesson['id'];
$current_topic      = (string)$current_lesson['topic'];
$current_date_iso   = date('Y-m-d', strtotime($current_lesson['lesson_date']));
$current_date_human = date('d.m.Y', strtotime($current_lesson['lesson_date']));

/* ===== Оцінка студента за поточний урок ===== */
$grade = null;
$g_stmt = $conn->prepare("
    SELECT grade
    FROM grades
    WHERE subject_id = ? AND lesson_id = ? AND student_id = ?
");
$g_stmt->bind_param("iii", $subject_id, $current_lesson_id, $user_id);
$g_stmt->execute();
$g_res = $g_stmt->get_result();
if ($row = $g_res->fetch_assoc()) {
    $grade = is_null($row['grade']) ? null : (int)$row['grade'];
}
$g_stmt->close();

/* Хелпер для навігації між уроками */
function build_lesson_url(int $subject_id, int $lesson_idx): string {
    return "student_grades.php?subject_id={$subject_id}&lesson_idx={$lesson_idx}";
}

/* Поточна сторінка (на майбутнє) */
$current_file = basename($_SERVER['SCRIPT_NAME']); // student_grades.php
?>
<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="UTF-8">
    <title>Мої оцінки — <?= htmlspecialchars($subject['subject_name'], ENT_QUOTES, 'UTF-8'); ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        :root{
            --brand-mint:#a3e8d3;
            --brand-mint-2:#92dec7;
            --brand-purple:#432755;
            --brand-purple-2:#3a244d;

            --ink:#1f2937;
            --muted:#4b5563;
            --bg:#f6f7fb;
            --card:#ffffff;
            --shadow: 0 10px 24px rgba(0,0,0,.08);
            --border: rgba(0,0,0,.10);
            --focus: rgba(67,39,85,.25);

            --chip-bg: rgba(163,232,211,.22);
            --chip-br: rgba(67,39,85,.14);
        }

        *{box-sizing:border-box}
        body{
            font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,"Noto Sans","Helvetica Neue",Arial;
            margin:0;
            background:var(--bg);
            color:var(--ink);
        }

        /* локальний контейнер */
        .wrap{
            max-width:1100px;
            margin:16px auto;
            padding:16px;
        }
        .card{
            background:var(--card);
            border:1px solid var(--border);
            border-radius:16px;
            box-shadow:var(--shadow);
            padding:18px;
        }

        /* прибираємо underline з глобального a:hover, але тільки на цій сторінці */
        .card a,
        .card a:hover{ text-decoration:none !important; }

        .page-head{
            display:flex;
            align-items:flex-start;
            justify-content:space-between;
            gap:12px;
            flex-wrap:wrap;
            margin-bottom:12px;
        }
        .title{
            margin:0;
            font-size:22px;
            color:var(--brand-purple);
            font-weight:900;
            letter-spacing:.2px;
        }
        .subtitle{
            margin:6px 0 0 0;
            color:var(--muted);
            font-weight:700;
            font-size:13px;
            line-height:1.45;
        }

        .section-title{
            margin:12px 0 10px;
            font-size:16px;
            font-weight:900;
            color:var(--brand-purple);
        }

        .lesson-head{
            margin-top:10px;
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:10px;
            flex-wrap:wrap;
        }
        .chips{
            display:flex;
            gap:8px;
            flex-wrap:wrap;
            align-items:center;
        }
        .chip{
            background: var(--chip-bg);
            border:1px solid var(--chip-br);
            color: var(--brand-purple);
            padding:6px 10px;
            border-radius:999px;
            font-size:12px;
            font-weight:900;
        }

        /* навігація уроків (як у parent) */
        .nav-lessons{
            display:flex;
            gap:8px;
            align-items:center;
            flex-wrap:wrap;
        }
        .nav-lessons a{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            padding:10px 12px;
            border-radius:999px;
            font-weight:900;
            font-size:13px;
            user-select:none;

            color:#fff !important;
            -webkit-text-fill-color:#fff !important;

            background: linear-gradient(180deg, var(--brand-purple), var(--brand-purple-2)) !important;
            border: 1px solid rgba(255,255,255,.18) !important;
            box-shadow: 0 10px 18px rgba(67,39,85,.16) !important;

            transition: transform .12s ease, box-shadow .12s ease, filter .12s ease;
        }
        .nav-lessons a:hover{
            transform: translateY(-1px);
            box-shadow: 0 14px 24px rgba(67,39,85,.22) !important;
            filter: saturate(1.05);
        }
        .nav-lessons a:active{ transform: translateY(0); }
        .nav-lessons a.disabled{
            opacity:.45;
            pointer-events:none;
            transform:none;
            filter:none;
            box-shadow:none !important;
        }

        /* таблиця */
        .table-wrap{
            margin-top:12px;
            border-radius:16px;
            overflow:hidden;
            border:1px solid rgba(0,0,0,.10);
            box-shadow: 0 10px 22px rgba(0,0,0,.06);
        }
        table{
            width:100%;
            border-collapse:collapse;
            table-layout:fixed;
            background:#fff;
        }
        th,td{
            padding:12px 10px;
            text-align:center;
            border-bottom:1px solid rgba(0,0,0,.08);
        }
        thead th{
            background: linear-gradient(135deg, rgba(67,39,85,.96) 0%, rgba(67,39,85,.86) 100%);
            color:#fff;
            border-bottom: 1px solid rgba(255,255,255,.18);
        }
        .col-name{width:55%;text-align:left;font-weight:900;}
        .col-grade{width:45%;}
        .topic{
            font-weight:900;
            line-height:1.25;
            margin-bottom:2px;
            word-wrap:break-word;
            display:-webkit-box;
            -webkit-box-orient:vertical;
            -webkit-line-clamp:3;
            overflow:hidden;
        }
        .date{
            font-size:12px;
            opacity:.9;
            font-weight:700;
        }

        .student-name{
            font-weight:900;
            line-height:1.25;
            display:-webkit-box;
            -webkit-box-orient:vertical;
            -webkit-line-clamp:2;
            overflow:hidden;
        }

        .back-row{
            margin-top:12px;
            display:flex;
            justify-content:flex-start;
        }
        .back-link{
            display:inline-flex;
            align-items:center;
            gap:10px;
            padding:10px 14px;
            border-radius:999px;
            font-weight:900;
            color: var(--brand-purple) !important;
            -webkit-text-fill-color: var(--brand-purple) !important;
            background: rgba(163,232,211,.22);
            border: 1px solid rgba(67,39,85,.14);
            box-shadow: 0 8px 16px rgba(0,0,0,.08), inset 0 1px 0 rgba(255,255,255,.65);
            transition: transform .12s ease, box-shadow .12s ease, filter .12s ease;
        }
        .back-link:hover{
            transform: translateY(-1px);
            box-shadow: 0 12px 22px rgba(0,0,0,.12), inset 0 1px 0 rgba(255,255,255,.7);
            filter: saturate(1.05);
        }
        .back-link:active{
            transform: translateY(0);
            box-shadow: 0 8px 16px rgba(0,0,0,.08);
        }

        @media (max-width:600px){
            .wrap{padding:12px}
            .card{padding:16px;border-radius:14px}
            th,td{padding:10px 8px}
            .col-name{width:58%}
            .col-grade{width:42%}
            .nav-lessons a{ width:100%; }
        }
    </style>
</head>
<body>

<?php require __DIR__ . '/../includes/header.php'; ?>

<main class="wrap">
    <section class="card">
        <div class="page-head">
            <div>
                <h1 class="title">Вітаємо, <?= htmlspecialchars($full_name, ENT_QUOTES, 'UTF-8'); ?>!</h1>
                <div class="subtitle">
                    Переглядаєш оцінку за один обраний урок. Перемикай уроки кнопками — без горизонтальної прокрутки.
                </div>
            </div>
        </div>

        <div class="section-title"><?= htmlspecialchars($subject['subject_name'], ENT_QUOTES, 'UTF-8'); ?></div>

        <div class="lesson-head">
            <div class="chips">
                <span class="chip">Уроків: <?= (int)$total_lessons; ?></span>
                <span class="chip">Урок: <?= (int)($lesson_idx + 1); ?> / <?= (int)$total_lessons; ?></span>
            </div>

            <div class="nav-lessons">
                <?php
                    $prev_idx = max(0, $lesson_idx - 1);
                    $next_idx = min($total_lessons - 1, $lesson_idx + 1);
                ?>
                <a class="<?= $lesson_idx<=0 ? 'disabled' : ''; ?>"
                   href="<?= htmlspecialchars(build_lesson_url($subject_id, $prev_idx), ENT_QUOTES, 'UTF-8'); ?>">
                    ← Попередній урок
                </a>
                <a class="<?= $lesson_idx>=$total_lessons-1 ? 'disabled' : ''; ?>"
                   href="<?= htmlspecialchars(build_lesson_url($subject_id, $next_idx), ENT_QUOTES, 'UTF-8'); ?>">
                    Наступний урок →
                </a>
            </div>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th class="col-name">ПІБ</th>
                        <th class="col-grade">

                            <div class="topic" title="<?= htmlspecialchars($current_topic, ENT_QUOTES, 'UTF-8'); ?>">
                                <?= htmlspecialchars($current_topic, ENT_QUOTES, 'UTF-8'); ?>
                            </div>
                            <div class="date"><?= htmlspecialchars($current_date_human, ENT_QUOTES, 'UTF-8'); ?></div>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td class="col-name">
                            <span class="student-name"><?= htmlspecialchars($full_name, ENT_QUOTES, 'UTF-8'); ?></span>
                        </td>
                        <td class="col-grade">
                            <?= is_null($grade) ? '—' : htmlspecialchars((string)$grade, ENT_QUOTES, 'UTF-8'); ?>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="back-row">
            <a href="student_subjects.php" class="back-link">← Повернутися до списку предметів</a>
        </div>
    </section>
</main>

<?php require __DIR__ . '/../includes/footer.php'; ?>

</body>
</html>
