<?php
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../includes/lang.php';

header('Content-Type: application/json');
ini_set('display_errors', 0);
error_reporting(E_ALL);

$db = db();
$user_id = $_SESSION['user_id'] ?? null;

if (!$user_id) {
    echo json_encode(['success' => false, 'error' => __('unauthorized')]);
    exit;
}

// Check frozen status
$stmt = $db->prepare("SELECT status FROM users WHERE id = ?");
$stmt->execute([$user_id]);
if ($stmt->fetchColumn() === 'frozen') {
    echo json_encode(['success' => false, 'error' => __('account_frozen')]);
    exit;
}

$action = $_REQUEST['action'] ?? '';

if ($action === 'get_orders') {
    $tab = $_GET['tab'] ?? 'spot';
    $symbol = $_GET['symbol'] ?? 'BTC';
    
    $open = [];
    $settlement = [];
    
    if ($tab === 'binary') {
        // Auto-settle expired orders
        $stmt = $db->prepare("SELECT o.*, u.win_loss_control as user_control FROM binary_orders o JOIN users u ON o.user_id = u.id WHERE o.user_id = ? AND o.status = 'pending' AND DATE_ADD(o.created_at, INTERVAL o.duration SECOND) <= NOW()");
        $stmt->execute([$user_id]);
        $expired = $stmt->fetchAll();
        
        foreach ($expired as $o) {
            $order_id = $o['id'];
            $result = '';
            // Simple settlement if we missed the real-time event
            if ($o['control_status'] == 1 || $o['user_control'] == 1) $result = 'won';
            elseif ($o['control_status'] == 2 || $o['user_control'] == 2) $result = 'lost';
            else {
                // Natural result fallback
                $result = (rand(0, 100) > 50) ? 'won' : 'lost';
            }
            
            // Dummy close price
            $close_price = $o['entry_price'];
            if ($result === 'won') {
                $close_price = ($o['direction'] === 'up' || $o['direction'] === 'buy') ? $o['entry_price'] * 1.01 : $o['entry_price'] * 0.99;
            } else {
                $close_price = ($o['direction'] === 'up' || $o['direction'] === 'buy') ? $o['entry_price'] * 0.99 : $o['entry_price'] * 1.01;
            }

            $db->beginTransaction();
            try {
                $db->prepare("UPDATE binary_orders SET status = ?, close_price = ?, end_at = NOW() WHERE id = ?")->execute([$result, $close_price, $order_id]);
                if ($result === 'won') {
                    $win_amount = $o['amount'] + ($o['amount'] * $o['profit_rate'] / 100);
                    $db->prepare("UPDATE user_balances SET available = available + ? WHERE user_id = ? AND symbol = 'USDT'")->execute([$win_amount, $user_id]);
                    $db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status) VALUES (?, 'binary_win', ?, 'USDT', 'completed')")->execute([$user_id, $win_amount]);
                } else {
                    $db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status) VALUES (?, 'binary_loss', ?, 'USDT', 'completed')")->execute([$user_id, $o['amount']]);
                }
                $db->commit();
            } catch (Exception $e) {
                $db->rollBack();
            }
        }

        $stmt = $db->prepare("SELECT * FROM binary_orders WHERE user_id = ? ORDER BY created_at DESC");
        $stmt->execute([$user_id]);
        $orders = $stmt->fetchAll();
        foreach ($orders as $o) {
            $row = [
                'id' => $o['id'],
                'time' => $o['created_at'],
                'pair' => $o['symbol'] . '/USDT',
                'type' => __('trade_binary'),
                'type_raw' => 'binary',
                'side' => ($o['direction'] === 'up' || $o['direction'] === 'buy') ? __('buy_up') : __('buy_down'),
                'side_type' => ($o['direction'] === 'up' || $o['direction'] === 'buy') ? 'up' : 'down',
                'price' => $o['entry_price'],
                'amount' => $o['amount'],
                'pnl' => $o['status'] === 'won' ? (float)($o['amount'] * $o['profit_rate'] / 100) : ($o['status'] === 'lost' ? -(float)$o['amount'] : 0),
                'total' => $o['status'] === 'won' ? (float)($o['amount'] + ($o['amount'] * $o['profit_rate'] / 100)) : ($o['status'] === 'lost' ? 0.00 : '---'),
                'status' => ($o['status'] === 'won' ? __('won') : ($o['status'] === 'lost' ? __('loss') : __('executing'))),
                'status_type' => $o['status'] === 'pending' ? 'executing' : $o['status'],
                'profitRate' => $o['profit_rate']
            ];
            if ($o['status'] === 'pending') {
                $row['status'] = __('executing');
                $row['totalSeconds'] = $o['duration'];
                $elapsed = time() - strtotime($o['created_at']);
                $row['secondsLeft'] = max(0, $o['duration'] - $elapsed);
                if ($row['secondsLeft'] > 0) $open[] = $row;
                else $settlement[] = $row;
            } else {
                $settlement[] = $row;
            }
        }
    } elseif ($tab === 'spot') {
        $stmt = $db->prepare("SELECT * FROM spot_orders WHERE user_id = ? ORDER BY created_at DESC");
        $stmt->execute([$user_id]);
        $orders = $stmt->fetchAll();
        foreach ($orders as $o) {
            $row = [
                'id' => $o['id'],
                'time' => $o['created_at'],
                'pair' => $o['symbol'] . '/USDT',
                'type' => __('trade_spot'),
                'type_raw' => 'spot',
                'side' => $o['side'] === 'buy' ? __('buy') : __('sell'),
                'side_type' => $o['side'],
                'price' => $o['price'],
                'amount' => $o['amount'],
                'total' => ($o['price'] * $o['amount']),
                'status' => $o['status'] === 'filled' ? __(3) : __(0),
                'status_type' => $o['status']
            ];
            if ($o['status'] === 0) $open[] = $row;
            else $settlement[] = $row;
        }
    } elseif ($tab === 'contract') {
        $stmt = $db->prepare("SELECT * FROM contract_orders WHERE user_id = ? ORDER BY created_at DESC");
        $stmt->execute([$user_id]);
        $orders = $stmt->fetchAll();
        foreach ($orders as $o) {
            $row = [
                'id' => $o['id'],
                'time' => $o['created_at'],
                'pair' => $o['symbol'] . '/USDT',
                'type' => __('trade_contract'),
                'type_raw' => 'contract',
                'side' => $o['direction'] === 'long' ? __('long') : __('short'),
                'side_type' => $o['direction'] === 'long' ? 'up' : 'down',
                'price' => $o['entry_price'],
                'amount' => $o['amount'],
                'pnl' => $o['profit'],
                'total' => ($o['amount'] / $o['leverage']) + $o['profit'],
                'status' => $o['status'] === 'open' ? __('executing') : ($o['profit'] >= 0 ? __('won') : __('loss')),
                'status_type' => $o['status'] === 'open' ? 'executing' : ($o['profit'] >= 0 ? 'won' : 'loss')
            ];
            if ($o['status'] === 'open') $open[] = $row;
            else $settlement[] = $row;
        }
    }
    
    echo json_encode(['success' => true, 'open' => $open, 'settlement' => $settlement]);
    exit;
}

