<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];

// Get file ID
$file_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($file_id <= 0) {
    die('Invalid file ID');
}

// Get user info based on role
$user_info = null;
if ($user_role == 'student') {
    $stmt = $pdo->prepare("SELECT * FROM students WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_info = $stmt->fetch();
} elseif ($user_role == 'teacher') {
    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_info = $stmt->fetch();
}

// Get file information
$stmt = $pdo->prepare("
    SELECT fu.*, 
           CASE 
               WHEN fu.uploader_type = 'student' THEN CONCAT(s.first_name, ' ', s.last_name)
               WHEN fu.uploader_type = 'teacher' THEN CONCAT(t.first_name, ' ', t.last_name)
               ELSE 'Admin'
           END as uploader_name
    FROM file_uploads fu
    LEFT JOIN students s ON fu.uploader_type = 'student' AND fu.uploader_id = s.id
    LEFT JOIN teachers t ON fu.uploader_type = 'teacher' AND fu.uploader_id = t.id
    WHERE fu.id = ? AND fu.status = 'active'
");
$stmt->execute([$file_id]);
$file = $stmt->fetch();

if (!$file) {
    die('File not found');
}

// Check permissions
$can_download = false;

// Admin can download everything
if ($user_role == 'admin') {
    $can_download = true;
}
// Owner can download their own files
elseif ($file['uploader_type'] == $user_role && $file['uploader_id'] == $user_info['id']) {
    $can_download = true;
}
// Students can download public teacher files
elseif ($user_role == 'student' && $file['uploader_type'] == 'teacher' && $file['is_public'] == 1) {
    // Check if file is for student's class or general
    if ($file['target_class_id'] == null || $file['target_class_id'] == $user_info['class_id']) {
        $can_download = true;
    }
}
// Teachers can download public files from other teachers
elseif ($user_role == 'teacher' && $file['uploader_type'] == 'teacher' && $file['is_public'] == 1) {
    $can_download = true;
}

if (!$can_download) {
    die('You do not have permission to download this file');
}

// Check if file exists
$file_path = '../' . $file['file_path'];
if (!file_exists($file_path)) {
    die('File not found on server');
}

// Set headers for download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file['original_name'] . '"');
header('Content-Length: ' . filesize($file_path));
header('Cache-Control: must-revalidate');
header('Pragma: public');

// Output file
readfile($file_path);

// Log download (optional)
try {
    $stmt = $pdo->prepare("
        INSERT INTO download_logs (file_id, downloader_type, downloader_id, download_time) 
        VALUES (?, ?, ?, NOW())
    ");
    // This would require creating a download_logs table, but it's optional
    // $stmt->execute([$file_id, $user_role, $user_info['id']]);
} catch (Exception $e) {
    // Ignore logging errors
}

exit();
?>