<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

$maxFileSize = 50 * 1024 * 1024;
$allowedExtensions = array('mp3', 'wav', 'ogg', 'm4a');

$uploadDir = dirname(__DIR__) . '/audio/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

function sendResponse($success, $message, $data = null) {
    $response = array(
        'success' => $success,
        'message' => $message
    );
    if ($data !== null) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    sendResponse(true, 'Preflight OK');
}

if (!isset($_FILES['audio'])) {
    sendResponse(false, '请选择要上传的音频文件');
}

$file = $_FILES['audio'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    sendResponse(false, '上传失败，错误码: ' . $file['error']);
}

if ($file['size'] > $maxFileSize) {
    sendResponse(false, '文件大小超过限制（最大50MB）');
}

$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($extension, $allowedExtensions)) {
    sendResponse(false, '不支持的文件格式，请上传MP3、WAV、OGG或M4A格式');
}

$fileName = 'bgm_' . date('YmdHis') . '_' . uniqid() . '.' . $extension;
$storagePath = 'audio/' . $fileName;
$destination = $uploadDir . $fileName;

if (!move_uploaded_file($file['tmp_name'], $destination)) {
    sendResponse(false, '文件保存失败');
}

$dbPath = __DIR__ . '/../wedding_data.db';
try {
    $pdo = new PDO("sqlite:$dbPath");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS audio_assets (
        audio_id TEXT PRIMARY KEY,
        audio_name TEXT NOT NULL,
        audio_type TEXT DEFAULT 'bgm',
        storage_path TEXT NOT NULL,
        file_name TEXT NOT NULL,
        file_size INTEGER DEFAULT 0,
        format TEXT DEFAULT '',
        is_active INTEGER DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    
    $audioId = 'audio_' . uniqid();
    $stmt = $pdo->prepare("INSERT INTO audio_assets (audio_id, audio_name, audio_type, storage_path, file_name, file_size, format) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$audioId, $_POST['audio_name'] ?? '背景音乐', 'bgm', $storagePath, $fileName, $file['size'], $extension]);
    
    sendResponse(true, '上传成功', [
        'audio_id' => $audioId,
        'storage_path' => $storagePath,
        'file_name' => $fileName
    ]);
} catch (PDOException $e) {
    sendResponse(false, '数据库保存失败: ' . $e->getMessage());
}
?>