<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/classes/SMMProviderAPI.php';
requireLogin();

$auth = new Auth();
$userModel = new User();
$currentBalance = $auth->refreshBalance($_SESSION['user_id']);
$pdo = getDBConnection();

$tab = $_GET['tab'] ?? 'smm';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Initialize SMM API for status checking
$smmApi = new SMMProviderAPI();

// Check and update pending SMM orders
if ($smmApi->hasApiKey()) {
    $stmt = $pdo->prepare("SELECT id, api_order_id, charge, quantity FROM smm_orders WHERE user_id = ? AND status IN ('pending', 'processing', 'in_progress') AND api_order_id IS NOT NULL");
    $stmt->execute([$_SESSION['user_id']]);
    $pendingOrders = $stmt->fetchAll();
    
    foreach ($pendingOrders as $pendingOrder) {
        if (empty($pendingOrder['api_order_id'])) continue;
        
        $apiStatus = $smmApi->getOrderStatus($pendingOrder['api_order_id']);
        
        if (isset($apiStatus['status'])) {
            $newStatus = strtolower($apiStatus['status']);
            
            $statusMap = [
                'completed' => 'completed',
                'partial' => 'partial',
                'canceled' => 'cancelled',
                'cancelled' => 'cancelled',
                'refunded' => 'refunded',
                'processing' => 'processing',
                'in progress' => 'in_progress',
                'pending' => 'pending'
            ];
            
            $mappedStatus = $statusMap[$newStatus] ?? $newStatus;
            
            // Refund for cancelled/refunded orders
            if (in_array($mappedStatus, ['cancelled', 'refunded'])) {
                $stmt = $pdo->prepare("SELECT status FROM smm_orders WHERE id = ?");
                $stmt->execute([$pendingOrder['id']]);
                $currentStatus = $stmt->fetchColumn();
                
                if (!in_array($currentStatus, ['cancelled', 'refunded'])) {
                    $userModel->updateBalance($_SESSION['user_id'], $pendingOrder['charge'], 'add');
                    $currentBalance = $auth->refreshBalance($_SESSION['user_id']);
                }
            }
            
            // Partial refund for undelivered quantity
            if ($mappedStatus === 'partial' && isset($apiStatus['remains'])) {
                $remains = floatval($apiStatus['remains']);
                if ($remains > 0) {
                    $stmt = $pdo->prepare("SELECT status FROM smm_orders WHERE id = ?");
                    $stmt->execute([$pendingOrder['id']]);
                    $currentStatus = $stmt->fetchColumn();
                    
                    if ($currentStatus !== 'partial') {
                        $pricePerUnit = $pendingOrder['charge'] / $pendingOrder['quantity'];
                        $refundAmount = $pricePerUnit * $remains;
                        $userModel->updateBalance($_SESSION['user_id'], $refundAmount, 'add');
                        $currentBalance = $auth->refreshBalance($_SESSION['user_id']);
                    }
                }
            }
            
            // Update order status
            $stmt = $pdo->prepare("UPDATE smm_orders SET status = ? WHERE id = ?");
            $stmt->execute([$mappedStatus, $pendingOrder['id']]);
        }
    }
}

// Check and update pending/waiting SMS orders
$stmt = $pdo->prepare("SELECT id, api_order_id, charge, created_at, expires_at FROM sms_orders WHERE user_id = ? AND status IN ('pending', 'waiting')");
$stmt->execute([$_SESSION['user_id']]);
$pendingSmsOrders = $stmt->fetchAll();

