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

$pdo = getDBConnection();

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

// Get SMM orders count
$smmTotal = $pdo->query("SELECT COUNT(*) FROM smm_orders")->fetchColumn();

// Get SMS orders count  
$smsTotal = $pdo->query("SELECT COUNT(*) FROM sms_orders")->fetchColumn();

// Build search condition
$searchWhere = "";
$searchParams = [];
if ($search) {
    $searchWhere = " AND (u.name LIKE ? OR u.email LIKE ? OR o.id = ?)";
    $searchParams = ["%$search%", "%$search%", $search];
}

if ($tab === 'sms') {
    // Get SMS orders
    $sql = "SELECT o.*, u.name as user_name, u.email as user_email, c.name as country_name, s.custom_name as service_name
            FROM sms_orders o
            LEFT JOIN users u ON o.user_id = u.id
            LEFT JOIN sms_countries c ON o.country_id = c.id
            LEFT JOIN sms_services s ON o.service_id = s.id
            WHERE 1=1 $searchWhere
            ORDER BY o.created_at DESC
            LIMIT $perPage OFFSET $offset";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($searchParams);
    $orders = $stmt->fetchAll();
    
    $countSql = "SELECT COUNT(*) FROM sms_orders o LEFT JOIN users u ON o.user_id = u.id WHERE 1=1 $searchWhere";
    $stmt = $pdo->prepare($countSql);
    $stmt->execute($searchParams);
    $total = $stmt->fetchColumn();
} else {
    // Get SMM orders
    $sql = "SELECT o.*, u.name as user_name, u.email as user_email, s.custom_name as service_name
            FROM smm_orders o
            LEFT JOIN users u ON o.user_id = u.id
            LEFT JOIN smm_services s ON o.service_id = s.id
            WHERE 1=1 $searchWhere
            ORDER BY o.created_at DESC
            LIMIT $perPage OFFSET $offset";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($searchParams);
    $orders = $stmt->fetchAll();
    
    $countSql = "SELECT COUNT(*) FROM smm_orders o LEFT JOIN users u ON o.user_id = u.id WHERE 1=1 $searchWhere";
    $stmt = $pdo->prepare($countSql);
    $stmt->execute($searchParams);
    $total = $stmt->fetchColumn();
}

$totalPages = ceil($total / $perPage);

// Status config
$statusConfig = [
    'completed' => ['color' => '#10B981', 'bg' => 'rgba(16,185,129,0.2)'],
    'received' => ['color' => '#10B981', 'bg' => 'rgba(16,185,129,0.2)'],
    'processing' => ['color' => '#3B82F6', 'bg' => 'rgba(59,130,246,0.2)'],
    'in_progress' => ['color' => '#3B82F6', 'bg' => 'rgba(59,130,246,0.2)'],
    'pending' => ['color' => '#F5A623', 'bg' => 'rgba(245,166,35,0.2)'],
    'waiting' => ['color' => '#F5A623', 'bg' => 'rgba(245,166,35,0.2)'],
    'cancelled' => ['color' => '#EF4444', 'bg' => 'rgba(239,68,68,0.2)'],
    'expired' => ['color' => '#EF4444', 'bg' => 'rgba(239,68,68,0.2)'],
    'refunded' => ['color' => '#8B5CF6', 'bg' => 'rgba(139,92,246,0.2)'],
    'partial' => ['color' => '#F59E0B', 'bg' => 'rgba(245,158,11,0.2)'],
];

