<?php
require_once '../includes/config.php';
require_once '../includes/auth.php';

// Check if file parameter exists
if (!isset($_GET['file'])) {
    http_response_code(400);
    die('File parameter missing');
}

$file_path = '../' . urldecode($_GET['file']);

// Validate file exists and is within allowed directories
$allowed_dirs = [
    'uploads/students/',
    'uploads/documents/',
    'uploads/universities/'
];

$valid_file = false;
foreach ($allowed_dirs as $dir) {
    if (strpos($file_path, $dir) !== false) {
        $valid_file = true;
        break;
    }
}

if (!$valid_file || !file_exists($file_path)) {
    http_response_code(404);
    die('File not found');
}

// Check authorization
if (!isLoggedIn()) {
    http_response_code(403);
    die('Access denied');
}

// For student documents, verify ownership
if (strpos($file_path, 'uploads/students/') !== false) {
    $student_id = $_SESSION['user_id'];
    
    // Extract student ID from path (format: uploads/students/[id]/filename)
    $path_parts = explode('/', $file_path);
    $file_student_id = $path_parts[3];
    
    if ($_SESSION['user_type'] === 'student' && $file_student_id != $student_id) {
        http_response_code(403);
        die('Access denied');
    }
    
    // For counselors/admins, verify they have access to this student
    if (($_SESSION['user_type'] === 'counselor' || $_SESSION['user_type'] === 'admin') {
        $stmt = $pdo->prepare("SELECT id FROM students WHERE id = ? AND (assigned_counselor_id = ? OR ? = 'admin')");
        $stmt->execute([$file_student_id, $_SESSION['user_id'], $_SESSION['user_type']]);
        
        if (!$stmt->fetch()) {
            http_response_code(403);
            die('Access denied');
        }
    }
}

// Get file info
$file_name = basename($file_path);
$file_size = filesize($file_path);
$mime_type = mime_content_type($file_path);

// Send file
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . $file_size);
readfile($file_path);
exit();
?>