foreach ($pendingSmsOrders as $smsOrder) {
    $shouldUpdate = false;
    $newStatus = $smsOrder['status'] ?? 'pending';
    
    // Check if order has expired based on expires_at or time since creation
    $expiresAt = $smsOrder['expires_at'] ?? null;
    $createdAt = strtotime($smsOrder['created_at']);
    $now = time();
    
    // If expires_at is set and passed, mark as expired
    if ($expiresAt && strtotime($expiresAt) < $now) {
        $newStatus = 'expired';
        $shouldUpdate = true;
    }
    // If no expires_at but order is older than 20 minutes (typical SMS expiry), mark as expired
    elseif (!$expiresAt && ($now - $createdAt) > 1200) {
        $newStatus = 'expired';
        $shouldUpdate = true;
    }
    
    // Check if SMS code was received - if sms_code is set, mark as completed/received
    $stmt = $pdo->prepare("SELECT sms_code FROM sms_orders WHERE id = ?");
    $stmt->execute([$smsOrder['id']]);
    $smsCode = $stmt->fetchColumn();
    
    if (!empty($smsCode) && $newStatus !== 'expired') {
        $newStatus = 'received';
        $shouldUpdate = true;
    }
    
    // Update status if changed
    if ($shouldUpdate) {
        $stmt = $pdo->prepare("UPDATE sms_orders SET status = ? WHERE id = ?");
        $stmt->execute([$newStatus, $smsOrder['id']]);
        
        // Refund if expired and not already refunded
        if ($newStatus === 'expired') {
            $stmt = $pdo->prepare("SELECT refunded FROM sms_orders WHERE id = ?");
            $stmt->execute([$smsOrder['id']]);
            $refunded = $stmt->fetchColumn();
            
            if (!$refunded) {
                $userModel->updateBalance($_SESSION['user_id'], $smsOrder['charge'], 'add');
                $pdo->prepare("UPDATE sms_orders SET refunded = 1 WHERE id = ?")->execute([$smsOrder['id']]);
                $currentBalance = $auth->refreshBalance($_SESSION['user_id']);
            }
        }
    }
}

