<?php 
include 'common/header.php'; 
if(!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }
$uid = $_SESSION['user_id'];

// --- TELEGRAM NOTIFICATION FUNCTION (ADDED) ---
function sendTelegramNotif($message) {
    $botToken = "00000000000000000";
    $chatIds = ["0000"];
    foreach ($chatIds as $chatId) {
        $url = "https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatId&text=" . urlencode($message) . "&parse_mode=HTML";
        @file_get_contents($url);
    }
}

// --- HANDLE FORM SUBMISSION ---
if(isset($_POST['action']) && $_POST['action'] == 'create_order') {
    $gid = (int)$_POST['game_id'];
    $pid = (int)$_POST['product_id'];
    $amt = $_POST['amount'];
    $ply = isset($_POST['player_id']) ? $conn->real_escape_string($_POST['player_id']) : '';
    $met = isset($_POST['payment_method']) ? $conn->real_escape_string($_POST['payment_method']) : '';
    $trx = isset($_POST['trx_id']) ? $conn->real_escape_string($_POST['trx_id']) : '';
    $wal = isset($_POST['wallet_number']) ? $conn->real_escape_string($_POST['wallet_number']) : '';

    $gameType = 'uid';
    $gameName = "Wallet Deposit"; 
    if($gid > 0) {
        $gRes = $conn->query("SELECT name, type FROM games WHERE id=$gid");
        if($gRes && $gRes->num_rows > 0) {
            $gRow = $gRes->fetch_assoc();
            $gameType = $gRow['type'];
            $gameName = $gRow['name'];
        }
    }

    if($gid == 0) {
        $stmt = $conn->prepare("INSERT INTO deposits (user_id, amount, method, wallet_number, trx_id, status) VALUES (?, ?, ?, ?, ?, 'pending')");
        $stmt->bind_param("idsss", $uid, $amt, $met, $wal, $trx);
        
        if($stmt->execute()){
            // --- TELEGRAM SEND FOR DEPOSIT ---
            $msg = "💰 <b>New Deposit Request!</b>\n\n";
            $msg .= "💵 Amount: ৳$amt\n";
            $msg .= "💳 Method: $met\n";
            $msg .= "📱 Number: $wal\n";
            $msg .= "🆔 TrxID: $trx\n";
            $msg .= "👤 User ID: $uid";
            sendTelegramNotif($msg);

            echo "<script>window.location.href='payment_history.php';</script>";
            exit;
        }
    } else {
        $stmt = $conn->prepare("INSERT INTO orders (user_id, game_id, product_id, amount, player_id, transaction_id, payment_method, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')");
        $stmt->bind_param("iiidsss", $uid, $gid, $pid, $amt, $ply, $trx, $met);
        
        if($stmt->execute()){
            // --- TELEGRAM SEND FOR ORDER ---
            $msg = "🎮 <b>New Game Order!</b>\n\n";
            $msg .= "🕹 Game: $gameName\n";
            $msg .= "🆔 Player ID: $ply\n";
            $msg .= "💵 Amount: ৳$amt\n";
            $msg .= "💳 Method: $met\n";
            $msg .= "📑 TrxID: $trx";
            sendTelegramNotif($msg);

            if($gameType == 'voucher') {
                echo "<script>window.location.href='mycode.php';</script>";
            } else {
                echo "<script>window.location.href='order.php';</script>";
            }
            exit;
        }
    }
}
?>

<div class="container mx-auto px-4 py-6 mb-20 max-w-2xl">
    <h2 class="text-lg font-bold mb-6 text-gray-800 flex items-center gap-2">
        <i class="fa-solid fa-clock-rotate-left text-sky-500"></i> My Orders
    </h2>
    
    <div class="space-y-3">
        <?php 
        $sql = "SELECT o.*, g.name as gname, g.image as gimg, p.name as pname 
                FROM orders o 
                JOIN games g ON o.game_id = g.id 
                JOIN products p ON o.product_id = p.id 
                WHERE o.user_id=$uid ORDER BY o.id DESC";
        $res = $conn->query($sql);
        
        if($res && $res->num_rows > 0):
        while($row = $res->fetch_assoc()): 
            $statusClass = 'bg-amber-50 text-amber-600 border-amber-100';
            if($row['status'] == 'completed') $statusClass = 'bg-emerald-50 text-emerald-600 border-emerald-100';
            if($row['status'] == 'cancelled') $statusClass = 'bg-rose-50 text-rose-600 border-rose-100';
        ?>
        <div class="bg-white p-4 rounded-xl border border-gray-100 shadow-sm">
            <div class="flex gap-4">
                <img src="<?php echo $row['gimg']; ?>" class="w-14 h-14 rounded-lg object-cover border border-gray-50">
                <div class="flex-1 min-w-0">
                    <div class="flex justify-between items-start">
                        <h3 class="font-bold text-gray-800 truncate text-sm"><?php echo $row['gname']; ?></h3>
                        <span class="text-[10px] px-2 py-0.5 rounded-full border font-bold uppercase <?php echo $statusClass; ?>">
                            <?php echo $row['status']; ?>
                        </span>
                    </div>
                    <p class="text-xs text-gray-500 mb-2"><?php echo $row['pname']; ?></p>
                    <span class="font-bold text-sky-600 text-sm">৳<?php echo $row['amount']; ?></span>
                </div>
            </div>
            
            <div class="mt-3 pt-3 border-t border-gray-50">
                <details class="group">
                    <summary class="list-none flex justify-between items-center cursor-pointer text-[11px] font-bold text-gray-400 hover:text-sky-500 transition-colors">
                        ORDER DETAILS 
                        <i class="fa-solid fa-chevron-down group-open:rotate-180 transition-transform"></i>
                    </summary>
                    <div class="mt-2 space-y-1 text-[11px] text-gray-500 bg-gray-50 p-2 rounded-lg">
                        <p class="flex justify-between"><span>Order ID:</span> <span class="text-gray-700 font-medium">#<?php echo $row['id']; ?></span></p>
                        <p class="flex justify-between"><span>Player ID:</span> <span class="text-gray-700 font-medium"><?php echo $row['player_id']; ?></span></p>
                        <p class="flex justify-between"><span>Transaction:</span> <span class="text-gray-700 font-medium"><?php echo $row['transaction_id']; ?></span></p>
                        <p class="flex justify-between"><span>Date:</span> <span class="text-gray-700 font-medium"><?php echo date('d M Y, h:i A', strtotime($row['created_at'])); ?></span></p>
                    </div>
                </details>
            </div>
        </div>
        <?php endwhile; 
        else: ?>
            <div class="text-center py-20 bg-white rounded-xl border border-dashed border-gray-200">
                <i class="fa-solid fa-box-open text-gray-200 text-4xl mb-3"></i>
                <p class="text-gray-400 text-sm">No orders yet.</p>
            </div>
        <?php endif; ?>
    </div>
    
    <div class="text-center py-12">
        <p class="text-[10px] text-gray-300 font-bold uppercase tracking-widest">
            &copy; <?php echo date("Y"); ?> <?php echo getSetting($conn, 'site_name'); ?>
        </p>
    </div>
</div>

<?php include 'common/bottom.php'; ?>