<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
$db = Database::getInstance();
$user = getCurrentUser();

$rawPath = $_GET['path'] ?? '';
$rawPath = str_replace(['\\'], ['/' ], $rawPath);
$path = ltrim($rawPath, '/');

if ($path === '' || (!str_starts_with($path, 'uploads/courses/') && !str_starts_with($path, 'uploads/communities/'))) {
    http_response_code(400);
    echo 'Invalid file path.';
    exit;
}

$fullPath = realpath(__DIR__ . '/../' . $path);
if ($fullPath === false || !is_file($fullPath)) {
    http_response_code(404);
    echo 'File not found.';
    exit;
}

// Security: ensure resolved path is still under project uploads
$uploadsRoot = realpath(__DIR__ . '/../uploads');
if ($uploadsRoot === false || strpos($fullPath, $uploadsRoot) !== 0) {
    http_response_code(403);
    echo 'Access denied.';
    exit;
}

$userId = (int)($user['id'] ?? 0);
$hasAccess = false;

// Admin-like roles always allowed
if (hasRole('super_admin') || hasRole('admin') || hasRole('regional_admin')) {
    $hasAccess = true;
}

if (!$hasAccess && str_starts_with($path, 'uploads/courses/')) {
    // Extract course_id from path: uploads/courses/{course_id}/...
    if (preg_match('~^uploads/courses/(\d+)/~', $path, $m)) {
        $courseId = (int)$m[1];

        // Instructors who own the course
        if (hasRole('instructor')) {
            $course = $db->get('SELECT instructor_id FROM courses WHERE id = ?', [$courseId]);
            if ($course && (int)$course['instructor_id'] === $userId) {
                $hasAccess = true;
            }
        }

        // Active enrolled students
        if (!$hasAccess && isset($_SESSION['role']) && $_SESSION['role'] === 'student') {
            $enrollment = $db->get('SELECT id FROM course_enrollments WHERE course_id = ? AND student_id = ? AND status = ? LIMIT 1', [$courseId, $userId, 'active']);
            if ($enrollment) {
                $hasAccess = true;
            }
        }
    }
}

if (!$hasAccess && str_starts_with($path, 'uploads/communities/')) {
    // Extract community_id from path: uploads/communities/{community_id}/...
    if (preg_match('~^uploads/communities/(\d+)/~', $path, $m)) {
        $communityId = (int)$m[1];

        // Check active membership
        $member = $db->get('SELECT id FROM community_members WHERE community_id = ? AND user_id = ? AND status = ? LIMIT 1', [$communityId, $userId, 'active']);
        if ($member) {
            $hasAccess = true;
        }
    }
}

if (!$hasAccess) {
    http_response_code(403);
    echo 'You do not have permission to view this file.';
    exit;
}

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = $finfo ? finfo_file($finfo, $fullPath) : null;
if ($finfo) {
    finfo_close($finfo);
}
if (!$mime) {
    $mime = 'application/octet-stream';
}

header('Content-Type: ' . $mime);
header('Content-Disposition: inline; filename="' . basename($fullPath) . '"');
header('Content-Length: ' . filesize($fullPath));

$fh = fopen($fullPath, 'rb');
if ($fh) {
    while (!feof($fh)) {
        echo fread($fh, 8192);
    }
    fclose($fh);
}
exit;
