<?php
session_start();
header('Content-Type: application/json');
ini_set('display_errors', 1);
error_reporting(E_ALL); // Recommended for debugging
date_default_timezone_set('Asia/Kolkata');
// Ensure user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit;
}

// Allowed extensions and MIME types
$allowedExtensions = ['mp4', 'mov', 'avi', 'wmv', 'mkv'];
$allowedMimes = [
    'video/mp4',            // .mp4
    'video/quicktime',      // .mov
    'video/x-msvideo',      // .avi
    'video/x-ms-wmv',       // .wmv
    'video/x-matroska'      // .mkv
];

// Upload directory
$uploadDir = __DIR__ . '/uploads/videos/';
if (!is_dir($uploadDir) && !mkdir($uploadDir, 0777, true)) {
    echo json_encode(['success' => false, 'message' => 'Failed to create upload directory.']);
    exit;
}
if (!is_writable($uploadDir)) {
    echo json_encode(['success' => false, 'message' => 'Upload directory is not writable.']);
    exit;
}

// Validate uploaded file
if (!isset($_FILES['video']) || $_FILES['video']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode([
        'success'    => false,
        'message'    => 'No video uploaded or an upload error occurred.',
        'error_code' => $_FILES['video']['error'] ?? null
    ]);
    exit;
}

$fileTmp       = $_FILES['video']['tmp_name'];
$fileName      = basename($_FILES['video']['name']);
$fileSize      = $_FILES['video']['size'];
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

// Check extension
if (!in_array($fileExtension, $allowedExtensions)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file extension.']);
    exit;
}

// Get MIME type
if (function_exists('finfo_open')) {
    $finfo    = finfo_open(FILEINFO_MIME_TYPE);
    $fileType = finfo_file($finfo, $fileTmp);
    finfo_close($finfo);
} else {
    $fileType = $_FILES['video']['type']; // fallback
}

// Check MIME type
if (!in_array($fileType, $allowedMimes)) {
    echo json_encode(['success' => false, 'message' => 'Invalid video format. Allowed types: MP4, MOV, AVI, WMV, MKV.']);
    exit;
}

// File size check (100MB max)
if ($fileSize > 100 * 1024 * 1024) {
    echo json_encode(['success' => false, 'message' => 'Video size exceeds 100MB limit.']);
    exit;
}

// Generate unique filename
$userId    = $_SESSION['user_id'];
$timestamp = time();
$safeName  = $userId . '_' . $timestamp . '.' . $fileExtension;
$destination = $uploadDir . $safeName;

// Move file
if (!move_uploaded_file($fileTmp, $destination)) {
    echo json_encode(['success' => false, 'message' => 'Failed to move uploaded video.']);
    exit;
}

// Success
echo json_encode([
    'success'  => true,
    'message'  => 'Video uploaded successfully!',
    'filename' => $safeName
]);
?>
