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

requireLogin();
$db = Database::getInstance();
$user = getCurrentUser();
$userId = (int)($user['id'] ?? 0);

$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;
}

$uploadsRoot = realpath(__DIR__ . '/../uploads');
if ($uploadsRoot === false || strpos($fullPath, $uploadsRoot) !== 0) {
    http_response_code(403);
    echo 'Access denied.';
    exit;
}

$hasAccess = false;
if (hasRole('super_admin') || hasRole('admin') || hasRole('regional_admin')) {
    $hasAccess = true;
}

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

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

        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/')) {
    if (preg_match('~^uploads/communities/(\d+)/~', $path, $m)) {
        $communityId = (int)$m[1];

        $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';
}

$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$isPdf = $mime === 'application/pdf' || $ext === 'pdf';
$isImage = str_starts_with($mime, 'image/');
$isVideo = str_starts_with($mime, 'video/');

$pageTitle = 'Resource Viewer';
include __DIR__ . '/includes/header.php';
?>

<div class="card">
  <div class="card-header d-flex justify-content-between align-items-center">
    <h5 class="mb-0">Resource</h5>
    <small class="text-muted"><?php echo htmlspecialchars(basename($path)); ?></small>
  </div>
  <div class="card-body">
    <div class="mb-3 text-muted small">
      This content is view-only. Downloading and copying are restricted as much as technically possible.
    </div>

    <?php if ($isPdf): ?>
      <div class="ratio ratio-4x3 border">
        <iframe
          src="<?php echo APP_URL; ?>/lms/file_view.php?path=<?php echo urlencode($path); ?>#toolbar=0&navpanes=0&scrollbar=0"
          style="border:0;"
          class="resource-viewer-frame"
        ></iframe>
      </div>
    <?php elseif ($isImage): ?>
      <div class="text-center">
        <img src="<?php echo APP_URL; ?>/lms/file_view.php?path=<?php echo urlencode($path); ?>" class="img-fluid user-select-none" oncontextmenu="return false;">
      </div>
    <?php elseif ($isVideo): ?>
      <video
        src="<?php echo APP_URL; ?>/lms/file_view.php?path=<?php echo urlencode($path); ?>"
        controls
        controlsList="nodownload noplaybackrate"
        style="width:100%;"
        oncontextmenu="return false;"
      ></video>
    <?php else: ?>
      <p class="text-muted">
        This file type cannot be displayed inside the browser in view-only mode.
        Please contact your instructor or admin if you need access.
      </p>
    <?php endif; ?>
  </div>
</div>

<script>
  (function () {
    document.addEventListener('contextmenu', function (e) {
      if (e.target.closest('.resource-viewer-frame') || e.target.closest('img') || e.target.closest('video')) {
        e.preventDefault();
      }
    });
    document.addEventListener('keydown', function (e) {
      if ((e.ctrlKey || e.metaKey) && (e.key === 's' || e.key === 'p' || e.key === 'u')) {
        e.preventDefault();
      }
    });
  })();
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
