<?php
// FILE: public_html/Nag/dashboard.php
session_start();
require_once '../db.php'; 

// 1. ADMIN SESSION CHECK
if (!isset($_SESSION['admin_id'])) { 
    header("Location: index.php"); 
    exit(); 
}

$admin_id = $_SESSION['admin_id'];

// 2. FETCH ADMIN DETAILS
$stmt = $conn->prepare("SELECT * FROM admins WHERE id = ?");
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows > 0) {
    $admin = $res->fetch_assoc();
    $first_name = !empty($admin['name']) ? $admin['name'] : 'Admin'; 
    $username   = !empty($admin['username']) ? $admin['username'] : 'Administrator';
} else {
    $first_name = 'Admin';
    $username = 'Administrator';
}

// --- HELPER: Safe Query ---
function safe_count($conn, $query) {
    try { $res = $conn->query($query); if ($res) return $res->fetch_row()[0]; } catch (Exception $e) { return 0; } return 0;
}

// --- FETCH STATS ---
$total_users = safe_count($conn, "SELECT COUNT(*) FROM users");

// Total Deposited
$total_deposited = 0;
if ($conn->query("SHOW TABLES LIKE 'transactions'")->num_rows > 0) {
    $q_dep = $conn->query("SELECT SUM(amount) FROM transactions WHERE status='success' AND (transaction_type = 'wallet_funding' OR transaction_type = 'credit')");
    $total_deposited = $q_dep->fetch_row()[0] ?? 0;
}

// User Holdings
$user_holdings = 0;
if ($conn->query("SHOW TABLES LIKE 'wallets'")->num_rows > 0) {
    $user_holdings = $conn->query("SELECT SUM(balance) FROM wallets")->fetch_row()[0] ?? 0;
} elseif ($conn->query("SHOW COLUMNS FROM users LIKE 'balance'")->num_rows > 0) {
    $user_holdings = $conn->query("SELECT SUM(balance) FROM users")->fetch_row()[0] ?? 0;
}

$pending_api = safe_count($conn, "SELECT COUNT(*) FROM users WHERE api_status = 'pending'");
$open_tickets = ($conn->query("SHOW TABLES LIKE 'support_tickets'")->num_rows > 0) ? safe_count($conn, "SELECT COUNT(*) FROM support_tickets WHERE status = 'open'") : 0;

// --- FETCH LISTS ---
$api_reqs = $conn->query("SELECT id, first_name, last_name, email FROM users WHERE api_status = 'pending'");

$tickets = false;
if ($conn->query("SHOW TABLES LIKE 'support_tickets'")->num_rows > 0) {
    $tickets = $conn->query("SELECT t.*, u.first_name, u.last_name, u.email FROM support_tickets t JOIN users u ON t.user_id = u.id WHERE t.status = 'open' ORDER BY t.created_at DESC LIMIT 5");
}

