<?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');
// Fetch orders that are pending and due, joined with user win_loss_control
$stmt = $pdo->prepare("SELECT o.*, u.win_loss_control as user_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: Order-level control overrides User-level control
    $final_control = 'none';
    if ($order['control'] !== 'none') {
        $final_control = $order['control'];
    } elseif ($order['user_control'] !== 'none') {
        $final_control = $order['user_control'];
    }

    if ($final_control === 'win') {
        $result = 'win';
    } elseif ($final_control === 'loss') {
        $result = 'loss';
    } else {
        // Default behavior if no control is set: 50/50 chance
        $result = (rand(0, 100) > 50) ? 'win' : 'loss';
    }

    if ($result === 'win') {
        $profit = $order['amount'] * $order['profit_rate'];
        $total_return = $order['amount'] + $profit;
        
        // Add balance to user
        $stmt_bal = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
        $stmt_bal->execute([$total_return, $order['user_id']]);
        
        // Set closing price slightly higher or lower than opening price to match result
        $variation = (float)($order['opening_price'] * 0.0001 * rand(1, 10));
        $closing_price = ($order['direction'] === 'up') ? $order['opening_price'] + $variation : $order['opening_price'] - $variation;
    } else {
        $profit = -$order['amount'];
        $variation = (float)($order['opening_price'] * 0.0001 * rand(1, 10));
        $closing_price = ($order['direction'] === 'up') ? $order['opening_price'] - $variation : $order['opening_price'] + $variation;
    }

    $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 current orders for the user to return to frontend
$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]);