if ($action === 'recharge') {
    $amount = (float)$_POST['amount'];
    $symbol = $_POST['symbol'] ?? 'USDT';
    $method = $_POST['method'] ?? 'Crypto';
    $tx_hash = $_POST['tx_hash'] ?? '';
    $fiat_amount = isset($_POST['fiat_amount']) ? (float)$_POST['fiat_amount'] : null;
    $fiat_currency = $_POST['fiat_currency'] ?? null;
    
    if ($amount <= 0) {
        echo json_encode(['success' => false, 'error' => __('invalid_amount')]);
        exit;
    }
    
    try {
        $stmt = $db->prepare("INSERT INTO finance_requests (user_id, type, amount, symbol, payment_method, tx_hash, fiat_amount, fiat_currency, `status`, ip_address) VALUES (?, 'recharge', ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$user_id, round($amount, 8), $symbol, $method, $tx_hash, $fiat_amount, $fiat_currency, '0', getRealIP()]);
        
        echo json_encode(['success' => true, 'id' => $db->lastInsertId()]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'complete_transfer') {
    $order_id = $_POST['order_id'] ?? null;
    if (!$order_id) {
        echo json_encode(['success' => false, 'error' => 'Missing order ID']);
        exit;
    }
    
    $stmt = $db->prepare("UPDATE finance_requests SET status = 'finished' WHERE id = ? AND user_id = ?");
    $stmt->execute([$order_id, $user_id]);
    
    echo json_encode(['success' => true]);
    exit;
}

if ($action === 'withdraw') {
    $amount = (float)$_POST['amount'];
    $symbol = $_POST['symbol'] ?? 'USDT';
    $address = $_POST['address'] ?? '';
    $password = $_POST['password'] ?? '';
    $fiat_amount = isset($_POST['fiat_amount']) ? (float)$_POST['fiat_amount'] : null;
    $fiat_currency = $_POST['fiat_currency'] ?? null;
    
    // Validate balance
    $stmt = $db->prepare("SELECT available FROM user_balances WHERE user_id = ? AND symbol = ?");
    $stmt->execute([$user_id, $symbol]);
    $bal = $stmt->fetchColumn();
    
    if ($bal < $amount) {
        echo json_encode(['success' => false, 'error' => __('insufficient_balance')]);
        exit;
    }
    
    // In a real app, validate withdrawal password here. 
    // For now we just proceed as requested.
    
    $db->beginTransaction();
    try {
        // Deduct balance
        $db->prepare("UPDATE user_balances SET available = available - ? WHERE user_id = ? AND symbol = ?")
           ->execute([$amount, $user_id, $symbol]);
        
        // Record request
        $stmt = $db->prepare("INSERT INTO finance_requests (user_id, type, amount, symbol, payment_details, fiat_amount, fiat_currency, `status`, ip_address) VALUES (?, 'withdrawal', ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$user_id, $amount, $symbol, $address, $fiat_amount, $fiat_currency, '0', getRealIP()]);
        
        // Add to transactions as pending
        $db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, `status`, ip_address) VALUES (?, 'withdrawal', ?, ?, ?, ?)")
           ->execute([$user_id, $amount, $symbol, '0', getRealIP()]);
           
        $db->commit();
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

echo json_encode(['success' => false, 'error' => __('invalid_action')]);
