<?php
declare(strict_types=1);

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

if (!isset($_SESSION['user_id'])) {
    header('Location: /index.php');
    exit();
}

$uid  = (int)($_SESSION['user_id'] ?? 0);
$role = (string)($_SESSION['role'] ?? '');

function h(?string $s): string { return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

function allowed_group_ids(mysqli $conn, int $uid, string $role): array {
    $ids = [];

    if ($role === 'admin') {
        $q = $conn->query("SELECT id FROM `groups`");
        if ($q) { while ($r = $q->fetch_assoc()) $ids[] = (int)$r['id']; $q->free(); }
        return array_values(array_unique(array_filter($ids)));
    }

    if ($role === 'student') {
        $st = $conn->prepare("SELECT group_id FROM users WHERE id=? AND role='student' LIMIT 1");
        if ($st) {
            $st->bind_param('i', $uid);
            $st->execute();
            $res = $st->get_result();
            if ($res && ($r = $res->fetch_assoc())) $ids[] = (int)($r['group_id'] ?? 0);
            $st->close();
        }
        return array_values(array_unique(array_filter($ids)));
    }

    if ($role === 'parent') {
        $st = $conn->prepare("
            SELECT DISTINCT u.group_id
            FROM parent_links pl
            JOIN users u ON u.id = pl.student_id AND u.role='student'
            WHERE pl.parent_id=?
        ");
        if ($st) {
            $st->bind_param('i', $uid);
            $st->execute();
            $res = $st->get_result();
            while ($res && ($r = $res->fetch_assoc())) $ids[] = (int)($r['group_id'] ?? 0);
            $st->close();
        }
        return array_values(array_unique(array_filter($ids)));
    }

    if ($role === 'teacher') {
        $st = $conn->prepare("SELECT id FROM `groups` WHERE class_teacher_id=?");
        if ($st) {
            $st->bind_param('i', $uid);
            $st->execute();
            $res = $st->get_result();
            while ($res && ($r = $res->fetch_assoc())) $ids[] = (int)$r['id'];
            $st->close();
        }
        $st2 = $conn->prepare("SELECT DISTINCT group_id FROM subjects WHERE teacher_id=?");
        if ($st2) {
            $st2->bind_param('i', $uid);
            $st2->execute();
            $res = $st2->get_result();
            while ($res && ($r = $res->fetch_assoc())) $ids[] = (int)($r['group_id'] ?? 0);
            $st2->close();
        }
        return array_values(array_unique(array_filter($ids)));
    }

    return [];
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { http_response_code(400); exit('Невірний id'); }

$st = $conn->prepare("
    SELECT t.*, s.subject_name, g.group_name
    FROM homework_tasks t
    JOIN subjects s ON s.id=t.subject_id
    JOIN `groups` g ON g.id=t.group_id
    WHERE t.id=?
    LIMIT 1
");
$task = null;
if ($st) {
    $st->bind_param('i', $id);
    $st->execute();
    $res = $st->get_result();
    $task = $res ? $res->fetch_assoc() : null;
    $st->close();
}
if (!$task) { http_response_code(404); exit('Завдання не знайдено'); }

$gids = allowed_group_ids($conn, $uid, $role);
if (!in_array((int)$task['group_id'], $gids, true)) { http_response_code(403); exit('Недостатньо прав'); }

$links = [];
$stL = $conn->prepare("SELECT url FROM homework_links WHERE task_id=? ORDER BY sort_order ASC, id ASC");
if ($stL) {
    $stL->bind_param('i', $id);
    $stL->execute();
    $res = $stL->get_result();
    while ($res && ($r = $res->fetch_assoc())) $links[] = (string)($r['url'] ?? '');
    $stL->close();
}

$files = [];
$stF = $conn->prepare("SELECT file_path, original_name, file_size FROM homework_files WHERE task_id=? ORDER BY id ASC");
if ($stF) {
    $stF->bind_param('i', $id);
    $stF->execute();
    $res = $stF->get_result();
    while ($res && ($r = $res->fetch_assoc())) $files[] = $r;
    $stF->close();
}

$created = (string)($task['created_at'] ?? '');
$createdHuman = $created ? date('d.m.Y', strtotime($created)) : '';
$due = (string)($task['due_date'] ?? '');
$dueHuman = $due ? date('d.m.Y', strtotime($due)) : '';

$header_title = 'Домашнє завдання';
?>
<!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);
            --danger:#b91c1c;
        }
        *{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;}
        .title{margin:0 0 8px;color:var(--brand-purple);font-size:22px;font-weight:1000;line-height:1.2;}
        .meta{color:var(--muted);font-weight:800;font-size:13px;line-height:1.5;}
        .due{margin-top:10px;font-weight:1000;color:var(--danger);}
        .body{margin-top:14px;white-space:pre-line;line-height:1.6;font-weight:700;}
        .block{margin-top:14px;}
        .block h3{margin:0 0 8px;color:var(--brand-purple);font-size:16px;font-weight:1000;}
        ul{margin:0;padding-left:18px;}
        li{margin:6px 0;}
        a{color:var(--brand-purple);font-weight:900;}
        .btn{
            display:inline-flex;align-items:center;justify-content:center;gap:8px;
            padding:12px 16px;border-radius:999px;border:1px solid rgba(0,0,0,.10);
            background:#fff;color:var(--brand-purple);text-decoration:none;font-weight:1000;
            box-shadow:0 10px 18px rgba(0,0,0,.08);
        }
        .btn:active{transform:translateY(1px)}
        @media (max-width:600px){.wrap{padding:12px}}
    </style>
</head>
<body>

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

<main class="wrap">
    <section class="card">
        <h1 class="title"><?= h((string)$task['subject_name']) ?></h1>
        <div class="meta">
            <?= h((string)$task['group_name']) ?><br>
            Завдання від: <?= h($createdHuman) ?>
        </div>

        <?php if ($dueHuman !== ''): ?>
            <div class="due">Виконати до: <?= h($dueHuman) ?></div>
        <?php endif; ?>

        <div class="body"><?= nl2br(h((string)$task['body'])) ?></div>

        <?php if (!empty($links)): ?>
            <div class="block">
                <h3>Посилання</h3>
                <ul>
                    <?php foreach ($links as $u): ?>
                        <?php if ($u === '') continue; ?>
                        <li><a href="<?= h($u) ?>" target="_blank" rel="noopener noreferrer"><?= h($u) ?></a></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <?php if (!empty($files)): ?>
            <div class="block">
                <h3>Файли</h3>
                <ul>
                    <?php foreach ($files as $f): ?>
                        <?php
                            $p = (string)($f['file_path'] ?? '');
                            $n = (string)($f['original_name'] ?? 'file');
                        ?>
                        <?php if ($p === '') continue; ?>
                        <li><a href="<?= h($p) ?>" download><?= h($n) ?></a></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <div style="margin-top:16px;">
            <a class="btn" href="/dz/dz.php">← Назад</a>
        </div>
    </section>
</main>

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

</body>
</html>