<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

try {
    $db = new PDO('sqlite:trading_platform.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // ট্রেড টেবিল তৈরি
    $db->exec("CREATE TABLE IF NOT EXISTS trades (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER,
        amount REAL,
        direction TEXT, 
        duration TEXT,  
        status TEXT DEFAULT 'Pending', 
        result_amount REAL DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

$user_id = $_SESSION['user_id'];
$message = "";

// ইউজারের বর্তমান ব্যালেন্স চেক
$stmt = $db->prepare("SELECT main_balance FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$current_balance = $stmt->fetchColumn();

// ট্রেড প্লেস করার লজিক
if (isset($_POST['place_trade'])) {
    $amount = (float)$_POST['trade_amount'];
    $direction = $_POST['direction'];
    $duration = $_POST['duration'];

    // সর্বনিম্ন ট্রেড $0.5 চেক
    if ($amount >= 0.5) {
        if ($amount <= $current_balance) {
            $new_balance = $current_balance - $amount;
            $update = $db->prepare("UPDATE users SET main_balance = ? WHERE id = ?");
            $update->execute([$new_balance, $user_id]);

            $stmt = $db->prepare("INSERT INTO trades (user_id, amount, direction, duration) VALUES (?, ?, ?, ?)");
            $stmt->execute([$user_id, $amount, $direction, $duration]);
            
            $message = "<div class='text-xs bg-green-500/10 text-green-500 p-3 rounded-xl border border-green-500/20 mb-4 text-center'>Trade Executed Successfully!</div>";
            $current_balance = $new_balance; 
        } else {
            $message = "<div class='text-xs bg-red-500/10 text-red-500 p-3 rounded-xl border border-red-500/20 mb-4 text-center'>Insufficient Balance!</div>";
        }
    } else {
        $message = "<div class='text-xs bg-yellow-500/10 text-yellow-500 p-3 rounded-xl border border-yellow-500/20 mb-4 text-center'>Minimum trade amount is $0.5</div>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Ziber - Live Trading Terminal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap');
        body { background: #0b0e11; color: #ffffff; font-family: 'Plus Jakarta Sans', sans-serif; padding-bottom: 100px; }
        .glass-panel { background: #161a21; border: 1px solid rgba(255, 255, 255, 0.05); }
        .btn-up { background-color: #2fb474; color: black; }
        .btn-down { background-color: #f6465d; color: white; }
        .trading-input { background: #0b0e11; border: 1px solid #2d3648; transition: 0.3s; color: white; }
        .trading-input:focus { border-color: #2fb474; outline: none; }
        ::-webkit-scrollbar { display: none; }
    </style>
</head>
<body class="p-4">

    <div class="flex justify-between items-center mb-6">
        <div class="flex items-center space-x-2">
            <div class="w-6 h-6 bg-[#2fb474] rounded-md flex items-center justify-center">
                <i class="fas fa-chart-line text-black text-[10px]"></i>
            </div>
            <span class="text-lg font-extrabold tracking-tighter uppercase">ZIBER</span>
        </div>
        <div class="text-right">
            <p class="text-[10px] text-gray-500 font-bold uppercase tracking-widest">Balance</p>
            <p class="text-lg font-black text-[#2fb474]">$<?php echo number_format($current_balance, 2); ?></p>
        </div>
    </div>

    <div class="glass-panel rounded-2xl overflow-hidden h-[300px] mb-6 relative border border-white/5 shadow-2xl">
        <iframe src="https://s.tradingview.com/widgetembed/?symbol=BINANCE:BTCUSDT&interval=1&theme=dark" class="w-full h-full border-0"></iframe>
    </div>

    <div class="glass-panel p-5 rounded-3xl mb-8">
        <?php echo $message; ?>
        
        <form method="POST" class="grid grid-cols-2 gap-4 mb-5">
            <div class="col-span-2">
                <label class="text-[10px] text-gray-500 uppercase font-black tracking-widest mb-2 block">Amount to Invest ($)</label>
                <input type="number" name="trade_amount" min="0.5" step="0.01" value="0.5" required 
                       class="trading-input w-full p-4 rounded-xl text-xl font-bold">
            </div>

            <div>
                <label class="text-[10px] text-gray-500 uppercase font-black tracking-widest mb-2 block">Duration</label>
                <select name="duration" class="trading-input w-full p-4 rounded-xl text-sm font-bold">
                    <option value="1min">1 MINUTE</option>
                    <option value="5min">5 MINUTES</option>
                    <option value="1hour">1 HOUR</option>
                </select>
            </div>

            <div class="flex flex-col justify-end">
                <div class="bg-black/40 p-3 rounded-xl border border-white/5 text-center">
                    <p class="text-[9px] text-gray-500 uppercase font-bold">Return (Est.)</p>
                    <p class="text-sm font-black text-green-500">90% Payout</p>
                </div>
            </div>

            <div class="col-span-2 grid grid-cols-2 gap-4 pt-2">
                <button type="submit" name="direction" value="up" class="btn-up py-4 rounded-2xl font-black text-xs uppercase tracking-widest active:scale-95 transition-all shadow-lg shadow-green-900/10">
                    UP <i class="fas fa-arrow-up ml-1"></i>
                </button>
                <button type="submit" name="direction" value="down" class="btn-down py-4 rounded-2xl font-black text-xs uppercase tracking-widest active:scale-95 transition-all shadow-lg shadow-red-900/10">
                    DOWN <i class="fas fa-arrow-down ml-1"></i>
                </button>
                <input type="hidden" name="place_trade" value="1">
            </div>
        </form>
    </div>

    <div class="mb-6">
        <h3 class="text-[10px] text-gray-500 uppercase font-black tracking-widest mb-4">Recent History</h3>
        <div class="space-y-3">
            <?php
            $stmt = $db->prepare("SELECT * FROM trades WHERE user_id = ? ORDER BY id DESC LIMIT 5");
            $stmt->execute([$user_id]);
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)):
                $is_up = $row['direction'] == 'up';
                $status = $row['status'];
                $status_color = ($status == 'Pending') ? 'text-yellow-500' : (($status == 'Win') ? 'text-[#2fb474]' : 'text-red-500');
            ?>
            <div class="glass-panel p-4 rounded-2xl flex justify-between items-center">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 rounded-xl flex items-center justify-center <?php echo $is_up ? 'bg-green-500/10 text-green-500' : 'bg-red-500/10 text-red-500'; ?>">
                        <i class="fas <?php echo $is_up ? 'fa-arrow-trend-up' : 'fa-arrow-trend-down'; ?>"></i>
                    </div>
                    <div>
                        <p class="text-xs font-bold uppercase"><?php echo $is_up ? 'CALL' : 'PUT'; ?></p>
                        <p class="text-[9px] text-gray-500"><?php echo date('h:i A', strtotime($row['created_at'])); ?></p>
                    </div>
                </div>
                <div class="text-right">
                    <p class="text-sm font-black">$<?php echo number_format($row['amount'], 2); ?></p>
                    <p class="text-[10px] font-bold uppercase <?php echo $status_color; ?>"><?php echo $status; ?></p>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
    </div>

    <?php include 'navbar.php'; ?>

</body>
</html>