<?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; charset=utf-8');

// 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 = dirname(__DIR__, 2) . '/videos/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$safeBaseName = preg_replace('/[^A-Za-z0-9._-]/', '_', pathinfo($file['name'], PATHINFO_FILENAME));
$newFilename = $safeBaseName . '_' . time() . '.' . $fileExtension;
$targetPath = $uploadDir . $newFilename;

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $videoUrl = $protocol . '://' . $host . BASE_URL . 'videos/' . $newFilename;

    if (ob_get_length()) {
        ob_clean();
    }

    echo json_encode([
        'success' => true,
        'message' => 'Video uploaded successfully',
        'video_path' => $videoUrl,
        'video_url' => $videoUrl
    ], JSON_UNESCAPED_SLASHES);
    exit;
} else {
    if (ob_get_length()) {
        ob_clean();
    }

    echo json_encode(['success' => false, 'message' => 'Failed to save file'], JSON_UNESCAPED_SLASHES);
    exit;
}