$txns = false;
if ($conn->query("SHOW TABLES LIKE 'transactions'")->num_rows > 0) {
    $txns = $conn->query("SELECT t.*, u.username FROM transactions t LEFT JOIN users u ON t.user_id = u.id ORDER BY t.created_at DESC LIMIT 10");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</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=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #2c5364; --secondary: #203a43; --bg: #f4f7f6; --text: #334155; --white: #ffffff; --sidebar-width: 260px; }
        * { margin:0; padding:0; box-sizing:border-box; }
        body { font-family:'Poppins', sans-serif; background:var(--bg); color:var(--text); display:flex; min-height:100vh; }
        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, var(--secondary) 0%, var(--primary) 100%); color:white; display:flex; flex-direction:column; position: fixed; height: 100%; z-index: 1000; left: 0; }
        .brand { padding:25px; text-align:center; border-bottom:1px solid rgba(255,255,255,0.1); }
        .brand img { max-height: 45px; }
        .nav { padding:20px; flex:1; }
        .nav a { display:flex; align-items:center; color:rgba(255,255,255,0.7); padding:12px 15px; text-decoration:none; margin-bottom:5px; border-radius:12px; transition:0.2s; }
        .nav a:hover, .nav a.active { background:white; color:var(--primary); font-weight:600; }
        .nav i { width:30px; text-align:center; }
        .main { flex:1; margin-left: var(--sidebar-width); padding: 25px; width: calc(100% - var(--sidebar-width)); }
        .header { display:flex; justify-content:space-between; align-items:center; background:white; padding:15px 20px; border-radius:15px; box-shadow:0 5px 20px rgba(0,0,0,0.03); margin-bottom:25px; }
        .grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(220px, 1fr)); gap:20px; margin-bottom:30px; }
        .card { background:white; padding:20px; border-radius:16px; box-shadow:0 10px 30px rgba(0,0,0,0.04); transition:0.3s; }
        .card:hover { transform:translateY(-5px); }
        .card-icon { width:50px; height:50px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-size:1.4rem; margin-bottom:15px; }
        .card h3 { margin:0 0 5px; color:#64748b; font-size:0.85rem; text-transform:uppercase; }
        .card .num { font-size:1.6rem; font-weight:700; color:var(--primary); }
        .section { background:white; border-radius:16px; padding:20px; margin-bottom:30px; box-shadow:0 10px 30px rgba(0,0,0,0.04); }
        .section-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; padding-bottom:15px; border-bottom:1px solid #e2e8f0; }
        table { width:100%; border-collapse:collapse; }
        th, td { padding:15px; text-align:left; border-bottom:1px solid #f1f5f9; font-size:0.9rem; }
        th { background:#f8fafc; color:#64748b; font-weight:600; font-size:0.8rem; }
        .badge { padding:5px 10px; border-radius:20px; font-size:0.75rem; font-weight:600; }
        .badge-success { background:#dcfce7; color:#166534; }
        .badge-warning { background:#fff7ed; color:#c2410c; }
        .btn { padding:8px 15px; border:none; border-radius:8px; cursor:pointer; font-size:0.85rem; color:white; }
        .btn-green { background:#10b981; } .btn-blue { background:var(--primary); }
    </style>
</head>
<body>

<div class="sidebar">
    <div class="brand"><img src="../assets/images/logo.png" alt="Logo"></div>
    <div class="nav">
        <a href="dashboard.php" class="active"><i class="fas fa-home"></i> Dashboard</a>
        <a href="users.php"><i class="fas fa-users"></i> Users</a>
        <a href="transactions.php"><i class="fas fa-chart-line"></i> Transactions</a>
        <a href="credit_user.php"><i class="fas fa-wallet"></i> Credit User</a>
        <a href="admin_data_plans.php"><i class="fas fa-wifi"></i> Data Plans</a>
        <a href="notifications.php"><i class="fas fa-bell"></i> Notifications</a>
        <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
        <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
</div>

<div class="main">
    <div class="header">
        <div>
            <h2 style="color:var(--primary); margin:0;">Hi, <?php echo htmlspecialchars($first_name); ?></h2>
            <small>Admin Overview</small>
        </div>
        <div style="width:40px; height:40px; background:var(--primary); color:white; border-radius:50%; display:flex; align-items:center; justify-content:center; font-weight:bold;">
            <?php echo strtoupper(substr($first_name, 0, 1)); ?>
        </div>
    </div>

    <div class="grid">
        <div class="card">
            <div class="card-icon" style="background:#dcfce7; color:#166534;"><i class="fas fa-coins"></i></div>
            <h3>Deposits</h3>
            <div class="num">₦<?php echo number_format($total_deposited, 2); ?></div>
        </div>
        <div class="card">
            <div class="card-icon" style="background:#fff7ed; color:#c2410c;"><i class="fas fa-wallet"></i></div>
            <h3>Holdings</h3>
            <div class="num">₦<?php echo number_format($user_holdings, 2); ?></div>
        </div>
        <div class="card">
            <div class="card-icon" style="background:#e0f2fe; color:#0284c7;"><i class="fas fa-users"></i></div>
            <h3>Users</h3>
            <div class="num"><?php echo $total_users; ?></div>
        </div>
        <div class="card">
            <div class="card-icon" style="background:#fae8ff; color:#86198f;"><i class="fas fa-headset"></i></div>
            <h3>Support</h3>
            <div class="num"><?php echo $open_tickets; ?></div>
        </div>
    </div>

    <?php if($api_reqs && $api_reqs->num_rows > 0): ?>
    <div class="section">
        <div class="section-header"><h3>Pending API Requests</h3></div>
        <div class="table-responsive">
            <table>
                <thead><tr><th>User</th><th>Email</th><th>Action</th></tr></thead>
                <tbody>
                    <?php while($u = $api_reqs->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo $u['first_name']; ?></td>
                        <td><?php echo $u['email']; ?></td>
                        <td><button class="btn btn-green" onclick="approveApi(<?php echo $u['id']; ?>)">Approve</button></td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <div class="section">
        <div class="section-header"><h3>Recent Transactions</h3></div>
        <div class="table-responsive">
            <table>
                <thead><tr><th>User</th><th>Reference</th><th>Amount</th><th>Status</th></tr></thead>
                <tbody>
                    <?php if($txns && $txns->num_rows > 0): ?>
                        <?php while($txn = $txns->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $txn['username'] ?? 'Deleted User'; ?></td>
                            <td style="font-family:monospace; color:#64748b;"><?php echo substr((string)$txn['reference'], 0, 15) . '...'; ?></td>
                            <td style="font-weight:700;">₦<?php echo number_format($txn['amount'], 2); ?></td>
                            <td><span class="badge badge-<?php echo $txn['status']=='success'?'success':'warning'; ?>"><?php echo ucfirst($txn['status']); ?></span></td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="4" style="text-align:center; padding:20px;">No transactions found</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    function approveApi(id) {
        if(confirm("Are you sure you want to approve API Access for this user?")) {
            let formData = new FormData();
            formData.append('user_id', id);

            // Correct Path: ../api/admin_approve_api.php
            fetch('../api/admin_approve_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if(data.status === 'success') {
                    location.reload();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Connection error');
            });
        }
    }
</script>

</body>
</html>