<?php 
ob_start();
include 'common/config.php';

if(!isset($_SESSION['user_id'])) { 
    if(isset($_GET['action'])) { die(json_encode(['status' => 'error'])); }
    header("Location: login.php"); 
    exit; 
}
$uid = (int)$_SESSION['user_id'];

// ====================================================
// AJAX STATUS CHECK
// ====================================================
if(isset($_GET['action']) && $_GET['action'] == 'check_status') {
    ob_clean(); 
    header('Content-Type: application/json');
    $oid = (int)$_GET['order_id'];
    $q = clone $conn;
    $res = $q->query("SELECT status FROM orders WHERE id=$oid AND user_id=$uid");
    if($res && $res->num_rows > 0) {
        echo json_encode(['status' => $res->fetch_assoc()['status']]);
    } else {
        echo json_encode(['status' => 'unknown']);
    }
    exit;
}

// ====================================================
// SELF-HEALING DATABASE: Ensure Stock Table Exists
// ====================================================
if(isset($conn)) {
    try {
        $conn->query("CREATE TABLE IF NOT EXISTS product_codes (
            id INT AUTO_INCREMENT PRIMARY KEY,
            product_id INT NOT NULL,
            code VARCHAR(255) NOT NULL,
            status ENUM('unused', 'used') DEFAULT 'unused',
            order_id INT DEFAULT 0,
            used_at TIMESTAMP NULL,
            INDEX(product_id),
            INDEX(status)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

        $checkCol = $conn->query("SHOW COLUMNS FROM games LIKE 'api_key'");
        if ($checkCol && $checkCol->num_rows == 0) {
            $conn->query("ALTER TABLE games ADD COLUMN api_key VARCHAR(255) DEFAULT NULL");
        }
    } catch (Exception $e) {
        // Silently continue if database structure already exists
    }
}

// ====================================================
// HANDLE FORM SUBMISSION (Must be before output)
// ====================================================
if(isset($_POST['action']) && $_POST['action'] == 'create_order') {
    $gid = (int)$_POST['game_id'];
    $pid = (int)$_POST['product_id'];
    $ply = isset($_POST['player_id']) ? $conn->real_escape_string($_POST['player_id']) : '';
    $met = isset($_POST['payment_method']) ? $conn->real_escape_string($_POST['payment_method']) : 'wallet';
    
    $trx = !empty($_POST['order_txid']) ? $conn->real_escape_string($_POST['order_txid']) : "TR-" . strtoupper(uniqid()); 

    $pQuery = $conn->query("SELECT * FROM products WHERE id=$pid");
    $gQuery = $conn->query("SELECT * FROM games WHERE id=$gid");
    
    if(!$pQuery || !$gQuery || $pQuery->num_rows == 0 || $gQuery->num_rows == 0) { 
        echo "<script>alert('Invalid Request'); window.location.href='index.php';</script>";
        exit;
    }
    
    $pData = $pQuery->fetch_assoc();
    $gData = $gQuery->fetch_assoc();
    
    $amt = (float)$pData['price'];
    $unipinCode = null;
    $stockId = 0;

    $conn->begin_transaction();

    try {
        // 1. STOCK CHECK (Fetch PIN for auto topup)
        $stockQ = $conn->query("SELECT id, code FROM product_codes WHERE product_id=$pid AND status='unused' LIMIT 1 FOR UPDATE");
        if ($stockQ && $stockQ->num_rows > 0) {
            $stockRow = $stockQ->fetch_assoc();
            $unipinCode = $stockRow['code'];
            $stockId = $stockRow['id'];
        }

        // 2. WALLET CHECK
        if($met == 'wallet') {
            $uRes = $conn->query("SELECT balance FROM users WHERE id=$uid");
            if(!$uRes || $uRes->num_rows == 0) throw new Exception("User not found!");
            
            $uData = $uRes->fetch_assoc();
            if($uData['balance'] < $amt) {
                throw new Exception("Insufficient Balance!");
            }
            $newBalance = $uData['balance'] - $amt;
            $conn->query("UPDATE users SET balance = $newBalance WHERE id = $uid");
        }

        // 3. INSERT ORDER
        $status = ($stockId > 0) ? 'processing' : 'pending';
        $stmt = $conn->prepare("INSERT INTO orders (user_id, game_id, product_id, amount, player_id, transaction_id, payment_method, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
        if(!$stmt) throw new Exception("Database error: " . $conn->error);
        
        $stmt->bind_param("iiidssss", $uid, $gid, $pid, $amt, $ply, $trx, $met, $status);
        $stmt->execute();
        $orderId = $stmt->insert_id;

        // 4. MARK CODE USED
        if($stockId > 0) {
            $conn->query("UPDATE product_codes SET status='used', order_id=$orderId, used_at=NOW() WHERE id=$stockId");
        }

        // COMMIT TRANSACTION
        $conn->commit();

        // 5. AUTO TOPUP TRIGGER
        if($stockId > 0) {
            $default_api = "API-7R1HS1YTYKHKDPJB"; 
            $apiKey = (!empty($gData['api_key'])) ? $gData['api_key'] : $default_api;
            
            // Hardcoded secure fallback for API
            $apiUrl = "https://apiserver.s2kgame.shop/api/unipintopup";
            
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $callbackUrl = $protocol . $_SERVER['HTTP_HOST'] . "/callback.php";

            $postData = [ 
                "api" => $apiKey, 
                "orderid" => (string)$orderId, 
                "playerid" => $ply, 
                "code" => $unipinCode, 
                "url" => $callbackUrl 
            ];

            $ch = curl_init($apiUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Accept: application/json'
            ]);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 5 seconds timeout so page loads fast
            curl_exec($ch);
            curl_close($ch);
        }

        header("Location: order.php");
        exit;

    } catch (Exception $e) {
        $conn->rollback();
        echo "<script>alert('".$e->getMessage()."'); window.location.href='game_detail.php?id=$gid';</script>";
        exit;
    }
}

// Output headers properly below logic
include 'common/header.php';
?>

<link href="https://fonts.googleapis.com/css2?family=Bree+Serif&family=Inter:wght@400;600;700&display=swap" rel="stylesheet">

<style>
    body {
        background-image: url('res/backgrounds/bg.png');
        background-repeat: repeat;
        background-size: 100% auto; 
        background-attachment: scroll;
        background-position: top center;
        font-family: 'Inter', sans-serif;
        -webkit-user-select: none; user-select: none;
    }

    .main-card {
        background: white;
        border-radius: 6px;
        box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        overflow: hidden;
    }

    .card-header {
        background: white;
        padding: 15px 20px;
        border-bottom: 1px solid #e5e7eb;
        font-family: 'Bree Serif', serif;
        font-size: 18px;
        font-weight: 700;
        display: flex; align-items: center; gap: 10px;
        color: #111827;
    }

    .order-item {
        padding: 15px 20px;
        border-bottom: 1px solid #f3f4f6;
    }
    .order-item:last-child { border-bottom: none; }

    .data-row {
        display: flex;
        margin-bottom: 8px;
        font-size: 14px;
        color: #1f2937;
        align-items: baseline;
    }

    .label {
        font-weight: 700;
        color: #000;
        width: 100px;
        flex-shrink: 0;
    }

    .value {
        font-weight: 500;
        color: #374151;
    }

    .st-pending { color: #eab308; font-weight: 700; } 
    .st-processing { color: #2563eb; font-weight: 700; } 
    .st-completed { color: #16a34a; font-weight: 700; } 
    .st-cancelled { color: #dc2626; font-weight: 700; } 
</style>

<div class="container mx-auto px-4 py-8 mb-20 max-w-lg">
    
    <div class="main-card">
        
        <div class="card-header">
            <i class="fa-solid fa-list-ul"></i> My Orders
        </div>
        
        <div class="flex flex-col">
            <?php 
            $sql = "SELECT o.*, g.name as gname, 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): 
                echo "<div class='p-10 text-center text-red-500 font-bold'>Database Error: " . htmlspecialchars($conn->error) . "</div>";
            elseif($res->num_rows > 0):
                while($row = $res->fetch_assoc()): 
                    $st = strtolower($row['status']);
                    $stClass = 'st-pending';
                    if($st == 'completed') $stClass = 'st-completed';
                    if($st == 'processing') $stClass = 'st-processing';
                    if($st == 'cancelled') $stClass = 'st-cancelled';
                    
                    $displayAmount = isset($row['amount']) ? (float)$row['amount'] : 0.00;
                    $date = isset($row['created_at']) ? date('d-m-Y h:i:s A', strtotime($row['created_at'])) : 'Unknown';
            ?>
            
            <div class="order-item <?php echo ($st == 'processing') ? 'processing-order' : ''; ?>" data-id="<?php echo isset($row['id']) ? $row['id'] : ''; ?>">
                <div class="data-row">
                    <span class="label">Order ID:</span>
                    <span class="value"><?php echo isset($row['id']) ? $row['id'] : ''; ?></span>
                </div>

                <div class="data-row">
                    <span class="label">Date:</span>
                    <span class="value"><?php echo $date; ?></span>
                </div>

                <div class="data-row">
                    <span class="label">Package:</span>
                    <span class="value"><?php echo isset($row['pname']) ? htmlspecialchars($row['pname']) : ''; ?></span>
                </div>
                
                <?php if(!empty($row['player_id'])): ?>
                <div class="data-row">
                    <span class="label">Player ID:</span>
                    <span class="value"><?php echo htmlspecialchars($row['player_id']); ?></span>
                </div>
                <?php endif; ?>

                <div class="data-row">
                    <span class="label">Price:</span>
                    <span class="value">৳<?php echo number_format($displayAmount); ?></span>
                </div>

                <div class="data-row">
                    <span class="label">Status:</span>
                    <span class="<?php echo $stClass; ?> status-text" style="display: inline-block; visibility: visible; opacity: 1;"><?php echo ($st == 'pending' || $st == 'processing') ? 'auto-processing' : $st; ?></span>
                </div>
            </div>

            <?php 
                endwhile; 
            else: 
            ?>
                <div class="p-10 text-center">
                    <i class="fa-solid fa-cart-shopping text-gray-200 text-5xl mb-4"></i>
                    <p class="text-gray-500 font-bold">No orders found.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div id="toast-container" style="position: fixed; top: 20px; right: 20px; z-index: 9999; display: flex; flex-direction: column; gap: 10px;"></div>

<script>
    function showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.style.padding = '12px 20px';
        toast.style.borderRadius = '4px';
        toast.style.color = '#fff';
        toast.style.fontWeight = 'bold';
        toast.style.boxShadow = '0 2px 4px rgba(0,0,0,0.2)';
        toast.style.background = type === 'success' ? '#16a34a' : '#dc2626';
        toast.innerText = message;
        
        document.getElementById('toast-container').appendChild(toast);
        setTimeout(() => toast.remove(), 4000);
    }

    document.querySelectorAll('.processing-order').forEach(orderDiv => {
        let orderId = orderDiv.getAttribute('data-id');
        if(!orderId) return;
        
        let statusSpan = orderDiv.querySelector('.status-text');
        
        let checkInterval = setInterval(() => {
            let fetchUrl = window.location.pathname + '?action=check_status&order_id=' + orderId;
            fetch(fetchUrl)
            .then(res => res.text())
            .then(text => {
                try {
                    let data = JSON.parse(text);
                    if(data.status && data.status !== 'processing' && data.status !== 'pending') {
                        clearInterval(checkInterval);
                        
                        if(data.status === 'completed') {
                            showToast('Order #' + orderId + ' Topup Successful!', 'success');
                            if(statusSpan) {
                                statusSpan.className = 'st-completed status-text';
                                statusSpan.innerText = 'completed';
                            }
                        } else if(data.status === 'cancelled' || data.status === 'error') {
                            showToast('Order #' + orderId + ' Topup Failed!', 'error');
                            if(statusSpan) {
                                statusSpan.className = 'st-cancelled status-text';
                                statusSpan.innerText = 'cancelled';
                            }
                        }
                    }
                } catch (e) {
                    console.error('Invalid JSON response:', text);
                }
            }).catch(err => console.error(err));
        }, 3000);
    });
</script>

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