<?php
header('Content-Type: application/json');
require_once '../db/config.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Please login first']);
    exit;
}

$user_id = $_SESSION['user_id'];
$data = json_decode(file_get_contents('php://input'), true);

$symbol = $data['symbol'] ?? '';
$amount = (float)($data['amount'] ?? 0);
$direction = $data['direction'] ?? '';
$duration = (int)($data['duration'] ?? 60);
$opening_price = (float)($data['opening_price'] ?? 0);

// Updated Validate duration and profit rates as per user request
// 60s/8%、90s/12%、120s/15%、180s/20%、300s/32%
$valid_durations = [
    60 => ['profit' => 0.08, 'min' => 100],
    90 => ['profit' => 0.12, 'min' => 5000],
    120 => ['profit' => 0.15, 'min' => 30000],
    180 => ['profit' => 0.20, 'min' => 100000],
    300 => ['profit' => 0.32, 'min' => 300000],
];

if (!isset($valid_durations[$duration])) {
    echo json_encode(['success' => false, 'error' => 'Invalid duration']);
    exit;
}

$profit_rate = $valid_durations[$duration]['profit'];
$min_amount = $valid_durations[$duration]['min'];

if ($amount < $min_amount) {
    echo json_encode(['success' => false, 'error' => "Minimum amount for {$duration}S is {$min_amount} USDT"]);
    exit;
}

$db = db();
$db->beginTransaction();

try {
    $stmt = $db->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
    
    if (!$user || $user['balance'] < $amount) {
        throw new Exception('Insufficient balance');
    }

    $new_balance = $user['balance'] - $amount;
    $db->prepare("UPDATE users SET balance = ? WHERE id = ?")->execute([$new_balance, $user_id]);

    $settle_at = date('Y-m-d H:i:s', time() + $duration);

    $stmt = $db->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]);

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