<?php
session_start();
ob_start();

require_once __DIR__ . '/../includes/db_connect.php';

/* ===== Екранування ===== */
function h(?string $s): string
{
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

/* ===== Авторизація ===== */
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', ['admin', 'teacher'], true)) {
    header("Location: ../index.php");
    exit();
}
$auth_role = $_SESSION['role'] ?? '';
$my_id     = (int)($_SESSION['user_id'] ?? 0);

/* ===== Вхідні ===== */
$teacher_id = isset($_GET['teacher_id']) ? (int)$_GET['teacher_id'] : 0;
if ($auth_role === 'teacher' && $teacher_id === 0) {
    $teacher_id = $my_id;
}
if ($teacher_id <= 0) {
    http_response_code(400);
    die("Невірний ідентифікатор викладача.");
}
/* Вчитель не може дивитися чужий профіль/експорти */
if ($auth_role === 'teacher' && $teacher_id !== $my_id) {
    http_response_code(403);
    die('Недостатньо прав.');
}

/* ===== Дані викладача ===== */
$tq = $conn->prepare("SELECT id, full_name, email, role FROM users WHERE id = ? AND role IN ('admin','teacher')");
$tq->bind_param("i", $teacher_id);
$tq->execute();
$tr = $tq->get_result();
if ($tr->num_rows === 0) {
    http_response_code(404);
    die("Викладача не знайдено.");
}
$teacher = $tr->fetch_assoc();
$tq->close();

/* ===== Предмети викладача з групами ===== */
$subjects = [];
$sq = $conn->prepare("
    SELECT s.id AS subject_id, s.subject_name, g.id AS group_id, g.group_name
    FROM subjects s
    JOIN `groups` g ON g.id = s.group_id
    WHERE s.teacher_id = ?
    ORDER BY g.group_name ASC, s.subject_name ASC
");
$sq->bind_param("i", $teacher_id);
$sq->execute();
$sr = $sq->get_result();
while ($row = $sr->fetch_assoc()) {
    $subjects[] = $row;
}
$sq->close();

$subject_id = isset($_GET['subject_id']) ? (int)$_GET['subject_id'] : 0;
$action     = $_GET['action'] ?? '';

$selected = null;
if ($subject_id > 0) {
    foreach ($subjects as $s) {
        if ((int)$s['subject_id'] === $subject_id) {
            $selected = $s;
            break;
        }
    }
}

/* ===== Утиліти ===== */
function fsafe(string $name): string
{
    $name = preg_replace('~[\/\\\\:\*\?"<>\|]+~u', ' ', $name);
    $name = preg_replace('~\s+~u', ' ', $name);
    return trim($name);
}

function ascii_safe(string $name): string
{
    $conv = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $name);
    if ($conv === false) {
        $conv = $name;
    }
    $conv = preg_replace('~[^A-Za-z0-9_\-\.]+~', '_', $conv);
    $conv = preg_replace('~_+~', '_', $conv);
    return trim($conv, '_');
}

function get_students_for_group(mysqli $conn, int $group_id): array
{
    $out = [];
    $st = $conn->prepare("SELECT u.id, u.full_name FROM users u WHERE u.role='student' AND u.group_id=? ORDER BY u.full_name ASC");
    $st->bind_param("i", $group_id);
    $st->execute();
    $res = $st->get_result();
    while ($r = $res->fetch_assoc()) {
        $out[] = $r;
    }
    $st->close();
    return $out;
}

function get_lessons_for_subject(mysqli $conn, int $subject_id): array
{
    $out = [];
    $lt = $conn->prepare("SELECT l.id, l.lesson_date, l.topic FROM lessons l WHERE l.subject_id=? ORDER BY l.lesson_date ASC, l.id ASC");
    $lt->bind_param("i", $subject_id);
    $lt->execute();
    $res = $lt->get_result();
    while ($r = $res->fetch_assoc()) {
        $out[] = $r;
    }
    $lt->close();
    return $out;
}

