<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/media.php';
requireLogin();
$user = getCurrentUser();
header('Content-Type: application/json');

if (!hasRole('instructor') && !hasPermission('can_create_courses')) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$course_id = isset($_POST['course_id']) ? (int)$_POST['course_id'] : 0;
$lesson_id = isset($_POST['lesson_id']) ? (int)$_POST['lesson_id'] : null;
if (!$course_id) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing course_id']);
    exit;
}

if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['error' => 'No file uploaded or upload error']);
    exit;
}

$file = $_FILES['file'];
$tmp = $file['tmp_name'];
$size = (int)$file['size'];
$originalName = preg_replace('/[^A-Za-z0-9._-]/', '_', basename($file['name']));

// Determine content type mapping by provided `type` POST param or infer
$contentType = $_POST['type'] ?? 'assignment';
if (!in_array($contentType, array_keys(MEDIA_ALLOWED))) {
    $contentType = 'assignment';
}

// size check
$max = MEDIA_MAX_SIZE[$contentType] ?? (50 * 1024 * 1024);
if ($size > $max) {
    http_response_code(413);
    echo json_encode(['error' => 'File exceeds maximum allowed size']);
    exit;
}

// MIME check
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $tmp);
finfo_close($finfo);
$allowed = MEDIA_ALLOWED[$contentType] ?? [];
if (!in_array($mime, $allowed)) {
    http_response_code(415);
    echo json_encode(['error' => 'Unsupported file type', 'detected_mime' => $mime]);
    exit;
}

// Move file into place
$uploadDir = __DIR__ . '/../../uploads/courses/' . (int)$course_id . '/lessons';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
$targetName = time() . '_' . $originalName;
$target = $uploadDir . DIRECTORY_SEPARATOR . $targetName;
if (!move_uploaded_file($tmp, $target)) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to move uploaded file']);
    exit;
}

// Try to generate thumbnail for videos (if ffmpeg present)
$thumbnailPath = null;
if ($contentType === 'video' && defined('FFMPEG_PATH') && is_executable(FFMPEG_PATH)) {
    $thumbName = pathinfo($targetName, PATHINFO_FILENAME) . '.jpg';
    $thumbTarget = $uploadDir . DIRECTORY_SEPARATOR . $thumbName;
    $cmd = escapeshellcmd(FFMPEG_PATH) . ' -y -ss 00:00:01 -i ' . escapeshellarg($target) . ' -frames:v 1 -q:v 2 ' . escapeshellarg($thumbTarget) . ' 2>&1';
    @shell_exec($cmd);
    if (file_exists($thumbTarget)) {
        $thumbnailPath = ltrim(str_replace(__DIR__ . '/../../', '', $thumbTarget), '/');
    }
}

$webPath = 'uploads/courses/' . (int)$course_id . '/lessons/' . $targetName;
$thumbnailWeb = $thumbnailPath ? $thumbnailPath : null;

// Insert metadata
$db = Database::getInstance();
$db->query("INSERT INTO course_media (course_id, lesson_id, file_path, mime, size, thumbnail_path) VALUES (?, ?, ?, ?, ?, ?)", [ $course_id, $lesson_id ?: null, $webPath, $mime, $size, $thumbnailWeb ]);
$mediaId = $db->getLastInsertId();

echo json_encode(['success' => true, 'media_id' => $mediaId, 'file_path' => $webPath, 'mime' => $mime, 'size' => $size, 'thumbnail' => $thumbnailWeb]);
exit;
