<?php
// POST /api/meetings/upload.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user      = requireAuth();
$db        = getDB();
$meetingId = (int)post('meeting_id', 0);
$fileType  = post('file_type', 'document'); // document|image|recording

if (!$meetingId) apiError('Meeting ID required.', 422);
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) apiError('Upload failed.', 422);

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

$origName = $_FILES['file']['name'];
$mimeType = mime_content_type($_FILES['file']['tmp_name']);
$size     = $_FILES['file']['size'];
$ext      = strtolower(pathinfo($origName, PATHINFO_EXTENSION));

// Determine file type from mime if not provided
if ($fileType === 'document') {
    if (str_starts_with($mimeType, 'image/'))    $fileType = 'image';
    elseif (str_starts_with($mimeType, 'audio/') || str_starts_with($mimeType, 'video/')) $fileType = 'recording';
}

$maxSize = 50 * 1024 * 1024; // 50MB
if ($size > $maxSize) apiError('File too large (max 50MB).', 422);

$filename = sprintf('mtg_%d_%s_%s.%s', $meetingId, $fileType, uniqid(), $ext);
$dest     = $uploadDir . $filename;

if (!move_uploaded_file($_FILES['file']['tmp_name'], $dest)) apiError('Failed to save file.', 500);

$db->prepare("
    INSERT INTO meeting_files (meeting_id, user_id, filename, original_name, file_size, mime_type, file_type)
    VALUES (?, ?, ?, ?, ?, ?, ?)
")->execute([$meetingId, $user['id'], $filename, $origName, $size, $mimeType, $fileType]);

$fileId = (int)$db->lastInsertId();
apiSuccess([
    'id'            => $fileId,
    'filename'      => $filename,
    'original_name' => $origName,
    'file_type'     => $fileType,
    'mime_type'     => $mimeType,
    'file_size'     => $size,
    'uploaded_by_name' => $user['full_name'],
], 'File uploaded.');