function get_grades_map(mysqli $conn, array $students, array $lessons): array
{
    $map = [];
    if (empty($students) || empty($lessons)) {
        return $map;
    }

    $student_ids = implode(',', array_map('intval', array_column($students, 'id')));
    $lesson_ids  = implode(',', array_map('intval', array_column($lessons, 'id')));

    $sql = "SELECT g.student_id, g.lesson_id, g.grade FROM grades g WHERE g.student_id IN ($student_ids) AND g.lesson_id IN ($lesson_ids)";
    if ($gr = $conn->query($sql)) {
        while ($r = $gr->fetch_assoc()) {

            $map[$r['student_id'] . ':' . $r['lesson_id']] = $r['grade'];
        }
        $gr->free();
    }

    return $map;
}

/* ===== Обгортання теми у 2 рядки ===== */
function wrap_topic_2lines(string $text, int $line1 = 55, int $line2 = 55): array
{
    $text = trim(preg_replace('~\s+~u', ' ', $text));
    if ($text === '') {
        return ['—', ''];
    }

    $a    = mb_substr($text, 0, $line1, 'UTF-8');
    $rest = mb_substr($text, $line1, 9999, 'UTF-8');
    $b    = mb_substr(trim($rest), 0, $line2, 'UTF-8');
    $tail = mb_substr(trim($rest), $line2, 1, 'UTF-8');

    if ($tail !== '') {
        $b = rtrim($b) . '…';
    }

    return [$a, $b];
}

/* ===== SVG з поворотом -90°, повертаємо як data:image/svg+xml;base64 ===== */
function svg_to_data_uri(string $svg): string
{
    return 'data:image/svg+xml;base64,' . base64_encode($svg);
}

/* ===== Вертикальна тема у вигляді IMG ===== */
function make_vertical_topic_img_src(string $topic, int $cellW = 16, int $cellH = 190): string
{
    [$l1, $l2] = wrap_topic_2lines((string)$topic, 58, 58);

    $fontSize = 9;
    $lineStep = 9;
    $w = $cellW;
    $h = $cellH;

    $l1e = htmlspecialchars($l1, ENT_QUOTES, 'UTF-8');
    $l2e = htmlspecialchars($l2, ENT_QUOTES, 'UTF-8');

    $textBlock =
        '<text x="2" y="12" font-family="DejaVu Sans" font-size="' . $fontSize . '" fill="#111">' .
            '<tspan x="2" y="12">' . $l1e . '</tspan>';

    if (trim($l2) !== '') {
        $textBlock .= '<tspan x="2" dy="' . $lineStep . '">' . $l2e . '</tspan>';
    }

    $textBlock .= '</text>';

    $svg =
        '<svg xmlns="http://www.w3.org/2000/svg" width="' . $w . '" height="' . $h . '" viewBox="0 0 ' . $w . ' ' . $h . '" preserveAspectRatio="none">' .
            '<rect x="0" y="0" width="' . $w . '" height="' . $h . '" fill="none"/>' .
            '<g transform="translate(0 ' . $h . ') rotate(-90)">' .
                $textBlock .
            '</g>' .
        '</svg>';

    return svg_to_data_uri($svg);
}

/* ===== Захист експорту від warning/deprecated Dompdf на PHP 8.4 ===== */
function pdf_export_guard_begin(): array
{
    $state = [
        'display_errors'         => ini_get('display_errors'),
        'display_startup_errors' => ini_get('display_startup_errors'),
        'html_errors'            => ini_get('html_errors'),
        'log_errors'             => ini_get('log_errors'),
        'error_reporting'        => error_reporting(),
        'ob_level'               => ob_get_level(),
    ];

    @ini_set('display_errors', '0');
    @ini_set('display_startup_errors', '0');
    @ini_set('html_errors', '0');
    @ini_set('zlib.output_compression', '0');

    if (function_exists('apache_setenv')) {
        @apache_setenv('no-gzip', '1');
    }

    error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED & ~E_WARNING & ~E_USER_WARNING & ~E_NOTICE & ~E_USER_NOTICE & ~E_STRICT);

    set_error_handler(
        static function (int $severity, string $message, string $file = '', int $line = 0): bool {
            $ignored = [
                E_DEPRECATED,
                E_USER_DEPRECATED,
                E_WARNING,
                E_USER_WARNING,
                E_NOTICE,
                E_USER_NOTICE,
                E_STRICT,
            ];

            if (in_array($severity, $ignored, true)) {
                error_log('[teacher_profile.php PDF export suppressed] ' . $message . ' in ' . $file . ':' . $line);
                return true;
            }

            return false;
        }
    );

    return $state;
}

