<?php
require_once '../includes/config.php';
requireAdmin();
$db = getDB();

$stats = [
    'total_users'     => $db->query("SELECT COUNT(*) FROM users WHERE role='user'")->fetchColumn(),
    'total_resellers' => $db->query("SELECT COUNT(*) FROM users WHERE role='reseller'")->fetchColumn(),
    'today_txn'       => $db->query("SELECT COUNT(*) FROM transactions WHERE DATE(created_at)=CURDATE()")->fetchColumn(),
    'today_revenue'   => $db->query("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE DATE(created_at)=CURDATE() AND status='success'")->fetchColumn(),
    'total_revenue'   => $db->query("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE status='success'")->fetchColumn(),
    'pending_deposits'=> $db->query("SELECT COUNT(*) FROM deposits WHERE status='pending'")->fetchColumn(),
];
$recent_txns      = $db->query("SELECT t.*, u.name, u.username, o.name as op_name FROM transactions t LEFT JOIN users u ON t.user_id=u.id LEFT JOIN operators o ON t.operator_id=o.id ORDER BY t.created_at DESC LIMIT 10")->fetchAll();
$pending_deposits = $db->query("SELECT d.*, u.name, u.username FROM deposits d JOIN users u ON d.user_id=u.id WHERE d.status='pending' ORDER BY d.created_at DESC LIMIT 5")->fetchAll();
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Admin Panel</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/admin.css">
    <style>
        .dep-item{padding:14px 0;border-bottom:1px solid #f0f0f0;display:flex;align-items:center;gap:12px}
        .dep-item:last-child{border:none}
        .dep-amt{font-size:16px;font-weight:800;color:var(--primary);white-space:nowrap}
        .dep-btns{display:flex;gap:6px;flex-shrink:0}
    </style>
</head>
<body>

<?php include '../includes/admin_sidebar.php'; ?>

<div class="main">
    <!-- Topbar -->
    <div class="topbar">
        <div class="topbar-left">
            <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
            <h1>Dashboard</h1>
        </div>
        <div class="topbar-right">
            <span class="topbar-date"><?= date('d M Y, h:i A') ?></span>
            <span class="admin-badge"><i class="fas fa-user-shield"></i> <?= htmlspecialchars($_SESSION['name']) ?></span>
        </div>
    </div>

    <div class="content">
        <!-- Stats Grid -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon blue"><i class="fas fa-users"></i></div>
                <div class="stat-info"><h3><?= $stats['total_users'] ?></h3><p>মোট ইউজার</p></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon yellow"><i class="fas fa-user-tie"></i></div>
                <div class="stat-info"><h3><?= $stats['total_resellers'] ?></h3><p>মোট রিসেলার</p></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon green"><i class="fas fa-exchange-alt"></i></div>
                <div class="stat-info"><h3><?= $stats['today_txn'] ?></h3><p>আজকের লেনদেন</p></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon green"><i class="fas fa-taka-sign"></i></div>
                <div class="stat-info"><h3><?= CURRENCY ?><?= number_format($stats['today_revenue'],0) ?></h3><p>আজকের আয়</p></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon blue"><i class="fas fa-chart-line"></i></div>
                <div class="stat-info"><h3><?= CURRENCY ?><?= number_format($stats['total_revenue'],0) ?></h3><p>মোট আয়</p></div>
            </div>
            <div class="stat-card" onclick="loadApiBalance()" style="cursor:pointer" title="ক্লিক করুন">
                <div class="stat-icon red"><i class="fas fa-satellite-dish"></i></div>
                <div class="stat-info">
                    <h3 id="apiBalDisplay" style="font-size:16px"><?= getSetting('successtopup_key') ? 'লোড করুন' : 'N/A' ?></h3>
                    <p>API Balance <small>(ক্লিক)</small></p>
                </div>
            </div>
        </div>

        <!-- Row -->
        <div class="row">
            <!-- Recent Transactions -->
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-exchange-alt"></i> সাম্প্রতিক লেনদেন</h3>
                    <a href="transactions.php" class="view-all">সব দেখুন →</a>
                </div>
                <div class="table-responsive">
                    <table>
                        <thead><tr><th>ইউজার</th><th>ফোন</th><th>পরিমাণ</th><th>অপারেটর</th><th>স্ট্যাটাস</th></tr></thead>
                        <tbody>
                        <?php foreach($recent_txns as $t): ?>
                        <tr>
                            <td><div class="user-info"><strong><?= htmlspecialchars($t['name']??'-') ?></strong><small>@<?= $t['username']??'' ?></small></div></td>
                            <td style="font-family:monospace;font-size:12px"><?= $t['phone_number']??'-' ?></td>
                            <td><strong><?= CURRENCY ?><?= number_format($t['amount'],2) ?></strong></td>
                            <td><?= $t['op_name']??ucfirst($t['type']) ?></td>
                            <td><span class="badge badge-<?= $t['status'] ?>"><?= ucfirst($t['status']) ?></span></td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Pending Deposits -->
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-plus-circle"></i> অপেক্ষারত ডিপোজিট</h3>
                    <a href="deposits.php" class="view-all">সব দেখুন →</a>
                </div>
                <?php if(empty($pending_deposits)): ?>
                <div class="empty"><i class="fas fa-check-circle" style="color:#38a169"></i>কোনো অপেক্ষারত ডিপোজিট নেই</div>
                <?php else: ?>
                <?php foreach($pending_deposits as $d): ?>
                <div class="dep-item">
                    <div style="flex:1;min-width:0">
                        <div class="dep-info"><h4><?= htmlspecialchars($d['name']) ?></h4><p><?= strtoupper($d['method']) ?> &bull; <?= date('d M, h:i A', strtotime($d['created_at'])) ?></p></div>
                    </div>
                    <span class="dep-amt"><?= CURRENCY ?><?= number_format($d['amount'],2) ?></span>
                    <div class="dep-btns">
                        <button class="btn-approve" onclick="approveDeposit(<?= $d['id'] ?>)"><i class="fas fa-check"></i></button>
                        <button class="btn-reject" onclick="rejectDeposit(<?= $d['id'] ?>)"><i class="fas fa-times"></i></button>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function approveDeposit(id){
    if(!confirm('অনুমোদন করবেন?'))return;
    fetch('ajax/deposit.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'approve',id})})
    .then(r=>r.json()).then(d=>{if(d.success)location.reload();else alert(d.message);});
}
function rejectDeposit(id){
    const note=prompt('প্রত্যাখ্যানের কারণ:');
    if(note===null)return;
    fetch('ajax/deposit.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'reject',id,note})})
    .then(r=>r.json()).then(d=>{if(d.success)location.reload();else alert(d.message);});
}
function loadApiBalance(){
    const el=document.getElementById('apiBalDisplay');
    el.textContent='লোড হচ্ছে...';el.style.fontSize='13px';
    fetch('ajax/check_api_balance.php').then(r=>r.json()).then(d=>{
        el.textContent=d.success?d.message.replace('✅ API Balance: ',''):'❌ Error';
        el.style.fontSize='13px';
    }).catch(()=>{el.textContent='❌ Failed';});
}
</script>
</body>
</html>
