<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$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 ending_config (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        config_key TEXT UNIQUE NOT NULL,
        config_value TEXT NOT NULL,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");

    $method = $_SERVER['REQUEST_METHOD'];

    if ($method === 'GET') {
        $stmt = $pdo->query("SELECT config_key, config_value FROM ending_config");
        $config = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $config[$row['config_key']] = $row['config_value'];
        }
        $defaultConfig = [
            'text' => '感谢各位来宾的光临，祝新人新婚快乐，永结同心！',
            'studio' => '礼典世家婚礼策划',
            'date' => '',
            'animation' => 'fade',
            'duration' => '30',
            'bgMusic' => '',
            'autoTrigger' => '1'
        ];
        $result = array_merge($defaultConfig, $config);
        echo json_encode(['success' => true, 'data' => $result]);
    } elseif ($method === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) {
            echo json_encode(['success' => false, 'message' => 'Invalid JSON']);
            exit;
        }
        foreach ($data as $key => $value) {
            $stmt = $pdo->prepare("INSERT OR REPLACE INTO ending_config (config_key, config_value) VALUES (:key, :value)");
            $stmt->execute([':key' => $key, ':value' => $value]);
        }
        echo json_encode(['success' => true, 'message' => '配置保存成功']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>