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

if (!isset($_SESSION['user_id'])) {
    echo json_encode([]); // Return empty array if not logged in
    exit;
}

$user_id = $_SESSION['user_id'];
$status_filter = $_GET['status'] ?? 'pending';

if (!in_array($status_filter, ['pending', 'completed'])) {
    $status_filter = 'pending';
}

$pdo = db();

// --- Settlement Logic for Due Orders ---
try {
    $now = date('Y-m-d H:i:s');
    // Fetch orders that are pending and due for settlement
    $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(PDO::FETCH_ASSOC);

    if (count($due_orders) > 0) {
        $pdo->beginTransaction();

        foreach ($due_orders as $order) {
            $result = 'loss'; 

            $final_control = $order['win_loss_control'];

            if ($final_control == 'win') {
                $result = 'win';
            } elseif ($final_control == 'loss') {
                $result = 'loss';
            } else { 
                $result = (rand(0, 100) < 51) ? 'loss' : 'win'; 
            }
            
            $profit = 0;
            if ($result === 'win') {
                $profit = $order['amount'] * $order['profit_rate'];
                $total_return = $order['amount'] + $profit;

                $bal_stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $bal_stmt->execute([$total_return, $order['user_id']]);
            } else {
                $profit = -$order['amount'];
            }

            $price_variation = (float)($order['opening_price'] * 0.0001 * rand(1, 5));
            if (($order['direction'] === 'up' && $result === 'win') || ($order['direction'] === 'down' && $result === 'loss')) {
                $closing_price = $order['opening_price'] + $price_variation;
            } else {
                $closing_price = $order['opening_price'] - $price_variation;
            }

            $update_stmt = $pdo->prepare(
                "UPDATE option_orders SET status = 'completed', result = ?, profit = ?, closing_price = ? WHERE id = ?"
            );
            $update_stmt->execute([$result, $profit, $closing_price, $order['id']]);
        }
        $pdo->commit();
    }
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("Option settlement failed: " . $e->getMessage());
}

// --- Fetch and Return Orders for Frontend ---
$stmt = $pdo->prepare("SELECT * FROM option_orders WHERE user_id = ? AND status = ? ORDER BY created_at DESC LIMIT 50");
$stmt->execute([$user_id, $status_filter]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($orders);
?>