$isAdmin = $_SESSION['role'] === 'admin';
?>
<!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">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #0A1628; color: #fff; min-height: 100vh; display: flex; }
        
        .sidebar { width: 260px; background: #0F2744; height: 100vh; position: fixed; left: 0; top: 0; z-index: 100; display: flex; flex-direction: column; transition: transform 0.3s; }
        .sidebar-header { padding: 1.5rem; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #1E3A5F; }
        .sidebar-header i { font-size: 1.5rem; color: #F5A623; }
        .sidebar-header span { font-weight: 700; color: #F5A623; font-size: 1.25rem; }
        .sidebar-nav { flex: 1; padding: 1rem 0; overflow-y: auto; }
        .nav-link { display: flex; align-items: center; gap: 12px; padding: 0.875rem 1.5rem; color: #E5E7EB; text-decoration: none; border-left: 3px solid transparent; }
        .nav-link:hover, .nav-link.active { background: #1E3A5F; color: #F5A623; border-left-color: #F5A623; }
        .nav-link i { width: 20px; text-align: center; }
        .nav-divider { height: 1px; background: #1E3A5F; margin: 0.75rem 1.5rem; }
        
        .main { flex: 1; margin-left: 260px; min-height: 100vh; display: flex; flex-direction: column; }
        .header { background: #0F2744; padding: 1rem 1.5rem; display: flex; align-items: center; justify-content: space-between; position: sticky; top: 0; z-index: 50; }
        .header-toggle { background: none; border: none; color: #fff; font-size: 1.25rem; cursor: pointer; display: none; }
        .header-user { display: flex; align-items: center; gap: 0.75rem; }
        .header-user i { color: #F5A623; }
        
        .content { flex: 1; padding: 1.5rem; }
        .page-title { font-size: 1.5rem; margin-bottom: 1.5rem; }
        .page-title i { color: #F5A623; margin-right: 0.5rem; }
        
        .stats-row { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
        .stat-box { background: #0F2744; padding: 1rem 1.5rem; border-radius: 10px; display: flex; align-items: center; gap: 1rem; }
        .stat-box i { font-size: 1.5rem; color: #F5A623; }
        .stat-box h4 { font-size: 1.25rem; margin: 0; }
        .stat-box p { margin: 0; color: #9CA3AF; font-size: 0.8rem; }
        
        .controls { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; align-items: center; }
        
        .tab-btns { display: flex; gap: 0.5rem; }
        .tab-btn { padding: 0.75rem 1.5rem; background: #0F2744; border: 1px solid #1E3A5F; border-radius: 8px; color: #9CA3AF; text-decoration: none; font-weight: 600; display: flex; align-items: center; gap: 0.5rem; }
        .tab-btn:hover, .tab-btn.active { background: #F5A623; color: #0A1628; border-color: #F5A623; }
        .tab-count { background: rgba(0,0,0,0.2); padding: 0.15rem 0.5rem; border-radius: 10px; font-size: 0.75rem; }
        
        .search-box { display: flex; gap: 0.5rem; flex: 1; max-width: 300px; }
        .search-box input { flex: 1; padding: 0.75rem 1rem; background: #0F2744; border: 1px solid #1E3A5F; border-radius: 8px; color: #fff; }
        .search-box input:focus { outline: none; border-color: #F5A623; }
        .search-box button { padding: 0.75rem 1rem; background: #F5A623; border: none; border-radius: 8px; color: #0A1628; cursor: pointer; }
        
        .card { background: #0F2744; border-radius: 12px; overflow: hidden; }
        
        .table-wrapper { overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; min-width: 800px; }
        th, td { padding: 1rem; text-align: left; border-bottom: 1px solid #1E3A5F; }
        th { background: #1E3A5F; font-weight: 600; font-size: 0.8rem; color: #9CA3AF; text-transform: uppercase; }
        td { font-size: 0.9rem; }
        tr:hover { background: rgba(245,166,35,0.05); }
        
        .user-info .name { font-weight: 600; }
        .user-info .email { font-size: 0.8rem; color: #9CA3AF; }
        
        .service-name { max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        
        .status { padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; display: inline-block; }
        
        .amount { font-weight: 700; color: #F5A623; }
        
        .link-cell { max-width: 150px; }
        .link-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block; color: #3B82F6; font-size: 0.8rem; }
        
        .phone { font-family: monospace; color: #3B82F6; }
        .code { font-family: monospace; color: #10B981; font-weight: 700; }
        
        .empty { text-align: center; padding: 3rem; color: #9CA3AF; }
        .empty i { font-size: 3rem; margin-bottom: 1rem; display: block; color: #1E3A5F; }
        
        .pagination { display: flex; justify-content: center; gap: 0.5rem; padding: 1.5rem; }
        .pagination a, .pagination span { padding: 0.5rem 1rem; background: #1E3A5F; border-radius: 8px; color: #fff; text-decoration: none; }
        .pagination a:hover { background: #F5A623; color: #0A1628; }
        .pagination .current { background: #F5A623; color: #0A1628; }
        
        .menu-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 99; display: none; }
        .menu-overlay.active { display: block; }
        
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-260px); }
            .sidebar.active { transform: translateX(0); }
            .main { margin-left: 0; }
            .header-toggle { display: block; }
            .controls { flex-direction: column; align-items: stretch; }
            .search-box { max-width: 100%; }
        }
    </style>
</head>
<body>
    <div class="menu-overlay" id="menuOverlay" onclick="toggleSidebar()"></div>
    
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header"><i class="fas fa-feather-alt"></i><span><?php echo SITE_NAME; ?></span></div>
        <nav class="sidebar-nav">
            <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
            <a href="users.php" class="nav-link"><i class="fas fa-users"></i> Users</a>
            <a href="orders.php" class="nav-link active"><i class="fas fa-shopping-cart"></i> Orders</a>
            <a href="fund-requests.php" class="nav-link"><i class="fas fa-money-bill"></i> Fund Requests</a>
            <a href="deposits.php" class="nav-link"><i class="fas fa-coins"></i> Deposit History</a>
            <div class="nav-divider"></div>
            <a href="smm-services.php" class="nav-link"><i class="fas fa-rocket"></i> SMM Services</a>
            <a href="sms-services.php" class="nav-link"><i class="fas fa-sms"></i> SMS Services</a>
            <div class="nav-divider"></div>
            <a href="banners.php" class="nav-link"><i class="fas fa-ad"></i> Banners</a>
            <a href="offers.php" class="nav-link"><i class="fas fa-tags"></i> Offers</a>
            <a href="support.php" class="nav-link"><i class="fas fa-headset"></i> Support</a>
            <?php if ($isAdmin): ?>
            <div class="nav-divider"></div>
            <a href="settings.php" class="nav-link"><i class="fas fa-cog"></i> Settings</a>
            <?php endif; ?>
            <div class="nav-divider"></div>
            <a href="<?php echo SITE_URL; ?>/logout.php" class="nav-link"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </nav>
    </aside>
    
    <main class="main">
        <header class="header">
            <button class="header-toggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
            <div class="header-user"><i class="fas fa-user-shield"></i> <span><?php echo htmlspecialchars($_SESSION['name']); ?></span></div>
        </header>
        
        <div class="content">
            <h1 class="page-title"><i class="fas fa-shopping-cart"></i> Orders</h1>
            
            <div class="stats-row">
                <div class="stat-box">
                    <i class="fas fa-rocket"></i>
                    <div>
                        <h4><?php echo number_format($smmTotal); ?></h4>
                        <p>SMM Orders</p>
                    </div>
                </div>
                <div class="stat-box">
                    <i class="fas fa-sms"></i>
                    <div>
                        <h4><?php echo number_format($smsTotal); ?></h4>
                        <p>SMS Orders</p>
                    </div>
                </div>
            </div>
            
            <div class="controls">
                <div class="tab-btns">
                    <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 $smmTotal; ?></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 $smsTotal; ?></span>
                    </a>
                </div>
                
                <form class="search-box" method="GET">
                    <input type="hidden" name="tab" value="<?php echo $tab; ?>">
                    <input type="text" name="search" placeholder="Search by user or ID..." value="<?php echo htmlspecialchars($search); ?>">
                    <button type="submit"><i class="fas fa-search"></i></button>
                </form>
            </div>
            
            <div class="card">
                <?php if (empty($orders)): ?>
                <div class="empty">
                    <i class="fas fa-<?php echo $tab === 'sms' ? 'sms' : 'rocket'; ?>"></i>
                    <h3>No <?php echo strtoupper($tab); ?> orders found</h3>
                    <p>Orders will appear here when users place them.</p>
                </div>
                <?php else: ?>
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>User</th>
                                <th>Service</th>
                                <?php if ($tab === 'smm'): ?>
                                <th>Link</th>
                                <th>Quantity</th>
                                <?php else: ?>
                                <th>Phone</th>
                                <th>Code</th>
                                <?php endif; ?>
                                <th>Amount</th>
                                <th>Status</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($orders as $order): 
                                $status = $order['status'];
                                $config = $statusConfig[$status] ?? ['color' => '#9CA3AF', 'bg' => 'rgba(156,163,175,0.2)'];
                            ?>
                            <tr>
                                <td>#<?php echo $order['id']; ?></td>
                                <td>
                                    <div class="user-info">
                                        <div class="name"><?php echo htmlspecialchars($order['user_name'] ?? 'Unknown'); ?></div>
                                        <div class="email"><?php echo htmlspecialchars($order['user_email'] ?? ''); ?></div>
                                    </div>
                                </td>
                                <td>
                                    <div class="service-name" title="<?php echo htmlspecialchars($order['service_name'] ?? ''); ?>">
                                        <?php echo htmlspecialchars($order['service_name'] ?? 'Service #' . ($order['service_id'] ?? '')); ?>
                                    </div>
                                </td>
                                <?php if ($tab === 'smm'): ?>
                                <td class="link-cell">
                                    <a href="<?php echo htmlspecialchars($order['link'] ?? '#'); ?>" target="_blank" class="link-text">
                                        <?php echo htmlspecialchars($order['link'] ?? '-'); ?>
                                    </a>
                                </td>
                                <td><?php echo number_format($order['quantity'] ?? 0); ?></td>
                                <?php else: ?>
                                <td class="phone"><?php echo htmlspecialchars($order['phone_number'] ?? '-'); ?></td>
                                <td class="code"><?php echo htmlspecialchars($order['sms_code'] ?? '-'); ?></td>
                                <?php endif; ?>
                                <td class="amount"><?php echo formatCurrency($order['charge'] ?? 0); ?></td>
                                <td>
                                    <span class="status" style="background: <?php echo $config['bg']; ?>; color: <?php echo $config['color']; ?>;">
                                        <?php echo ucfirst(str_replace('_', ' ', $status)); ?>
                                    </span>
                                </td>
                                <td style="color: #9CA3AF; font-size: 0.85rem; white-space: nowrap;">
                                    <?php echo date('M j, Y', strtotime($order['created_at'])); ?><br>
                                    <small><?php echo date('g:i A', strtotime($order['created_at'])); ?></small>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if ($totalPages > 1): ?>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                    <a href="?tab=<?php echo $tab; ?>&search=<?php echo urlencode($search); ?>&page=<?php echo $page - 1; ?>"><i class="fas fa-chevron-left"></i></a>
                    <?php endif; ?>
                    <span class="current"><?php echo $page; ?> / <?php echo $totalPages; ?></span>
                    <?php if ($page < $totalPages): ?>
                    <a href="?tab=<?php echo $tab; ?>&search=<?php echo urlencode($search); ?>&page=<?php echo $page + 1; ?>"><i class="fas fa-chevron-right"></i></a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </main>
    
    <script>function toggleSidebar() { document.getElementById('sidebar').classList.toggle('active'); document.getElementById('menuOverlay').classList.toggle('active'); }</script>
</body>
</html>