<?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;
}

$status = $_GET['status'] ?? 'pending';
$pdo = db();

// Auto-settle orders that are due
$now = date('Y-m-d H:i:s');
$stmt = $pdo->prepare("SELECT o.*, u.win_loss_control FROM option_orders o JOIN users u ON o.user_id = u.id WHERE o.status = 'pending' AND o.settle_at <= ?");
$stmt->execute([$now]);
$due_orders = $stmt->fetchAll();

foreach ($due_orders as $order) {
    $result = 'loss';
    $profit = 0;
    
    // Win/Loss Control Logic
    if ($order['win_loss_control'] === 'win') {
        $result = 'win';
    } elseif ($order['win_loss_control'] === 'loss') {
        $result = 'loss';
    } else {
        // Normal: Random or could be based on real price. 
        // For simplicity in these "second contract" systems, it's often slightly biased or random if not controlled.
        // Let's do 50/50 for "none" control.
        $result = (rand(0, 100) > 50) ? 'win' : 'loss';
    }

    if ($result === 'win') {
        $profit = $order['amount'] * $order['profit_rate'];
        $total_return = $order['amount'] + $profit;
        
        // Add balance
        $stmt_bal = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
        $stmt_bal->execute([$total_return, $order['user_id']]);
        
        // Update closing price slightly higher or lower based on direction
        $closing_price = ($order['direction'] === 'up') ? $order['opening_price'] * 1.001 : $order['opening_price'] * 0.999;
    } else {
        $profit = -$order['amount'];
        $closing_price = ($order['direction'] === 'up') ? $order['opening_price'] * 0.999 : $order['opening_price'] * 1.001;
    }

    $stmt_update = $pdo->prepare("UPDATE option_orders SET status = 'completed', result = ?, profit = ?, closing_price = ? WHERE id = ?");
    $stmt_update->execute([$result, $profit, $closing_price, $order['id']]);
}

// Fetch orders
$stmt = $pdo->prepare("SELECT * FROM option_orders WHERE user_id = ? AND status = ? ORDER BY created_at DESC");
$stmt->execute([$user_id, $status]);
$orders = $stmt->fetchAll();

echo json_encode(['success' => true, 'data' => $orders]);
