<?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;
$identifier = isset($_POST['identifier']) ? preg_replace('/[^A-Za-z0-9_-]/', '', $_POST['identifier']) : null;
$chunk_index = isset($_POST['chunk_index']) ? (int)$_POST['chunk_index'] : 0;
$total_chunks = isset($_POST['total_chunks']) ? (int)$_POST['total_chunks'] : 0;
$originalName = isset($_POST['filename']) ? preg_replace('/[^A-Za-z0-9._-]/', '_', basename($_POST['filename'])) : null;
$contentType = $_POST['type'] ?? 'assignment';

if (!$course_id || !$identifier || !$originalName || $total_chunks <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing parameters']);
    exit;
}

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

$chunkTmp = $_FILES['chunk']['tmp_name'];
$chunkSize = (int)$_FILES['chunk']['size'];

// Ensure temp dir
$tmpDir = __DIR__ . '/../../uploads/tmp/' . $identifier;
if (!is_dir($tmpDir)) mkdir($tmpDir, 0755, true);
$chunkFile = $tmpDir . DIRECTORY_SEPARATOR . 'chunk_' . $chunk_index;
if (!move_uploaded_file($chunkTmp, $chunkFile)) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to move chunk']);
    exit;
}

// Check if all chunks are present
$uploaded = glob($tmpDir . DIRECTORY_SEPARATOR . 'chunk_*');
if (count($uploaded) == $total_chunks) {
    // assemble
    $finalName = time() . '_' . $originalName;
    $uploadDir = __DIR__ . '/../../uploads/courses/' . (int)$course_id . '/lessons';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
    $finalPath = $uploadDir . DIRECTORY_SEPARATOR . $finalName;

    $out = fopen($finalPath, 'ab');
    for ($i = 0; $i < $total_chunks; $i++) {
        $part = $tmpDir . DIRECTORY_SEPARATOR . 'chunk_' . $i;
        if (!file_exists($part)) {
            fclose($out);
            http_response_code(500);
            echo json_encode(['error' => 'Missing chunk ' . $i]);
            exit;
        }
        $in = fopen($part, 'rb');
        stream_copy_to_stream($in, $out);
        fclose($in);
    }
    fclose($out);

    // cleanup chunks
    array_map('unlink', glob($tmpDir . DIRECTORY_SEPARATOR . 'chunk_*'));
    @rmdir($tmpDir);

    // Validate assembled file (mime, size)
    $size = filesize($finalPath);
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $finalPath);
    finfo_close($finfo);

    $max = MEDIA_MAX_SIZE[$contentType] ?? (50 * 1024 * 1024);
    if ($size > $max) {
        unlink($finalPath);
        http_response_code(413);
        echo json_encode(['error' => 'Assembled file exceeds maximum allowed size']);
        exit;
    }
    if (!in_array($mime, MEDIA_ALLOWED[$contentType] ?? [])) {
        unlink($finalPath);
        http_response_code(415);
        echo json_encode(['error' => 'Unsupported assembled file type', 'detected_mime' => $mime]);
        exit;
    }

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

    $webPath = 'uploads/courses/' . (int)$course_id . '/lessons/' . $finalName;

    $db = Database::getInstance();
    $db->query("INSERT INTO course_media (course_id, lesson_id, file_path, mime, size, thumbnail_path) VALUES (?, ?, ?, ?, ?, ?)", [ $course_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;
}

// chunk accepted
echo json_encode(['success' => true, 'chunk_index' => $chunk_index]);
exit;
