<?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 [];
}

$gids = allowed_group_ids($conn, $uid, $role);
if (!$gids) {
    $header_title = 'Домашнє завдання';
    ?>
    <!DOCTYPE html>
    <html lang="uk">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Домашнє завдання</title>
        <link rel="stylesheet" href="/assets/css/style.css">
    </head>
    <body>
    <?php require_once __DIR__ . '/../includes/header.php'; ?>
    <div style="max-width:1000px;margin:16px auto;padding:16px;">
        <div style="background:#fff;border:1px solid rgba(0,0,0,.10);border-radius:16px;box-shadow:0 10px 24px rgba(0,0,0,.08);padding:18px;font-weight:900;">
            Немає доступних груп для перегляду домашніх завдань.
        </div>
    </div>
    <?php require_once __DIR__ . '/../includes/footer.php'; ?>
    </body>
    </html>
    <?php
    exit();
}

$filter_group = (int)($_GET['group_id'] ?? 0);
if ($filter_group > 0 && !in_array($filter_group, $gids, true)) $filter_group = 0;

$groupsMap = [];
$in = implode(',', array_map('intval', $gids));
$qg = $conn->query("SELECT id, group_name FROM `groups` WHERE id IN ($in) ORDER BY group_name ASC");
if ($qg) { while ($r = $qg->fetch_assoc()) $groupsMap[(int)$r['id']] = (string)$r['group_name']; $qg->free(); }

$where = $filter_group > 0 ? "t.group_id=".(int)$filter_group : "t.group_id IN ($in)";

$sql = "
    SELECT t.id, t.group_id, t.subject_id, t.teacher_id, t.due_date, t.created_at,
           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 $where
    ORDER BY t.created_at DESC, t.id DESC
    LIMIT 200
";
$tasks = [];
$qt = $conn->query($sql);
if ($qt) { while ($r = $qt->fetch_assoc()) $tasks[] = $r; $qt->free(); }

$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:1100px;margin:16px auto;padding:16px;}
        .top{display:flex;align-items:flex-end;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:12px;}
        h1{margin:0;color:var(--brand-purple);font-size:22px;font-weight:1000;}
        .filter{min-width:min(520px,100%);}
        label{display:block;margin:0 0 6px;font-weight:900;color:var(--brand-purple);font-size:14px;}
        select{width:100%;padding:12px;border:1px solid rgba(0,0,0,.14);border-radius:12px;background:#fff;font-size:15px;}
        .grid{display:grid;gap:12px;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));}
        .card{
            background:var(--card);
            border:1px solid rgba(0,0,0,.10);
            border-radius:16px;
            box-shadow:var(--shadow);
            padding:14px;
            text-decoration:none;
            color:var(--ink);
            transition: transform .12s ease, box-shadow .12s ease;
            display:block;
        }
        .card:hover{transform:translateY(-1px);box-shadow:0 14px 28px rgba(0,0,0,.12);}
        .title{font-weight:1000;color:var(--brand-purple);font-size:16px;line-height:1.25;margin:0 0 6px;}
        .meta{color:var(--muted);font-weight:800;font-size:13px;line-height:1.4;}
        .due{margin-top:10px;font-weight:1000;color:var(--danger);}
        .empty{
            background:#fff;border:1px solid rgba(0,0,0,.10);border-radius:16px;box-shadow:var(--shadow);
            padding:18px;font-weight:900;color:var(--muted);
        }
        @media (max-width:600px){.wrap{padding:12px}}
    </style>
</head>
<body>

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

<main class="wrap">
    <div class="top">
        <h1>Домашнє завдання</h1>

        <?php if (count($gids) > 1): ?>
        <div class="filter">
            <label>Група</label>
            <select onchange="location='?group_id='+this.value">
                <option value="0">Всі доступні групи</option>
                <?php foreach ($groupsMap as $gid => $gn): ?>
                    <option value="<?= (int)$gid ?>" <?= ((int)$gid===$filter_group?'selected':'') ?>><?= h($gn) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
    </div>

    <?php if (!$tasks): ?>
        <div class="empty">Поки що немає домашніх завдань.</div>
    <?php else: ?>
        <div class="grid">
            <?php foreach ($tasks as $t): ?>
                <?php
                    $created = (string)($t['created_at'] ?? '');
                    $createdHuman = $created ? date('d.m.Y', strtotime($created)) : '';
                    $due = (string)($t['due_date'] ?? '');
                    $dueHuman = $due ? date('d.m.Y', strtotime($due)) : '';
                ?>
                <a class="card" href="/dz/view.php?id=<?= (int)$t['id'] ?>">
                    <div class="title"><?= h((string)$t['subject_name']) ?></div>
                    <div class="meta">
                        <?= h((string)$t['group_name']) ?><br>
                        Завдання від: <?= h($createdHuman) ?>
                    </div>
                    <?php if ($dueHuman !== ''): ?>
                        <div class="due">Виконати до: <?= h($dueHuman) ?></div>
                    <?php endif; ?>
                </a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</main>

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

</body>
</html>