<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../../includes/functions.php';

header('Content-Type: application/json');

// Allow local video playback in CSP
header('Content-Security-Policy: default-src \'self\'; media-src \'self\' \'unsafe-inline\' data: blob:;');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

requireAnyRole(['instructor', 'admin']);

$videoTypes = ['mp4', 'webm', 'ogg', 'mov', 'avi', 'wmv'];
$maxVideoSize = 500 * 1024 * 1024;

if (!isset($_FILES['video_file'])) {
    echo json_encode(['success' => false, 'message' => 'No file uploaded']);
    exit;
}

$file = $_FILES['video_file'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'Upload error code: ' . $file['error']]);
    exit;
}

if ($file['size'] > $maxVideoSize) {
    echo json_encode(['success' => false, 'message' => 'File too large. Max 500MB']);
    exit;
}

$fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($fileExtension, $videoTypes)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file type']);
    exit;
}

$uploadDir = '../../uploads/video/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$newFilename = time() . '_' . bin2hex(random_bytes(8)) . '.' . $fileExtension;
$targetPath = $uploadDir . $newFilename;

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    $videoUrl = 'uploads/video/' . $newFilename;
    echo json_encode([
        'success' => true, 
        'message' => 'Video uploaded successfully', 
        'video_path' => $videoUrl,
        'video_url' => $videoUrl
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save file']);
}