function pdf_export_guard_end(array $state): void
{
    restore_error_handler();

    error_reporting((int)($state['error_reporting'] ?? E_ALL));

    if (array_key_exists('display_errors', $state) && $state['display_errors'] !== false) {
        @ini_set('display_errors', (string)$state['display_errors']);
    }
    if (array_key_exists('display_startup_errors', $state) && $state['display_startup_errors'] !== false) {
        @ini_set('display_startup_errors', (string)$state['display_startup_errors']);
    }
    if (array_key_exists('html_errors', $state) && $state['html_errors'] !== false) {
        @ini_set('html_errors', (string)$state['html_errors']);
    }
}

function clear_all_output_buffers(): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
}

function stream_download_and_exit(string $path, string $contentType, string $downloadName): void
{
    clear_all_output_buffers();

    header('X-Content-Type-Options: nosniff');
    header('Content-Type: ' . $contentType);
    header('Content-Disposition: attachment; filename="' . basename($downloadName) . '"');
    header('Content-Length: ' . (string)filesize($path));
    header('Cache-Control: private, must-revalidate');
    header('Pragma: public');
    header('Expires: 0');
    header('Accept-Ranges: bytes');

    readfile($path);
    exit();
}

/* ===== HTML журналу (для PDF/екрану) ===== */
function build_journal_html(array $teacher, array $selected, array $students, array $lessons, array $grades_map): string
{
    $title = h($selected['subject_name'] . ' — ' . $selected['group_name']);
    $tname = h($teacher['full_name']);
    $today = date('Y-m-d H:i');

    $CELL_W = 16;
    $HEAD_H = 190;

    ob_start();
    ?>
    <style>
        @page { margin: 10px 8px; size: A4 landscape; }

        body{
            font-family: DejaVu Sans, Arial, sans-serif;
            color:#111;
            font-size:10px;
        }
        h1{
            font-size:16px;
            margin:0 0 6px;
            text-align:center;
        }
        .meta{
            font-size:11px;
            text-align:center;
            margin-bottom:8px;
            color:#333;
        }

        table{
            width:100%;
            border-collapse:collapse;
            table-layout:fixed;
        }
        th, td{
            border:1px solid #888;
            padding:3px 4px;
            font-size:10px;
            vertical-align:middle;
        }
        th{ background:#f3f4f6; }

        .left{ text-align:left; }
        .center{ text-align:center; }

        .w-num{ width:22px; }
        .w-name{ width:320px; }
        .w-lesson{ width:<?php echo (int)$CELL_W; ?>px; padding:0; }
        .w-avg{ width:44px; }

        td.w-name, th.w-name{
            white-space:normal !important;
            overflow:visible !important;
            text-overflow:clip !important;
            word-break:break-word;
            overflow-wrap:anywhere;
            line-height:1.15;
        }

        th.w-lesson{
            height:<?php echo (int)$HEAD_H; ?>px;
            vertical-align:bottom;
            padding:0;
        }
        .vimg{
            display:block;
            width:<?php echo (int)$CELL_W; ?>px;
            height:<?php echo (int)$HEAD_H; ?>px;
        }

        td.w-lesson{
            text-align:center;
            font-size:10px;
            padding:2px 0;
        }
    </style>

    <h1><?php echo $title; ?></h1>
    <div class="meta">
        Викладач: <?php echo $tname; ?> • Згенеровано: <?php echo h($today); ?>
    </div>

    <table>
        <thead>
            <tr>
                <th class="center w-num">№</th>
                <th class="left w-name">ПІБ учня</th>

                <?php if (!empty($lessons)): ?>
                    <?php foreach ($lessons as $l): ?>
                        <?php
                        $topic = (string)($l['topic'] ?? '—');
                        $src   = make_vertical_topic_img_src($topic, (int)$CELL_W, (int)$HEAD_H);
                        ?>
                        <th class="center w-lesson">
                            <img class="vimg" src="<?php echo h($src); ?>" alt="<?php echo h($topic); ?>">
                        </th>
                    <?php endforeach; ?>
                <?php else: ?>
                    <th class="center">Уроків ще немає</th>
                <?php endif; ?>

                <th class="center w-avg">Сер.</th>
            </tr>
        </thead>

        <tbody>
            <?php if (empty($students)): ?>
                <tr>
                    <td class="center" colspan="<?php echo (!empty($lessons) ? (3 + count($lessons)) : 3); ?>">
                        Немає учнів у цій групі.
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($students as $i => $st): ?>
                    <tr>
                        <td class="center w-num"><?php echo $i + 1; ?></td>
                        <td class="left w-name"><?php echo h($st['full_name']); ?></td>

                        <?php
                        $sum = 0;
                        $cnt = 0;

                        if (!empty($lessons)):
                            foreach ($lessons as $l):
                                $key = $st['id'] . ':' . $l['id'];
                                $g   = $grades_map[$key] ?? '';
                                if ($g !== '' && is_numeric($g)) {
                                    $sum += (float)$g;
                                    $cnt++;
                                }
                                echo '<td class="center w-lesson">' . h((string)$g) . '</td>';
                            endforeach;
                        else:
                            echo '<td class="center">—</td>';
                        endif;

                        $avg = ($cnt > 0) ? round($sum / $cnt, 2) : '—';
                        ?>
                        <td class="center w-avg"><?php echo h((string)$avg); ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
    <?php
    return ob_get_clean();
}

/* ===== Експорт (PDF одного предмета або ZIP усіх) ===== */
$autoload = __DIR__ . '/../includes/dompdf/autoload.inc.php';
if (($action === 'pdf' || $action === 'zip_all') && !file_exists($autoload)) {
    http_response_code(500);
    die("Не знайдено Dompdf. Очікується: includes/dompdf/autoload.inc.php");
}
if ($action !== '' && !in_array($action, ['pdf', 'zip_all'], true)) {
    http_response_code(400);
    die('Невірний параметр дії.');
}

if ($action === 'pdf' && $selected) {
    $guard = pdf_export_guard_begin();

    try {
        require_once $autoload;

        $students = get_students_for_group($conn, (int)$selected['group_id']);
        $lessons  = get_lessons_for_subject($conn, (int)$selected['subject_id']);
        $grades   = get_grades_map($conn, $students, $lessons);

        $html = build_journal_html($teacher, $selected, $students, $lessons, $grades);

        $tname = fsafe($teacher['full_name']);
        $sname = fsafe($selected['subject_name']);
        $gname = fsafe($selected['group_name']);
        $stamp = date('Y-m-d H-i');

        $baseDir = dirname(__DIR__) . '/archive/' . $tname;
        if (!is_dir($baseDir)) {
            @mkdir($baseDir, 0775, true);
        }

        $filename = "{$sname}, {$gname}, {$stamp}.pdf";
        $fullpath = $baseDir . '/' . $filename;

        $dompdf = new \Dompdf\Dompdf([
            'isRemoteEnabled'     => true,
            'isHtml5ParserEnabled'=> true,
        ]);
        $dompdf->loadHtml($html, 'UTF-8');
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();

        file_put_contents($fullpath, $dompdf->output());

        pdf_export_guard_end($guard);
        stream_download_and_exit($fullpath, 'application/pdf', $filename);
    } catch (\Throwable $e) {
        pdf_export_guard_end($guard);
        http_response_code(500);
        die('Помилка генерації PDF: ' . h($e->getMessage()));
    }
}

if ($action === 'zip_all' && !empty($subjects)) {
    if (!class_exists('ZipArchive')) {
        http_response_code(500);
        die('ZIP недоступний на сервері.');
    }

    $guard = pdf_export_guard_begin();

    try {
        set_time_limit(0);
        require_once $autoload;

        $tname   = fsafe($teacher['full_name']);
        $stamp   = date('Y-m-d_H-i');
        $baseArc = dirname(__DIR__) . '/archive/' . $tname;
        if (!is_dir($baseArc)) {
            @mkdir($baseArc, 0775, true);
        }

        $zipBase = ascii_safe("Journals_{$stamp}.zip");
        $zipPath = $baseArc . '/' . $zipBase;

        $zip = new ZipArchive();
        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
            throw new RuntimeException("Не вдалося створити ZIP архів.");
        }

        foreach ($subjects as $subj) {
            $students = get_students_for_group($conn, (int)$subj['group_id']);
            $lessons  = get_lessons_for_subject($conn, (int)$subj['subject_id']);
            $grades   = get_grades_map($conn, $students, $lessons);

            $html = build_journal_html($teacher, $subj, $students, $lessons, $grades);

            $sname = fsafe($subj['subject_name']);
            $gname = fsafe($subj['group_name']);

            $pdfDiskName = "{$sname}, {$gname}, {$stamp}.pdf";
            $pdfDiskPath = $baseArc . '/' . $pdfDiskName;

            $dompdf = new \Dompdf\Dompdf([
                'isRemoteEnabled'      => true,
                'isHtml5ParserEnabled' => true,
            ]);
            $dompdf->loadHtml($html, 'UTF-8');
            $dompdf->setPaper('A4', 'landscape');
            $dompdf->render();

            file_put_contents($pdfDiskPath, $dompdf->output());

            $entryName = ascii_safe($subj['subject_name']) . '_' . ascii_safe($subj['group_name']) . '_' . $stamp . '.pdf';
            if ($entryName === '') {
                $entryName = 'journal_' . uniqid('', true) . '.pdf';
            }

            $zip->addFile($pdfDiskPath, $entryName);
        }

        $zip->close();

        pdf_export_guard_end($guard);
        stream_download_and_exit($zipPath, 'application/zip', basename($zipPath));
    } catch (\Throwable $e) {
        pdf_export_guard_end($guard);
        http_response_code(500);
        die('Помилка генерації ZIP/PDF: ' . h($e->getMessage()));
    }
}

