﻿﻿??????????????
﻿﻿??????????????
<?php
include('session-st.php');
include 'connection.php';

if (!isset($_GET['file'])) {
    echo "Access denied or file not found.";
    exit;
}

// Only allow a filename (prevent ../, absolute paths etc)
$filename = basename($_GET['file']);               // e.g. 2_1765177917_8725.pdf
if ($filename === '' || strpos($filename, '.') === false) {
    echo "Invalid file.";
    exit;
}

// Build the safe server-side absolute path where files actually live
$baseDir = realpath(__DIR__ . "/../uploads/tasks"); // resolves symlinks, gives absolute path
if ($baseDir === false) {
    echo "Server error.";
    exit;
}
$fullPath = $baseDir . DIRECTORY_SEPARATOR . $filename;

// Student course from session
$student_course = $_SESSION['course'] ?? null;
if (!$student_course) {
    echo "Access denied.";
    exit;
}

// Prepare DB check.
// The DB stores paths like "../uploads/tasks/filename.pdf" — so prepare multiple variants to match.
$stored_with_dotdot = "../uploads/tasks/" . $filename;
$stored_without_dotdot = "uploads/tasks/" . $filename;
$like_filename = "%" . $filename; // fallback if other unexpected prefixes used

$sql = "SELECT tf.file_path
        FROM tasks t
        JOIN task_files tf ON t.id = tf.task_id
        WHERE (tf.file_path = ? OR tf.file_path = ? OR tf.file_path LIKE ?)
          AND t.course = ?
          AND t.status IN ('active','published')
        LIMIT 1";

$stmt = $conn->prepare($sql);
if ($stmt === false) {
    echo "DB error.";
    exit;
}
$stmt->bind_param("ssss", $stored_with_dotdot, $stored_without_dotdot, $like_filename, $student_course);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo "Access denied or file not found.";
    exit;
}

// Ensure the file exists in the safe folder before serving
if (!is_file($fullPath) || !is_readable($fullPath)) {
    echo "File not found.";
    exit;
}

// Safe MIME map
$file_ext = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
$mime_types = [
    'pdf'  => 'application/pdf',
    'doc'  => 'application/msword',
    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'jpg'  => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'png'  => 'image/png'
];

if (!isset($mime_types[$file_ext])) {
    echo "Unsupported file type.";
    exit;
}

// Serve the file (inline so PDF opens in browser)
header('Content-Type: ' . $mime_types[$file_ext]);
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Length: ' . filesize($fullPath));

// readfile in chunks (better for large files)
$fp = fopen($fullPath, 'rb');
if ($fp) {
    while (!feof($fp)) {
        echo fread($fp, 8192);
        flush();
    }
    fclose($fp);
}
exit;
?>
