<?php
declare(strict_types=1);

// journal/student_journal.php — перегляд оцінок для ролі student

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

/* ===== Хелпер ===== */
if (!function_exists('h')) {
    function h(?string $s): string {
        return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

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

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

/* ===== Хелпер для посилань між уроками ===== */
if (!function_exists('build_lesson_url')) {
    function build_lesson_url(int $subject_id, int $lesson_idx): string {
        return "student_journal.php?subject_id={$subject_id}&lesson_idx={$lesson_idx}";
    }
}

/* ===== Список предметів, де є хоч одна оцінка (може бути порожнім) ===== */
$subjects = [];
$subjects_stmt = $conn->prepare("
    SELECT id, subject_name
    FROM subjects
    WHERE id IN (SELECT subject_id FROM grades WHERE student_id = ?)
    ORDER BY subject_name ASC
");
if ($subjects_stmt) {
    $subjects_stmt->bind_param("i", $student_id);
    $subjects_stmt->execute();
    $subjects_res = $subjects_stmt->get_result();
    if ($subjects_res) {
        while ($row = $subjects_res->fetch_assoc()) {
            $subjects[] = $row;
        }
    }
    $subjects_stmt->close();
}

/* ===== Обраний предмет ===== */
$subject_id = isset($_GET['subject_id']) ? (int)$_GET['subject_id'] : 0;
$selected_subject = null;

if ($subject_id > 0) {
    $subject_stmt = $conn->prepare("SELECT subject_name FROM subjects WHERE id = ?");
    if ($subject_stmt) {
        $subject_stmt->bind_param("i", $subject_id);
        $subject_stmt->execute();
        $sr = $subject_stmt->get_result();
        if ($sr && $sr->num_rows > 0) {
            $selected_subject = $sr->fetch_assoc();
        } else {
            $subject_id = 0;
        }
        $subject_stmt->close();
    } else {
        $subject_id = 0;
    }
}

/* ===== Якщо предмет вибраний — готуємо дані уроків та поточний індекс ===== */
$lessons = [];
$total_lessons = 0;
$lesson_idx = -1;
$current_lesson = null;
$current_lesson_id = 0;
$current_topic = '';
$current_date_human = '';

if ($subject_id > 0 && $selected_subject) {
    $less_stmt = $conn->prepare("
        SELECT id, lesson_date, topic
        FROM lessons
        WHERE subject_id = ?
        ORDER BY lesson_date ASC, id ASC
    ");
    if ($less_stmt) {
        $less_stmt->bind_param("i", $subject_id);
        $less_stmt->execute();
        $less_res = $less_stmt->get_result();
        if ($less_res) {
            while ($row = $less_res->fetch_assoc()) {
                $lessons[] = $row;
            }
        }
        $less_stmt->close();
    }

    $total_lessons = count($lessons);

    if ($total_lessons > 0) {
        $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'] ?? 0);
        $current_topic = (string)($current_lesson['topic'] ?? '');
        $current_date_human = date('d.m.Y', strtotime((string)($current_lesson['lesson_date'] ?? 'now')));
    }
}

/*
  ===== Оцінка студента за поточний урок (якщо є)
  - якщо рядок у grades Є, але grade=NULL -> "Не здав"
  - якщо рядка НЕМАЄ -> "—"
*/
$grade = null;
$grade_row_exists = false;

if ($current_lesson_id > 0) {
    $g_stmt = $conn->prepare("
        SELECT grade FROM grades
        WHERE subject_id = ? AND lesson_id = ? AND student_id = ?
        LIMIT 1
    ");
    if ($g_stmt) {
        $g_stmt->bind_param("iii", $subject_id, $current_lesson_id, $student_id);
        $g_stmt->execute();
        $g_res = $g_stmt->get_result();
        if ($g_res && ($g = $g_res->fetch_assoc())) {
            $grade_row_exists = true;
            $grade = is_null($g['grade']) ? null : (int)$g['grade'];
        }
        $g_stmt->close();
    }
}

/* ===== Лог: перегляд оцінок (grades_view) ===== */
if ($subject_id > 0 && $selected_subject && $current_lesson_id > 0) {
    $key  = 'grades_view_' . $student_id . '_' . $subject_id . '_' . $current_lesson_id;
    $now  = time();
    $last = (int)($_SESSION[$key] ?? 0);

    if ($now - $last >= 30) {
        $_SESSION[$key] = $now;

        $subjName = (string)($selected_subject['subject_name'] ?? '');
        $topicShort = $current_topic !== '' ? mb_substr($current_topic, 0, 140) : 'без теми';

        $grade_text = '—';
        if ($grade_row_exists) {
            $grade_text = is_null($grade) ? 'Не здав' : (string)$grade;
        }

        $msg = "Переглянув оцінки: {$subjName} — урок: {$topicShort} ({$current_date_human}) — оцінка: {$grade_text}";
        ej_log_action($conn, $student_id, 'student', 'grades_view', $msg);
    }
}
?>
<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="UTF-8">
    <title>Мій журнал</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-br: rgba(255,255,255,.22);
        }

        *{box-sizing:border-box}

        body{
            margin:0;
            background:var(--bg);
            color:var(--ink);
            font-family:system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,"Helvetica Neue",Arial,sans-serif;
        }

        .wrap{
            max-width:900px;
            margin:16px auto;
            padding:16px;
        }

        .card{
            background:var(--card);
            border:1px solid var(--border);
            border-radius:16px;
            box-shadow:var(--shadow);
            padding:18px;
        }

        h1{
            margin:0 0 8px;
            color:var(--brand-purple);
            font-size:22px;
            font-weight:1000;
            letter-spacing:.2px;
        }

        h2{
            margin:14px 0 10px;
            color:var(--brand-purple);
            font-size:16px;
            font-weight:1000;
        }

        .subline{
            margin:0 0 12px;
            color:var(--muted);
            font-size:13px;
            font-weight:700;
        }

        .info{
            background: rgba(163,232,211,.22);
            border: 1px solid rgba(67,39,85,.14);
            color: var(--brand-purple);
            padding: 12px;
            border-radius: 14px;
            margin-top: 12px;
            font-size: 14px;
            font-weight: 800;
            line-height: 1.5;
            text-align:left;
        }

        /* Предмети: читабельний білий текст на фіолетовому */
        .subjects{
            display:flex;
            flex-wrap:wrap;
            gap:10px;
            margin:0;
            padding:0;
            list-style:none;
        }

        .subj a{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            padding:10px 12px;
            border-radius:999px;
            text-decoration:none !important;

            font-weight:900;
            font-size:13px;

            background: linear-gradient(180deg, var(--brand-purple) 0%, var(--brand-purple-2) 100%) !important;
            color:#ffffff !important;

            border:1px solid var(--chip-br) !important;
            transition:transform .12s ease, filter .12s ease;
        }

        .subj a:hover{
            transform:translateY(-1px);
            filter:brightness(1.07);
        }

        .subj a:focus{
            outline:none;
            box-shadow:0 0 0 3px var(--focus);
        }

        .subj a.active{
            background: linear-gradient(180deg, var(--brand-mint) 0%, var(--brand-mint-2) 100%) !important;
            color: var(--brand-purple) !important;
            border-color: rgba(67,39,85,.22) !important;
            filter:none;
        }

        .top-row{
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:10px;
            flex-wrap:wrap;
            margin:10px 0 8px;
        }

        .badges{
            display:flex;
            gap:8px;
            flex-wrap:wrap;
        }

        .badge{
            background: rgba(163,232,211,.22);
            border:1px solid rgba(67,39,85,.14);
            color: var(--brand-purple);
            padding:6px 10px;
            border-radius:999px;
            font-size:12px;
            font-weight:900;
        }

        .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:8px 10px;
            border:1px solid rgba(0,0,0,.10);
            border-radius:12px;
            text-decoration:none;
            color:var(--brand-purple);
            background:#fff;
            font-size:13px;
            font-weight:900;
        }
        .nav-lessons a:hover{ background:#f3f4f6; }
        .nav-lessons .disabled{ opacity:.5; pointer-events:none; }

        table{
            width:100%;
            border-collapse:separate;
            border-spacing:0;
            table-layout:fixed;
            margin-top:10px;
            overflow:hidden;
            border-radius:14px;
            border:1px solid rgba(0,0,0,.10);
        }

        th,td{
            padding:12px 10px;
            text-align:center;
            background:#fff;
            border-bottom:1px solid rgba(0,0,0,.08);
        }

        thead th{
            background: linear-gradient(180deg, var(--brand-purple) 0%, var(--brand-purple-2) 100%);
            color:#fff;
            border-bottom:1px solid rgba(255,255,255,.18);
        }

        tbody tr:last-child td{ border-bottom:none; }

        .col-name{ width:55%; text-align:left; }
        .col-grade{ width:45%; }

        .topic{
            font-weight:1000;
            font-size:14px;
            line-height:1.25;
            display:block;
        }

        .date{
            font-size:12px;
            opacity:.9;
            margin-top:3px;
            display:block;
        }

        .grade-pill{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            min-width:44px;
            padding:8px 12px;
            border-radius:999px;
            font-weight:1000;
            border:1px solid rgba(0,0,0,.10);
            background: rgba(163,232,211,.18);
            color: var(--brand-purple);
        }
        .grade-pill.na{
            background:#f3f4f6;
            color:#6b7280;
        }
        .grade-pill.fail{
            background: rgba(239,68,68,.12);
            border-color: rgba(239,68,68,.22);
            color:#991b1b;
        }

        @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%}
        }
    </style>
</head>
<body>

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

<main class="wrap">
    <section class="card">
        <h1>Вітаємо, <?= h($full_name); ?>!</h1>
        <p class="subline">Тут відображаються предмети, де у вас уже є хоча б одна оцінка.</p>

        <h2>Ваші предмети</h2>

        <?php if (count($subjects) > 0): ?>
            <ul class="subjects">
                <?php foreach ($subjects as $row): ?>
                    <?php
                        $sid = (int)($row['id'] ?? 0);
                        $active = ($subject_id > 0 && $sid === $subject_id) ? 'active' : '';
                    ?>
                    <li class="subj">
                        <a class="<?= $active ?>" href="student_journal.php?subject_id=<?= $sid ?>">
                            <?= h((string)($row['subject_name'] ?? '')) ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php else: ?>
            <div class="info">
                Поки що у вас немає жодної оцінки. Коли з’явиться перша — відповідні предмети автоматично відобразяться тут.
            </div>
        <?php endif; ?>

        <?php if ($subject_id > 0 && $selected_subject): ?>
            <h2 style="margin-top:16px">
                Оцінки з предмету: <?= h((string)($selected_subject['subject_name'] ?? '')); ?>
            </h2>

            <?php if ($total_lessons > 0): ?>
                <div class="top-row">
                    <div class="badges">
                        <span class="badge">Уроків: <?= (int)$total_lessons; ?></span>
                        <span class="badge">Урок: <?= (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="<?= h(build_lesson_url($subject_id, $prev_idx)); ?>">← Попередній урок</a>

                        <a class="<?= ($lesson_idx >= $total_lessons - 1) ? 'disabled' : ''; ?>"
                           href="<?= h(build_lesson_url($subject_id, $next_idx)); ?>">Наступний урок →</a>
                    </div>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th class="col-name">ПІБ</th>
                            <th class="col-grade">
                                <span class="topic" title="<?= h($current_topic); ?>">
                                    <?= h($current_topic); ?>
                                </span>
                                <span class="date"><?= h($current_date_human); ?></span>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td class="col-name"><?= h($full_name); ?></td>
                            <td class="col-grade">
                                <?php
                                    if (!$grade_row_exists) {
                                        echo '<span class="grade-pill na">—</span>';
                                    } else {
                                        if (is_null($grade)) {
                                            echo '<span class="grade-pill fail">Не здав</span>';
                                        } else {
                                            echo '<span class="grade-pill">' . h((string)$grade) . '</span>';
                                        }
                                    }
                                ?>
                            </td>
                        </tr>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="info">Для цього предмету ще немає уроків.</div>
            <?php endif; ?>
        <?php endif; ?>
    </section>
</main>

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

</body>
</html>