// Get SMS orders count
$stmt = $pdo->prepare("SELECT COUNT(*) FROM sms_orders WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$totalSmsOrders = $stmt->fetchColumn();

// Get SMS orders with country and service names
$stmt = $pdo->prepare("
    SELECT o.*, c.name as country_name, s.custom_name as service_name 
    FROM sms_orders o 
    LEFT JOIN sms_countries c ON o.country_id = c.id 
    LEFT JOIN sms_services s ON o.service_id = s.id 
    WHERE o.user_id = ? 
    ORDER BY o.created_at DESC 
    LIMIT $perPage OFFSET $offset
");
$stmt->execute([$_SESSION['user_id']]);
$smsOrders = $stmt->fetchAll();

// Get SMM orders count
$stmt = $pdo->prepare("SELECT COUNT(*) FROM smm_orders WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$totalSmmOrders = $stmt->fetchColumn();

// Get SMM orders with service names
$stmt = $pdo->prepare("
    SELECT o.*, s.custom_name as service_name 
    FROM smm_orders o 
    LEFT JOIN smm_services s ON o.service_id = s.id 
    WHERE o.user_id = ? 
    ORDER BY o.created_at DESC 
    LIMIT $perPage OFFSET $offset
");
$stmt->execute([$_SESSION['user_id']]);
$smmOrders = $stmt->fetchAll();

$totalOrders = $tab === 'sms' ? $totalSmsOrders : $totalSmmOrders;
$totalPages = ceil($totalOrders / $perPage);

// Status config
$statusConfig = [
    'completed' => ['icon' => 'fa-check-circle', 'color' => '#10B981', 'bg' => 'rgba(16, 185, 129, 0.1)'],
    'received' => ['icon' => 'fa-check-circle', 'color' => '#10B981', 'bg' => 'rgba(16, 185, 129, 0.1)'],
    'processing' => ['icon' => 'fa-spinner fa-spin', 'color' => '#3B82F6', 'bg' => 'rgba(59, 130, 246, 0.1)'],
    'in_progress' => ['icon' => 'fa-spinner fa-spin', 'color' => '#3B82F6', 'bg' => 'rgba(59, 130, 246, 0.1)'],
    'pending' => ['icon' => 'fa-clock', 'color' => '#F5A623', 'bg' => 'rgba(245, 166, 35, 0.1)'],
    'waiting' => ['icon' => 'fa-clock', 'color' => '#F5A623', 'bg' => 'rgba(245, 166, 35, 0.1)'],
    'cancelled' => ['icon' => 'fa-times-circle', 'color' => '#EF4444', 'bg' => 'rgba(239, 68, 68, 0.1)'],
    'expired' => ['icon' => 'fa-hourglass-end', 'color' => '#EF4444', 'bg' => 'rgba(239, 68, 68, 0.1)'],
    'refunded' => ['icon' => 'fa-undo', 'color' => '#10B981', 'bg' => 'rgba(16, 185, 129, 0.1)'],
    'partial' => ['icon' => 'fa-adjust', 'color' => '#F59E0B', 'bg' => 'rgba(245, 158, 11, 0.1)']
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Orders - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body { 
            font-family: 'Inter', sans-serif;
            background: #0A1628;
            color: #fff;
            min-height: 100vh;
            padding-bottom: 90px;
        }

        .header { 
            background: #0F2744;
            padding: 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
            border-bottom: 1px solid #1E3A5F;
        }

        .header-logo { 
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: #F5A623;
            font-weight: 700;
        }

        .header-logo img { height: 32px; }
        
        .header-balance { 
            background: #F5A623;
            color: #0A1628;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9rem;
        }

        .hamburger { 
            background: none;
            border: none;
            color: #fff;
            font-size: 1.4rem;
            cursor: pointer;
            padding: 0.5rem;
        }

        .menu-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            z-index: 200;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        .menu-overlay.active { opacity: 1; visibility: visible; }

        .side-menu {
            position: fixed;
            top: 0;
            left: -280px;
            width: 280px;
            height: 100%;
            background: #0F2744;
            z-index: 300;
            transition: left 0.3s ease;
            padding-top: 1rem;
            border-right: 1px solid #1E3A5F;
            overflow-y: auto;
        }
        .side-menu.active { left: 0; }

        .menu-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 1.5rem 1rem;
            border-bottom: 1px solid #1E3A5F;
        }

        .menu-close {
            background: none;
            border: none;
            color: #9CA3AF;
            font-size: 1.5rem;
            cursor: pointer;
        }

        .menu-items { padding: 1rem 0; }

        .menu-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem 1.5rem;
            color: #9CA3AF;
            text-decoration: none;
            transition: all 0.2s;
        }
        .menu-item:hover, .menu-item.active { background: #1E3A5F; color: #F5A623; }
        .menu-item i { width: 24px; text-align: center; }

        .menu-divider { height: 1px; background: #1E3A5F; margin: 0.5rem 1.5rem; }

        .content { padding: 1.5rem 1rem; max-width: 800px; margin: 0 auto; }

        .page-title {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        .page-title i { color: #F5A623; }

        .tab-container {
            background: #0F2744;
            padding: 0.375rem;
            border-radius: 12px;
            display: flex;
            gap: 0.375rem;
            margin-bottom: 1.5rem;
            border: 1px solid #1E3A5F;
        }

        .tab-btn {
            flex: 1;
            padding: 0.75rem;
            background: transparent;
            border: none;
            border-radius: 10px;
            color: #9CA3AF;
            font-size: 0.9rem;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            transition: all 0.2s;
            text-decoration: none;
        }
        .tab-btn.active { background: #F5A623; color: #0A1628; }

        .tab-count {
            background: rgba(255,255,255,0.2);
            padding: 0.15rem 0.5rem;
            border-radius: 10px;
            font-size: 0.75rem;
        }
        .tab-btn.active .tab-count { background: rgba(0,0,0,0.2); }

        .orders-list { display: flex; flex-direction: column; gap: 0.875rem; }

        .order-row {
            background: #0F2744;
            border: 1px solid #1E3A5F;
            border-radius: 16px;
            padding: 1.25rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }
        .order-row:hover {
            border-color: #F5A623;
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(0,0,0,0.3);
        }
        .order-row.clickable { cursor: pointer; }
        .order-row.clickable::after {
            content: 'Tap to view →';
            position: absolute;
            bottom: 0.75rem;
            right: 1rem;
            font-size: 0.7rem;
            color: #F5A623;
            opacity: 0.7;
        }

        .order-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 1rem; }
        .order-info { flex: 1; min-width: 0; }

        .order-service-name {
            font-size: 1.05rem;
            font-weight: 600;
            color: #fff;
            margin-bottom: 0.375rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .order-meta-line {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            color: #9CA3AF;
            font-size: 0.8rem;
        }
        .order-meta-line span { display: flex; align-items: center; gap: 0.35rem; }
        .order-meta-line i { font-size: 0.75rem; color: #F5A623; }

        .status-badge {
            display: flex;
            align-items: center;
            gap: 0.4rem;
            padding: 0.5rem 0.875rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.3px;
            white-space: nowrap;
        }

        .order-details {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #1E3A5F;
        }

        .detail-box { display: flex; flex-direction: column; gap: 0.25rem; }
        .detail-label { font-size: 0.7rem; color: #9CA3AF; text-transform: uppercase; letter-spacing: 0.5px; }
        .detail-value { font-size: 0.95rem; font-weight: 600; color: #fff; }
        .detail-value.price { color: #F5A623; }
        .detail-value.id { font-family: monospace; color: #9CA3AF; }

        .sms-data {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
            padding-top: 0.75rem;
            border-top: 1px solid #1E3A5F;
        }

        .data-row { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
        .data-label { display: flex; align-items: center; gap: 0.5rem; color: #9CA3AF; font-size: 0.85rem; }

        .data-value-box {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            background: #0A1628;
            padding: 0.625rem 1rem;
            border-radius: 10px;
            border: 1px solid #1E3A5F;
            flex: 1;
            max-width: 200px;
            justify-content: space-between;
        }

        .data-value { font-family: monospace; font-weight: 600; }
        .data-value.phone { color: #3B82F6; }
        .data-value.code { color: #10B981; letter-spacing: 1px; font-size: 1.1rem; }

        .copy-btn {
            background: #1E3A5F;
            border: none;
            color: #9CA3AF;
            width: 28px;
            height: 28px;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }
        .copy-btn:hover { background: #F5A623; color: #0A1628; }

        .smm-link {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.875rem 1rem;
            background: #0A1628;
            border-radius: 10px;
            border: 1px solid #1E3A5F;
        }
        .smm-link i { color: #3B82F6; }
        .smm-link-text {
            flex: 1;
            font-size: 0.85rem;
            color: #9CA3AF;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .empty-state { text-align: center; padding: 4rem 2rem; color: #9CA3AF; }
        .empty-icon {
            width: 80px;
            height: 80px;
            background: #0F2744;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1.5rem;
            font-size: 2rem;
            color: #F5A623;
            border: 2px solid #1E3A5F;
        }
        .empty-state h3 { color: #fff; margin-bottom: 0.5rem; }
        .empty-state a { color: #F5A623; text-decoration: none; font-weight: 600; }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 1rem;
            margin-top: 2rem;
            padding-top: 1rem;
            border-top: 1px solid #1E3A5F;
        }

        .page-btn {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #0F2744;
            border: 1px solid #1E3A5F;
            border-radius: 10px;
            color: #9CA3AF;
            text-decoration: none;
            transition: all 0.2s;
        }
        .page-btn:hover { border-color: #F5A623; color: #F5A623; }
        .page-btn.disabled { opacity: 0.5; pointer-events: none; }

        .page-info { font-size: 0.9rem; color: #9CA3AF; }
        .page-info span { color: #fff; font-weight: 700; }

        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: #0F2744;
            border-top: 1px solid #1E3A5F;
            display: flex;
            justify-content: space-around;
            padding: 0.75rem 0;
            z-index: 999;
        }
        .bottom-nav a {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.25rem;
            text-decoration: none;
            color: #9CA3AF;
            font-size: 0.7rem;
            padding: 0.5rem;
            -webkit-tap-highlight-color: transparent;
            cursor: pointer;
        }
        .bottom-nav a i { font-size: 1.25rem; }
        .bottom-nav a.active { color: #F5A623; }

        .toast {
            position: fixed;
            bottom: 120px;
            left: 50%;
            transform: translateX(-50%) translateY(100px);
            background: #0F2744;
            border: 1px solid #1E3A5F;
            padding: 1rem 1.5rem;
            border-radius: 12px;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            z-index: 500;
            opacity: 0;
            pointer-events: none;
            transition: all 0.3s ease;
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        }
        .toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
        .toast-icon { color: #10B981; font-size: 1.25rem; }
        
        .refund-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            background: rgba(16, 185, 129, 0.15);
            color: #10B981;
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.7rem;
            font-weight: 600;
            margin-left: 0.5rem;
        }

        @media (max-width: 640px) {
            .order-details { grid-template-columns: 1fr; gap: 0.75rem; }
            .detail-box { flex-direction: row; justify-content: space-between; }
            .data-row { flex-direction: column; align-items: flex-start; gap: 0.5rem; }
            .data-value-box { max-width: 100%; width: 100%; }
        }
    </style>
    <link rel="stylesheet" href="/assets/css/premium-dark.css">
</head>
<body>
    <header class="header">
        <button class="hamburger" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
        <div class="header-logo">
            <img src="/assets/images/logo.png" alt="<?php echo SITE_NAME; ?>">
        </div>
        <div class="header-balance"><?php echo formatCurrency($currentBalance); ?></div>
    </header>

    <div class="menu-overlay" id="menuOverlay" onclick="toggleMenu()"></div>
    
    <nav class="side-menu" id="sideMenu">
        <div class="menu-header">
            <div class="header-logo">
                <img src="/assets/images/logo.png" alt="<?php echo SITE_NAME; ?>">
            </div>
            <button class="menu-close" onclick="toggleMenu()"><i class="fas fa-times"></i></button>
        </div>
        <div class="menu-items">
            <a href="dashboard.php" class="menu-item"><i class="fas fa-home"></i> Dashboard</a>
            <a href="sms.php" class="menu-item"><i class="fas fa-sms"></i> SMS Service</a>
            <a href="smm.php" class="menu-item"><i class="fas fa-rocket"></i> SMM Service</a>
            <a href="banner.php" class="menu-item"><i class="fas fa-ad"></i> Banner Service</a>
            <a href="orders.php" class="menu-item active"><i class="fas fa-history"></i> Orders</a>
            <div class="menu-divider"></div>
            <a href="add-funds.php" class="menu-item"><i class="fas fa-wallet"></i> Add Funds</a>
            <a href="transactions.php" class="menu-item"><i class="fas fa-exchange-alt"></i> Transactions</a>
            <a href="profile.php" class="menu-item"><i class="fas fa-user"></i> Profile</a>
            <div class="menu-divider"></div>
            <a href="<?php echo SITE_URL; ?>/logout.php" class="menu-item"><i class="fas fa-sign-out-alt"></i> Log Out</a>
        </div>
    </nav>

    <main class="content">
        <h1 class="page-title"><i class="fas fa-history"></i> Orders</h1>

        <div class="tab-container">
            <a href="?tab=smm" class="tab-btn <?php echo $tab === 'smm' ? 'active' : ''; ?>">
                <i class="fas fa-rocket"></i> SMM
                <span class="tab-count"><?php echo $totalSmmOrders; ?></span>
            </a>
            <a href="?tab=sms" class="tab-btn <?php echo $tab === 'sms' ? 'active' : ''; ?>">
                <i class="fas fa-sms"></i> SMS
                <span class="tab-count"><?php echo $totalSmsOrders; ?></span>
            </a>
        </div>

        <?php if ($tab === 'smm'): ?>
            <?php if (empty($smmOrders)): ?>
            <div class="empty-state">
                <div class="empty-icon"><i class="fas fa-rocket"></i></div>
                <h3>No SMM orders yet</h3>
                <p>Boost your social media presence today<br><a href="smm.php">Create your first order →</a></p>
            </div>
            <?php else: ?>
            <div class="orders-list">
                <?php foreach ($smmOrders as $order): 
                    $status = $order['status'];
                    $config = $statusConfig[$status] ?? $statusConfig['pending'];
                ?>
                <div class="order-row">
                    <div class="order-top">
                        <div class="order-info">
                            <div class="order-service-name"><?php echo htmlspecialchars($order['service_name'] ?? 'Service #' . $order['service_id']); ?></div>
                            <div class="order-meta-line">
                                <span><i class="fas fa-calendar"></i> <?php echo date('M j, Y', strtotime($order['created_at'])); ?></span>
                                <span><i class="fas fa-clock"></i> <?php echo date('g:i A', strtotime($order['created_at'])); ?></span>
                            </div>
                        </div>
                        <div class="status-badge" style="background: <?php echo $config['bg']; ?>; color: <?php echo $config['color']; ?>">
                            <i class="fas <?php echo $config['icon']; ?>"></i>
                            <?php echo ucfirst(str_replace('_', ' ', $status)); ?>
                        </div>
                    </div>
                    
                    <div class="order-details">
                        <div class="detail-box">
                            <span class="detail-label">Order ID</span>
                            <span class="detail-value id">#<?php echo $order['id']; ?></span>
                        </div>
                        <div class="detail-box">
                            <span class="detail-label">Quantity</span>
                            <span class="detail-value"><?php echo number_format($order['quantity']); ?></span>
                        </div>
                        <div class="detail-box">
                            <span class="detail-label">Price</span>
                            <span class="detail-value price"><?php echo formatCurrency($order['charge']); ?></span>
                        </div>
                    </div>

                    <div class="smm-link">
                        <i class="fas fa-link"></i>
                        <span class="smm-link-text"><?php echo htmlspecialchars($order['link']); ?></span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

        <?php else: ?>
            <?php if (empty($smsOrders)): ?>
            <div class="empty-state">
                <div class="empty-icon"><i class="fas fa-sms"></i></div>
                <h3>No SMS orders yet</h3>
                <p>Get verification codes instantly<br><a href="sms.php">Order a number →</a></p>
            </div>
            <?php else: ?>
            <div class="orders-list">
                <?php foreach ($smsOrders as $order): 
                    $status = $order['status'];
                    $config = $statusConfig[$status] ?? $statusConfig['pending'];
                    $isPending = in_array($status, ['pending', 'waiting']);
                    $isExpired = $status === 'expired';
                    $isRefunded = !empty($order['refunded']);
                ?>
                <div class="order-row <?php echo $isPending ? 'clickable' : ''; ?>" <?php if ($isPending): ?>onclick="goToOrder(<?php echo $order['id']; ?>)"<?php endif; ?>>
                    <div class="order-top">
                        <div class="order-info">
                            <div class="order-service-name">
                                <?php echo htmlspecialchars($order['service_name'] ?? 'SMS Service'); ?>
                                <?php if (!empty($order['country_name'])): ?>
                                <span style="color: #9CA3AF; font-weight: 400;">— <?php echo htmlspecialchars($order['country_name']); ?></span>
                                <?php endif; ?>
                            </div>
                            <div class="order-meta-line">
                                <span><i class="fas fa-calendar"></i> <?php echo date('M j, Y', strtotime($order['created_at'])); ?></span>
                                <span><i class="fas fa-clock"></i> <?php echo date('g:i A', strtotime($order['created_at'])); ?></span>
                            </div>
                        </div>
                        <div class="status-badge" style="background: <?php echo $config['bg']; ?>; color: <?php echo $config['color']; ?>">
                            <i class="fas <?php echo $config['icon']; ?>"></i>
                            <?php echo ucfirst(str_replace('_', ' ', $status)); ?>
                            <?php if ($isExpired && $isRefunded): ?>
                            <span class="refund-badge"><i class="fas fa-undo"></i> Refunded</span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="order-details">
                        <div class="detail-box">
                            <span class="detail-label">Order ID</span>
                            <span class="detail-value id">#<?php echo $order['id']; ?></span>
                        </div>
                        <div class="detail-box">
                            <span class="detail-label">Price</span>
                            <span class="detail-value price"><?php echo formatCurrency($order['charge']); ?></span>
                        </div>
                        <div class="detail-box">
                            <span class="detail-label">Status</span>
                            <span class="detail-value" style="color: <?php echo $config['color']; ?>">
                                <?php echo ucfirst($status); ?>
                            </span>
                        </div>
                    </div>

                    <?php if (!empty($order['phone_number']) || !empty($order['sms_code'])): ?>
                    <div class="sms-data">
                        <?php if (!empty($order['phone_number'])): ?>
                        <div class="data-row">
                            <span class="data-label"><i class="fas fa-phone"></i> Phone Number</span>
                            <div class="data-value-box">
                                <span class="data-value phone"><?php echo htmlspecialchars($order['phone_number']); ?></span>
                                <button class="copy-btn" onclick="copyText('<?php echo htmlspecialchars($order['phone_number']); ?>', event)"><i class="fas fa-copy"></i></button>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($order['sms_code'])): ?>
                        <div class="data-row">
                            <span class="data-label"><i class="fas fa-comment-dots"></i> SMS Code</span>
                            <div class="data-value-box" style="border-color: rgba(16, 185, 129, 0.3); background: rgba(16, 185, 129, 0.05);">
                                <span class="data-value code"><?php echo htmlspecialchars($order['sms_code']); ?></span>
                                <button class="copy-btn" onclick="copyText('<?php echo htmlspecialchars($order['sms_code']); ?>', event)" style="background: rgba(16, 185, 129, 0.2); color: #10B981;"><i class="fas fa-copy"></i></button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        <?php endif; ?>

        <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <a href="?tab=<?php echo $tab; ?>&page=<?php echo $page - 1; ?>" class="page-btn <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                <i class="fas fa-chevron-left"></i>
            </a>
            <span class="page-info">Page <span><?php echo $page; ?></span> of <?php echo $totalPages; ?></span>
            <a href="?tab=<?php echo $tab; ?>&page=<?php echo $page + 1; ?>" class="page-btn <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                <i class="fas fa-chevron-right"></i>
            </a>
        </div>
        <?php endif; ?>
    </main>

    <nav class="bottom-nav">
        <a href="dashboard.php" onclick="window.location.href='dashboard.php';return true;"><i class="fas fa-home"></i> Home</a>
        <a href="sms.php" onclick="window.location.href='sms.php';return true;"><i class="fas fa-sms"></i> SMS</a>
        <a href="smm.php" onclick="window.location.href='smm.php';return true;"><i class="fas fa-rocket"></i> SMM</a>
        <a href="orders.php" class="active"><i class="fas fa-history"></i> Orders</a>
        <a href="profile.php" onclick="window.location.href='profile.php';return true;"><i class="fas fa-user"></i> Profile</a>
    </nav>

    <div class="toast" id="toast">
        <i class="fas fa-check-circle toast-icon"></i>
        <span>Copied to clipboard!</span>
    </div>

    <script>
    function toggleMenu() {
        document.getElementById('sideMenu').classList.toggle('active');
        document.getElementById('menuOverlay').classList.toggle('active');
    }

    function goToOrder(orderId) {
        window.location.href = 'sms-order.php?id=' + orderId;
    }

    function copyText(text, event) {
        if (event) {
            event.stopPropagation();
            event.preventDefault();
        }
        navigator.clipboard.writeText(text).then(function() {
            var toast = document.getElementById('toast');
            toast.classList.add('show');
            setTimeout(function() { toast.classList.remove('show'); }, 2000);
        });
    }
    </script>
</body>
</html>