/* ===== Підготовка даних для перегляду ===== */
$students = $lessons = $grades_map = [];
if ($selected) {
    $students   = get_students_for_group($conn, (int)$selected['group_id']);
    $lessons    = get_lessons_for_subject($conn, (int)$selected['subject_id']);
    $grades_map = get_grades_map($conn, $students, $lessons);
}

/* ===== Заголовок сторінки ===== */
$page_title  = 'Профіль викладача — ' . $teacher['full_name'];
$active_page = 'teacher_profile';

/* ===== Навігація адмінпанелі ===== */
$navItems = [];
if ($auth_role === 'admin') {
    $navItems = [
        ['href' => 'dashboard.php',      'label' => 'Журнали'],
        ['href' => '../journal/group_journal.php', 'label' => 'Управління журналами'],
        ['href' => 'dz/index.php',       'label' => 'Домашнє завдання'],
        ['href' => 'admin_students.php', 'label' => 'Учні'],
        ['href' => 'admin_father.php',   'label' => 'Батьки'],
        ['href' => 'admin_teachers.php', 'label' => 'Вчителі'],
        ['href' => 'admin_system.php',   'label' => 'Система'],
    ];
}

$current_file = basename($_SERVER['PHP_SELF'] ?? '');
$nav_current  = $current_file;
if ($auth_role === 'admin' && $nav_current === 'teacher_profile.php') {
    $nav_current = 'admin_teachers.php';
}
?>
<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="UTF-8">
    <meta name="robots" content="noindex, nofollow">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <title><?php echo h($page_title); ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        :root{
            --brand:#402050;
            --brand-hover:#341a44;
            --mint:#a0e0d0;
            --mint-soft:#eaf8f4;

            --bg: var(--mint-soft);
            --card:#ffffff;
            --text:#1f2937;
            --muted: rgba(31,41,55,.72);

            --radius:14px;
            --shadow:0 10px 24px rgba(17,24,39,.08);
            --border: rgba(64,32,80,.12);

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

        .container{
            width:100%;
            max-width:980px;
            padding:16px;
            margin:0 auto;
        }

        .admin-tabs{
            display:flex;
            gap:10px;
            flex-wrap:wrap;
            align-items:center;
            margin: 2px 0 14px;
        }
        .admin-tabs a{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            gap:8px;
            padding:10px 14px;
            border-radius:999px;
            text-decoration:none;
            font-weight:900;
            font-size:14px;
            color: var(--text);
            background: rgba(67,40,85,.08);
            border: 1px solid rgba(67,40,85,.18);
            box-shadow: 0 10px 22px rgba(67,40,85,.08);
            transition: transform .08s ease, box-shadow .12s ease, background .12s ease, border-color .12s ease;
        }
        .admin-tabs a:hover{
            transform: translateY(-1px);
            background: rgba(160,232,208,.45);
            border-color: rgba(67,40,85,.22);
            box-shadow: 0 14px 28px rgba(67,40,85,.10);
        }
        .admin-tabs a.active{
            color:#fff;
            background: linear-gradient(135deg, var(--brand) 0%, #4b2a61 55%, rgba(160,232,208,.95) 120%);
            border-color: rgba(255,255,255,.22);
            box-shadow: 0 18px 40px rgba(67,40,85,.18);
        }

        .card{
            background:var(--card);
            border-radius:var(--radius);
            box-shadow:var(--shadow);
            padding:18px;
            border:1px solid rgba(64,32,80,.08);
        }
        h1{
            margin:0 0 8px;
            font-size:22px;
            text-align:center;
        }
        .lead{
            color:var(--muted);
            font-size:14px;
            text-align:center;
            margin:0 0 14px;
        }

        .grid{ display:grid; gap:12px; }
        .item{
            border:1px solid var(--border);
            border-radius:12px;
            background:#fff;
            padding:12px;
        }
        .item h3{ margin:0 0 4px; font-size:15px; }
        .muted{ color:var(--muted); font-size:13px; margin:0 0 10px; }
        .row-actions{ display:flex; gap:8px; flex-wrap:wrap; }

        .btn{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            gap:6px;
            padding:10px 14px;
            font-size:14px;
            font-weight:800;
            border-radius:999px;
            border:1px solid var(--brand);
            background:var(--brand);
            color:#fff;
            text-decoration:none;
            cursor:pointer;
        }
        .btn:hover{ background:var(--brand-hover); border-color:var(--brand-hover); }

        .btn.secondary{
            background:#fff;
            color:var(--brand);
            border-color: rgba(64,32,80,.28);
        }
        .btn.secondary:hover{
            background: var(--mint-soft);
            border-color: rgba(64,32,80,.40);
        }

        .journal{ overflow:auto; }
        table{ width:100%; border-collapse:collapse; }
        th, td{ border:1px solid rgba(64,32,80,.14); padding:8px; font-size:13px; }
        th{ background: var(--mint-soft); text-align:left; color:#1f2937; }
        tr:nth-child(even) td{ background:#fbfffe; }
        tr:hover td{ background:#f3fbf8; }
        .center{ text-align:center; }

        .toolbar{
            display:flex;
            gap:8px;
            flex-wrap:wrap;
            justify-content:center;
            margin-bottom:12px;
        }

        @media (max-width:540px){
            .grid{ grid-template-columns: 1fr; }
            .row-actions .btn{ flex:1 1 100%; }
            .btn{ width:100%; }
            .container{ padding:10px; }
            th, td{ padding:6px; font-size:12px; }
            .admin-tabs{ margin: 10px 0 14px; }
            .admin-tabs a{ flex:1 1 auto; }
        }
        @media (min-width:768px){
            .card{ padding:22px; }
            h1{ font-size:24px; }
            .grid{ grid-template-columns: 1fr 1fr; }
        }
    </style>
</head>
<body>

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

<main class="container">

    <?php if (!empty($navItems)): ?>
        <nav class="admin-tabs" aria-label="Адмін навігація">
            <?php foreach ($navItems as $it): ?>
                <?php
                $href = (string)($it['href'] ?? '');
                $lbl  = (string)($it['label'] ?? '');
                $isActive = (basename($href) === $nav_current);
                ?>
                <a href="<?php echo h($href); ?>" class="<?php echo $isActive ? 'active' : ''; ?>">
                    <?php echo h($lbl); ?>
                </a>
            <?php endforeach; ?>
        </nav>
    <?php endif; ?>

    <section class="card">
        <h1><?php echo h($teacher['full_name']); ?></h1>
        <p class="lead">Список предметів за групами, експорт журналів у PDF або ZIP.</p>

        <?php if (!empty($subjects)): ?>
            <div class="toolbar">
                <a class="btn" href="?teacher_id=<?php echo (int)$teacher_id; ?>&action=zip_all">
                    Завантажити ZIP усіх журналів (PDF)
                </a>
            </div>
        <?php endif; ?>

        <?php if (empty($subjects)): ?>
            <p class="lead">У цього викладача поки не додано предметів.</p>
        <?php else: ?>
            <div class="grid">
                <?php foreach ($subjects as $s): ?>
                    <div class="item">
                        <h3><?php echo h($s['subject_name']); ?></h3>
                        <p class="muted">Група: <?php echo h($s['group_name']); ?></p>
                        <div class="row-actions">
                            <a class="btn secondary"
                               href="?teacher_id=<?php echo (int)$teacher_id; ?>&subject_id=<?php echo (int)$s['subject_id']; ?>">
                                Переглянути журнал
                            </a>
                            <a class="btn"
                               href="?teacher_id=<?php echo (int)$teacher_id; ?>&subject_id=<?php echo (int)$s['subject_id']; ?>&action=pdf">
                                Експорт у PDF
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>

    <?php if ($selected): ?>
        <?php
        $students   = get_students_for_group($conn, (int)$selected['group_id']);
        $lessons    = get_lessons_for_subject($conn, (int)$selected['subject_id']);
        $grades_map = get_grades_map($conn, $students, $lessons);
        ?>
        <section class="card" style="margin-top:14px">
            <h2 style="margin:0 0 8px; text-align:center; font-size:18px">
                Журнал: <?php echo h($selected['subject_name'] . ' — ' . $selected['group_name']); ?>
            </h2>
            <div class="journal">
                <table>
                    <thead>
                    <tr>
                        <th style="width:40px" class="center">№</th>
                        <th>ПІБ учня</th>
                        <?php if (!empty($lessons)): ?>
                            <?php foreach ($lessons as $l): ?>
                                <th class="center" title="<?php echo h((string)$l['topic']); ?>">
                                    <?php
                                    $t = trim((string)$l['topic']);
                                    if (mb_strlen($t, 'UTF-8') > 12) {
                                        $t = mb_substr($t, 0, 12, 'UTF-8') . '…';
                                    }
                                    echo h($t);
                                    ?>
                                </th>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <th class="center">Уроків немає</th>
                        <?php endif; ?>
                        <th class="center">Ø</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if (empty($students)): ?>
                        <tr>
                            <td class="center" colspan="<?php echo 3 + max(1, count($lessons)); ?>">
                                Немає учнів у цій групі.
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($students as $i => $st): ?>
                            <tr>
                                <td class="center"><?php echo $i + 1; ?></td>
                                <td><?php echo h($st['full_name']); ?></td>
                                <?php
                                $sum = 0;
                                $cnt = 0;

                                if (!empty($lessons)):
                                    foreach ($lessons as $l):
                                        $key = $st['id'] . ':' . $l['id'];
                                        $g   = $grades_map[$key] ?? '';
                                        if ($g !== '' && is_numeric($g)) {
                                            $sum += (float)$g;
                                            $cnt++;
                                        }
                                        echo '<td class="center">' . h((string)$g) . '</td>';
                                    endforeach;
                                else:
                                    echo '<td class="center">—</td>';
                                endif;

                                $avg = ($cnt > 0) ? round($sum / $cnt, 2) : '—';
                                ?>
                                <td class="center"><?php echo h((string)$avg); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="toolbar" style="margin-top:12px">
                <a class="btn"
                   href="?teacher_id=<?php echo (int)$teacher_id; ?>&subject_id=<?php echo (int)$selected['subject_id']; ?>&action=pdf">
                    Завантажити PDF
                </a>
            </div>
        </section>
    <?php endif; ?>
</main>

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

</body>
</html>