<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

/* session is already started in header.php */
if (!isset($_SESSION['student'])) {
    echo "ERROR: student session missing";
    exit;
}

require_once("public/connection.php");

$student_id = (int) $_SESSION['student'];

/* =========================
   FETCH STUDENT CLASS
========================= */
$stmt = $connection->prepare("SELECT class FROM students WHERE id = ?");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    echo "ERROR: student not found";
    exit;
}

$student_class = $res->fetch_assoc()['class'];
$stmt->close();

/* =========================
/* =========================
   DOWNLOAD HANDLER (FIXED)
========================= */
if (isset($_POST['download_id'])) {
    $id = (int) $_POST['download_id'];

    $stmt = $connection->prepare("
        SELECT file_path, file_name
        FROM lesson_plans
        WHERE id = ? AND class = ?
        LIMIT 1
    ");
    $stmt->bind_param("is", $id, $student_class);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows !== 1) {
        die("ERROR: File not found");
    }

    $row = $res->fetch_assoc();

    // Build absolute file path safely
    $filePath = $_SERVER['DOCUMENT_ROOT'] . "/uploads/lesson_plans/" . basename($row['file_path']);

    if (!file_exists($filePath)) {
        die("ERROR: File does not exist on server");
    }

    // Clean any previous output
    if (ob_get_length()) {
        ob_end_clean();
    }

    // Detect mime type automatically
    $mime = mime_content_type($filePath);

    header("Content-Description: File Transfer");
    header("Content-Type: $mime");
    header("Content-Disposition: attachment; filename=\"" . basename($row['file_name']) . "\"");
    header("Content-Length: " . filesize($filePath));
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: public");

    readfile($filePath);
    exit;
}

/* =========================
   FETCH LESSON PLANS
========================= */
$stmt = $connection->prepare("
    SELECT *
    FROM lesson_plans
    WHERE class = ?
    ORDER BY upload_date DESC
");
$stmt->bind_param("s", $student_class);
$stmt->execute();
$result = $stmt->get_result();
?>

<h3><i class="fa fa-book-open"></i> My E-Notes (<?= htmlspecialchars($student_class) ?>)</h3>

<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
    <th>File</th>
    <th>Subject</th>
    <th>Term</th>
    <th>Session</th>
    <th>Date</th>
    <th>Download</th>
</tr>
</thead>
<tbody>

<?php if ($result->num_rows === 0): ?>
<tr>
    <td colspan="6" class="text-center text-muted">
        No lesson notes available for your class
    </td>
</tr>
<?php endif; ?>

<?php while ($row = $result->fetch_assoc()): ?>
<tr>
    <td><?= htmlspecialchars($row['file_name']) ?></td>
    <td><?= htmlspecialchars($row['subject']) ?></td>
    <td><?= htmlspecialchars($row['term']) ?></td>
    <td><?= htmlspecialchars($row['session']) ?></td>
    <td><?= htmlspecialchars($row['upload_date']) ?></td>
    <td>
        <form method="POST">
            <input type="hidden" name="download_id" value="<?= $row['id'] ?>">
            <button class="btn btn-success btn-sm">
                Download
            </button>
        </form>
    </td>
</tr>
<?php endwhile; ?>

</tbody>
</table>
</div>
