<?php
require_once __DIR__ . '/config.php';
$me = must_auth();
if ($_SERVER['REQUEST_METHOD']!=='POST') fail('POST only',405);
if (empty($_FILES['file'])) fail('No file');
$f = $_FILES['file'];
if ($f['size'] > MAX_MB*1024*1024) fail('File too large (max '.MAX_MB.'MB)');
if ($f['error'] !== UPLOAD_ERR_OK)  fail('Upload error code: '.$f['error']);
$mime    = mime_content_type($f['tmp_name']);
$allowed = array(
    'image/jpeg','image/png','image/gif','image/webp',
    'video/mp4','video/webm',
    'audio/mpeg','audio/ogg','audio/webm','audio/wav',
    'application/pdf','application/zip','application/x-zip-compressed','text/plain',
    'application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document'
);
if (!in_array($mime,$allowed)) fail('File type not allowed: '.$mime);
$sub = strpos($mime,'image')===0?'images':(strpos($mime,'video')===0?'videos':(strpos($mime,'audio')===0?'audio':'documents'));
$ext = strtolower(pathinfo($f['name'],PATHINFO_EXTENSION));
$ext = preg_replace('/[^a-z0-9]/', '', $ext);
if ($ext === '') $ext = 'bin';
$nm  = bin2hex(random_bytes(10)).'.'.$ext;
$dir = UP_DIR.$sub.'/';
if (!is_dir($dir)) mkdir($dir,0777,true);
if (!move_uploaded_file($f['tmp_name'],$dir.$nm)) fail('Could not save file');
$type = strpos($mime,'image')===0?'image':(strpos($mime,'video')===0?'video':(strpos($mime,'audio')===0?'audio':'document'));
ok(array('url'=>UP_URL.$sub.'/'.$nm,'type'=>$type,'mime'=>$mime,'name'=>$f['name'],'size'=>$f['size']));
