<?php
session_start();
require_once '../db/config.php';

header('Content-Type: application/json');

$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    echo json_encode(['success' => false, 'error' => '未登录']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$symbol = $data['symbol'] ?? '';
$amount = floatval($data['amount'] ?? 0);
$direction = $data['direction'] ?? '';
$duration = intval($data['duration'] ?? 0);
$profit_rate = floatval($data['profit_rate'] ?? 0);
$opening_price = floatval($data['opening_price'] ?? 0);

if (!$symbol || $amount <= 0 || !in_array($direction, ['up', 'down']) || !in_array($duration, [60, 90, 120, 180, 300])) {
    echo json_encode(['success' => false, 'error' => '参数错误']);
    exit;
}

$pdo = db();
try {
    $pdo->beginTransaction();

    // Check balance
    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
    
    if (!$user || $user['balance'] < $amount) {
        throw new Exception('余额不足');
    }

    // Deduct balance
    $stmt = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
    $stmt->execute([$amount, $user_id]);

    // Create order
    $settle_at = date('Y-m-d H:i:s', time() + $duration);
    $stmt = $pdo->prepare("INSERT INTO option_orders (user_id, symbol, amount, direction, duration, profit_rate, opening_price, status, settle_at) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)");
    $stmt->execute([$user_id, $symbol, $amount, $direction, $duration, $profit_rate, $opening_price, $settle_at]);

    $pdo->commit();
    echo json_encode(['success' => true, 'new_balance' => $user['balance'] - $amount]);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
