<?php
// download
if (isset($_POST['id'])) {
    $id = (int)$_POST['id'];
    $stmt = $connection->prepare("SELECT file_path FROM lesson_plans WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows === 1) {
        $file = $res->fetch_assoc()['file_path'];

        // Construct absolute file path
        $base_dir = realpath($_SERVER['DOCUMENT_ROOT'] . '/uploads/lesson_plans/');
        $full_path = realpath($base_dir . '/' . basename($file));

        // Validate file exists and is within the intended directory
        if ($full_path && strpos($full_path, $base_dir) === 0 && file_exists($full_path)) {
            // Clear output buffer to prevent any prior output
            ob_clean();
            flush();

            // Set headers for PDF download
            header('Content-Description: File Transfer');
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="' . basename($full_path) . '"');
            header('Content-Length: ' . filesize($full_path));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');

            // Read the file
            readfile($full_path);
            exit;
        } else {
            $_SESSION['msg'] = "File not found or access denied.";
            $_SESSION['type'] = "danger";
        }
    } else {
        $_SESSION['msg'] = "Lesson plan not found.";
        $_SESSION['type'] = "danger";
    }

    // Redirect to lesson plans page on error
    header("Location: lesson_plans");
    exit;
}
?>
<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Lesson Plan</h1>
    <p>Class Lesson Plans</p>
  </div>  
</div>

<!-- Display Uploaded Lesson Plans -->
<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>Lesson Plans</h4>
        </div>
        <div class='panel-body'>
            <table class='table table-bordered'>
				<thead>
					<tr>
						<th>Subject</th>
						<th>Class</th>
						<th>Term</th>
						<th>Session</th>
						<th>Upload Date</th>                        
						<th>Action</th>
					</tr>
				</thead>
				<tbody>
					<?php
						$query = "SELECT * FROM lesson_plans ORDER BY upload_date DESC";
						$result = mysqli_query($connection, $query);
						$sn = 1; // Initialize serial number
						while ($row = mysqli_fetch_assoc($result)) {
						    echo "<tr>
    <td>{$row['subject']}</td>
    <td>{$row['class']}</td>
    <td>{$row['term']}</td>
    <td>{$row['session']}</td>
    <td>{$row['upload_date']}</td>
    <td>";

if (!empty($row['file_path'])) {
    echo "<form method='POST' action=''>
            <input type='hidden' name='id' value='" . htmlspecialchars($row['id']) . "'>
            <button type='submit' class='btn btn-success btn-sm'>Download</button>
          </form>";
} else {
    echo "N/A";
}
					    $sn++; // Increment serial number
						}
					?>
				</tbody>
			</table>
        </div>
    </div>
</div>

