<?php
/**
 * Heritage Voice — upload.php
 * POST /api/upload.php?type=audio
 * POST /api/upload.php?type=image
 * Auth: Bearer token (admin role)
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';

cors();

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

$type = isset($_GET['type']) ? $_GET['type'] : 'audio';
$user = hv_get_user();

// Avatar: mọi user đăng nhập đều được upload
// Audio/image: cần editor trở lên
if ($type === 'avatar') {
    if (!$user) json_error('Unauthorized', 401);
} else {
    if (!$user || !in_array($user['role'], array('admin','superadmin','editor'))) {
        json_error('Unauthorized', 401);
    }
}

if ($type === 'audio') {
    $exts    = array('mp3','m4a','aac','ogg','wav');
    $maxSize = 50 * 1024 * 1024;
    $dir     = dirname(__DIR__) . '/audio/';
    $urlBase = 'https://tads.ctv.hanoi.vn/audio/';
} elseif ($type === 'avatar') {
    $exts    = array('jpg','jpeg','png','webp','');
    $maxSize = 5 * 1024 * 1024;
    $dir     = dirname(__DIR__) . '/images/avatars/';
    $urlBase = 'https://tads.ctv.hanoi.vn/images/avatars/';
} else {
    $exts    = array('jpg','jpeg','png','webp');
    $maxSize = 5 * 1024 * 1024;
    $dir     = dirname(__DIR__) . '/images/';
    $urlBase = 'https://tads.ctv.hanoi.vn/images/';
}

if (empty($_FILES['file'])) json_error('Không tìm thấy file');

$file = $_FILES['file'];
if ($file['error'] !== UPLOAD_ERR_OK) json_error('Lỗi upload: ' . $file['error']);
if ($file['size'] > $maxSize) json_error('File quá lớn. Tối đa ' . ($maxSize/1024/1024) . 'MB');

$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($type === 'avatar') {
    $ext = $ext ?: 'jpg'; // blob từ Cropper không có ext
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $newName = 'avatar_' . ($user['id'] ?? 'u') . '_' . time() . '.' . $ext;
} else {
    if (!in_array($ext, $exts)) json_error('Định dạng không hỗ trợ: ' . $ext);
    $site    = isset($_GET['site'])  ? preg_replace('/[^a-z0-9_-]/', '', $_GET['site'])  : 'hv';
    $point   = isset($_GET['point']) ? preg_replace('/[^a-z0-9_-]/', '', $_GET['point']) : '';
    $lang    = isset($_GET['lang'])  ? preg_replace('/[^a-z]/', '', $_GET['lang'])        : '';
    $prefix  = $lang ? $lang . '_' . ($point ?: $site) : ($point ? $site . '_' . $point : $site);
    $newName = $prefix . '_' . time() . '.' . $ext;
}

if (!is_dir($dir)) mkdir($dir, 0755, true);
if (!move_uploaded_file($file['tmp_name'], $dir . $newName)) json_error('Không thể lưu file. Kiểm tra quyền thư mục /audio/');

$duration = 0;
if ($type === 'audio') {
    $dur = @shell_exec("ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 " . escapeshellarg($dir . $newName) . " 2>/dev/null");
    if ($dur) $duration = (int) round((float) trim($dur));
}

json_ok([
    'url'          => $urlBase . $newName,
    'filename'     => $newName,
    'original'     => $file['name'],
    'size_human'   => round($file['size']/1024/1024, 2) . ' MB',
    'duration_sec' => $duration,
], 'Upload thành công');
