<?php
// Handle Download
if (isset($_GET['download'])) {
    $id = (int)$_GET['download'];
    $stmt = $connection->prepare("SELECT file_path, title FROM curriculum WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        $file = $row['file_path'];
        if (file_exists($file)) {
            ob_clean();
            flush();
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($file) . '"');
            header('Content-Length: ' . filesize($file));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            readfile($file);
            exit;
        }
    }
    $_SESSION['msg'] = "File not found.";
    $_SESSION['type'] = "danger";
    header("Location: student_elibrary");
    exit;
}

// Get the student's class from session
$student_class = '';
$reg = $_SESSION['reg_number'] ?? '';
if ($reg) {
    $res = mysqli_query($connection, "SELECT class FROM students WHERE reg_number = '" . mysqli_real_escape_string($connection, $reg) . "' LIMIT 1");
    if ($row = mysqli_fetch_assoc($res)) {
        $student_class = $row['class'];
    }
}

// Filter logic
$filter_category = $_GET['filter_category'] ?? '';
$filter_subject  = $_GET['filter_subject'] ?? '';

$sql = "SELECT * FROM curriculum WHERE (class = '" . mysqli_real_escape_string($connection, $student_class) . "' OR class = 'All Classes') ";
if ($filter_category) $sql .= " AND category = '" . mysqli_real_escape_string($connection, $filter_category) . "'";
if ($filter_subject)  $sql .= " AND subject = '"  . mysqli_real_escape_string($connection, $filter_subject) . "'";
$sql .= " ORDER BY id DESC";
$materials = mysqli_query($connection, $sql);

// Counts for stats
$count_books  = mysqli_num_rows(mysqli_query($connection, "SELECT id FROM curriculum WHERE class = '" . mysqli_real_escape_string($connection, $student_class) . "' AND category='E-Book'"));
$count_notes  = mysqli_num_rows(mysqli_query($connection, "SELECT id FROM curriculum WHERE class = '" . mysqli_real_escape_string($connection, $student_class) . "' AND category='Class Note'"));
$count_assign = mysqli_num_rows(mysqli_query($connection, "SELECT id FROM curriculum WHERE class = '" . mysqli_real_escape_string($connection, $student_class) . "' AND category='Assignment'"));
?>

<div class="page-title">
    <div>
        <h1><i class="fa fa-book-reader"></i> My Digital Library</h1>
        <p>Download class notes, e-books and assignments for your class: <strong><?= htmlspecialchars($student_class) ?></strong></p>
    </div>
</div>

<!-- Stats Row -->
<div class="row">
    <div class="col-md-4">
        <div class="card p-3 mb-4 text-white border-0 shadow-sm" style="background: linear-gradient(135deg, #3a7bd5, #3a6073);">
            <h3><?= $count_books ?></h3>
            <p class="mb-0"><i class="fa fa-book mr-1"></i> E-Books Available</p>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card p-3 mb-4 text-white border-0 shadow-sm" style="background: linear-gradient(135deg, #11998e, #38ef7d);">
            <h3><?= $count_notes ?></h3>
            <p class="mb-0"><i class="fa fa-scroll mr-1"></i> Class Notes</p>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card p-3 mb-4 text-white border-0 shadow-sm" style="background: linear-gradient(135deg, #f7971e, #ffd200);">
            <h3><?= $count_assign ?></h3>
            <p class="mb-0"><i class="fa fa-tasks mr-1"></i> Assignments</p>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="card p-3 mb-4 border-0 shadow-sm">
    <form class="form-inline" method="GET">
        <input type="hidden" name="view" value="student_elibrary">
        <label class="mr-2 font-weight-bold">Filter:</label>

        <select name="filter_category" class="form-control form-control-sm mr-2" onchange="this.form.submit()">
            <option value="">-- All Categories --</option>
            <option value="E-Book"     <?= $filter_category == 'E-Book'    ? 'selected' : '' ?>>E-Books</option>
            <option value="Class Note" <?= $filter_category == 'Class Note' ? 'selected' : '' ?>>Class Notes</option>
            <option value="Assignment" <?= $filter_category == 'Assignment' ? 'selected' : '' ?>>Assignments</option>
        </select>

        <select name="filter_subject" class="form-control form-control-sm mr-2" onchange="this.form.submit()">
            <option value="">-- All Subjects --</option>
            <?php
            $sub_res = mysqli_query($connection, "SELECT DISTINCT subject FROM curriculum WHERE class = '" . mysqli_real_escape_string($connection, $student_class) . "' ORDER BY subject");
            while ($s = mysqli_fetch_row($sub_res)):
                $selected = ($filter_subject == $s[0]) ? 'selected' : '';
            ?>
                <option value="<?= $s[0] ?>" <?= $selected ?>><?= $s[0] ?></option>
            <?php endwhile; ?>
        </select>

        <a href="?view=student_elibrary" class="btn btn-sm btn-outline-secondary">Reset</a>
    </form>
</div>

<!-- Materials Grid -->
<?php if (mysqli_num_rows($materials) > 0): ?>
<div class="row">
    <?php while ($row = mysqli_fetch_assoc($materials)):
        $ext = strtolower(pathinfo($row['file_path'], PATHINFO_EXTENSION));
        $icon  = 'fa-file-pdf text-danger';
        if (in_array($ext, ['doc', 'docx']))     $icon = 'fa-file-word text-primary';
        if (in_array($ext, ['ppt', 'pptx']))     $icon = 'fa-file-powerpoint text-warning';
        if (in_array($ext, ['zip', 'rar']))      $icon = 'fa-file-archive text-secondary';
        $badge = ['E-Book' => 'badge-primary', 'Class Note' => 'badge-success', 'Assignment' => 'badge-warning'];
        $badge_class = $badge[$row['category']] ?? 'badge-secondary';
    ?>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm mb-4 h-100">
            <div class="card-body text-center p-4">
                <i class="fa <?= $icon ?> fa-4x mb-3"></i>
                <span class="badge <?= $badge_class ?> px-2 py-1 mb-2 d-block"><?= $row['category'] ?></span>
                <h5 class="font-weight-bold"><?= htmlspecialchars($row['title']) ?></h5>
                <p class="text-muted small mb-1"><i class="fa fa-tag mr-1"></i><?= $row['subject'] ?></p>
                <p class="text-muted small"><?= $row['description'] ? substr($row['description'], 0, 80) . '...' : '' ?></p>
                <p class="text-muted small"><i class="fa fa-user mr-1"></i>By: <?= $row['uploaded_by'] ?></p>
            </div>
            <div class="card-footer bg-white border-0 text-center pb-3">
                <a href="?view=student_elibrary&download=<?= $row['id'] ?>" class="btn btn-primary btn-sm px-4">
                    <i class="fa fa-download mr-1"></i> Download
                </a>
            </div>
        </div>
    </div>
    <?php endwhile; ?>
</div>
<?php else: ?>
<div class="card border-0 shadow-sm text-center py-5">
    <div class="card-body text-muted">
        <i class="fa fa-folder-open fa-4x mb-3 d-block"></i>
        <h5>No materials available for your class yet.</h5>
        <p>Check back later or contact your teacher.</p>
    </div>
</div>
<?php endif; ?>
