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

$response = ['success' => false, 'error' => 'An unknown error occurred.'];

if (isset($_FILES['file'])) {
    $file = $_FILES['file'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $response['error'] = 'File upload error: ' . $file['error'];
    } else {
        $fileExt = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $fileMime = mime_content_type($file['tmp_name']);

        $targetDir = '';
        $allowedTypes = [];
        $maxSize = 0;
        $prefix = '';

        // Determine settings based on file type
        if (strpos($fileMime, 'image/') === 0) {
            $targetDir = 'assets/uploads/images/';
            $allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            $maxSize = 5 * 1024 * 1024; // 5 MB
            $prefix = 'img_';
        } elseif (strpos($fileMime, 'video/') === 0) {
            $targetDir = 'assets/uploads/videos/';
            $allowedTypes = ['mp4', 'webm', 'mov', 'ogv'];
            $maxSize = 50 * 1024 * 1024; // 50 MB
            $prefix = 'vid_';
        } else {
            $response['error'] = 'Unsupported file type: ' . $fileMime;
        }

        if ($targetDir) {
            if (!is_dir($targetDir)) {
                mkdir($targetDir, 0775, true);
            }

            if (!in_array($fileExt, $allowedTypes)) {
                $response['error'] = 'Invalid file extension. Allowed: ' . implode(', ', $allowedTypes);
            } elseif ($file['size'] > $maxSize) {
                $response['error'] = 'File is too large. Maximum size is ' . ($maxSize / 1024 / 1024) . ' MB.';
            } else {
                $fileName = preg_replace("/[^a-zA-Z0-9-_\.]/", "", basename($file['name']));
                $uniqueName = $prefix . uniqid('', true) . '.' . $fileExt;
                $targetPath = $targetDir . $uniqueName;

                if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                    $response = [
                        'success' => true,
                        'filePath' => $targetPath
                    ];
                } else {
                    $response['error'] = 'Failed to move uploaded file.';
                }
            }
        }
    }
} else {
    $response['error'] = 'No file uploaded.';
}

echo json_encode($response);
?>