<?php
session_start();
if (!isset($_SESSION['username'])) {
    $_SESSION['username'] = "Guest"; 
}

include 'includes/header.php';
include 'includes/admin-sidebar.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'config.php'; 

// Restrict access to only Super-Admins
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'super-admin') {
    die("Access Denied: You are not authorized to view this page.");
}

$user_id = $_SESSION['user_id'];
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Fetch Super-Admin info
$stmt = $conn->prepare("SELECT username, balance FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
$username = htmlspecialchars($user['username']);

// Deposit stats
$stmt = $conn->prepare("SELECT COUNT(*) AS total, SUM(amount) AS total_deposit FROM tbl_deposits");
$stmt->execute();
$deposit_stats = $stmt->get_result()->fetch_assoc();
$stmt->close();
$total_deposit_transactions = $deposit_stats['total'];
$total_deposit = $deposit_stats['total_deposit'] ?? 0;

// Withdrawal stats
$stmt = $conn->prepare("SELECT COUNT(*) AS total, SUM(amount) AS total_withdrawal FROM tbl_withdrawals");
$stmt->execute();
$withdraw_stats = $stmt->get_result()->fetch_assoc();
$stmt->close();
$total_withdrawal_transactions = $withdraw_stats['total'];
$total_withdrawal = $withdraw_stats['total_withdrawal'] ?? 0;

// Transfer stats
$stmt = $conn->prepare("SELECT COUNT(*) AS total FROM tbl_transfers");
$stmt->execute();
$transfer_stats = $stmt->get_result()->fetch_assoc();
$stmt->close();
$total_transfer_transactions = $transfer_stats['total'];

// Get all transactions (Deposits, Withdrawals, Transfers Sent & Received)
$query = "
    SELECT 'Deposit' AS type, d.amount, d.status, d.created_at, u.username 
    FROM tbl_deposits d
    JOIN users u ON d.user_id = u.id
    UNION ALL
    SELECT 'Withdrawal' AS type, w.amount, w.status, w.created_at, u.username 
    FROM tbl_withdrawals w
    JOIN users u ON w.user_id = u.id
    UNION ALL
    SELECT 'Transfer (Sent)' AS type, t.amount, 'Sent' AS status, t.created_at, sender.username 
    FROM tbl_transfers t
    JOIN users sender ON t.sender_id = sender.id
    UNION ALL
    SELECT 'Transfer (Received)' AS type, t.amount, 'Received' AS status, t.created_at, recipient.username 
    FROM tbl_transfers t
    JOIN users recipient ON t.recipient_id = recipient.id
    ORDER BY created_at DESC
    LIMIT ? OFFSET ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$transactions = $stmt->get_result();

// Count total records for pagination
$stmt = $conn->prepare("
    SELECT COUNT(*) AS total FROM (
        SELECT id FROM tbl_deposits
        UNION ALL
        SELECT id FROM tbl_withdrawals
        UNION ALL
        SELECT id FROM tbl_transfers
        UNION ALL
        SELECT id FROM tbl_transfers
    ) AS combined");
$stmt->execute();
$total_records = $stmt->get_result()->fetch_assoc()['total'];
$stmt->close();
$total_pages = ceil($total_records / $limit);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Super-Admin Dashboard</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="includes/css/style.css">
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-10 content">
            <!-- Header Section -->
            <div class="row">
                <div class="col-md-4">
                    <div class="card card deposit p-3">
                        <h5>Deposits</h5>
                        <h3>GHS <?php echo number_format($total_deposit, 2); ?></h3>
                        <p><?php echo $total_deposit_transactions; ?> Transactions</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card withdraw p-3">
                        <h5>Withdrawals</h5>
                        <h3>GHS <?php echo number_format($total_withdrawal, 2); ?></h3>
                        <p><?php echo $total_withdrawal_transactions; ?> Transactions</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card balance p-3">
                        <h5>Total Balance</h5>
                        <h3>GHS <?php echo number_format($user['balance'], 2); ?></h3>
                    </div>
                </div>
            </div>
            
            <h4 class="mt-4">Deposits & Withdrawals Chart</h4>
            <canvas id="transactionsChart"></canvas>
<!-- Transaction History -->
<h4 class="mt-4">Transaction History</h4>
<div class="table-responsive">
    <table class="table table-bordered">
        <thead>
            <tr><th>Date</th><th>User</th><th>Type</th><th>Amount</th><th>Status</th></tr>
        </thead>
        <tbody>
            <?php while ($row = $transactions->fetch_assoc()): ?>
                <tr>
                    <td><?php echo $row['created_at']; ?></td>
                    <td><?php echo htmlspecialchars($row['username']); ?></td>
                    <td>
                        <span class="btn 
                            <?php 
                                echo ($row['type'] == 'Deposit') ? 'btn-success' : 
                                     (($row['type'] == 'Withdrawal') ? 'btn-danger' : 
                                     (strpos($row['type'], 'Sent') !== false ? 'btn-warning' : 'btn-info')); 
                            ?> btn-sm">
                            <?php echo $row['type']; ?>
                        </span>
                    </td>
                    <td>GHS <?php echo number_format($row['amount'], 2); ?></td>
                    <td><?php echo ucfirst($row['status']); ?></td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<!-- Pagination -->
<div class="pagination">
    <!-- Previous Button -->
    <?php if ($page > 1): ?>
        <a href="?page=<?php echo $page - 1; ?>" class="btn btn-primary mx-1">Previous</a>
    <?php else: ?>
        <span class="btn btn-secondary mx-1" disabled>Previous</span>
    <?php endif; ?>

    <!-- Pagination Numbers (1 to 6) -->
    <?php 
        $start = 1;
        $end = min(6, $total_pages);  // Show pages from 1 to 6, or as many as the total pages
        for ($i = $start; $i <= $end; $i++): 
    ?>
        <a href="?page=<?php echo $i; ?>" class="btn btn-primary mx-1 <?php echo ($i == $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
    <?php endfor; ?>

    <!-- Next Button -->
    <?php if ($page < $total_pages): ?>
        <a href="?page=<?php echo $page + 1; ?>" class="btn btn-primary mx-1">Next</a>
    <?php else: ?>
        <span class="btn btn-secondary mx-1" disabled>Next</span>
    <?php endif; ?>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const ctx = document.getElementById("transactionsChart").getContext("2d");

    const transactionsChart = new Chart(ctx, {
        type: "line",
        data: {
            labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            datasets: [
                {
                    label: "Deposits (GHS)",
                    data: [0, 0, 0, <?php echo $total_deposit; ?>, 1200, 700, 1100, 1300, 900, 950, 850, 1000],
                    borderColor: "#007bff",
                    backgroundColor: "rgba(0,123,255,0.2)",
                    fill: true,
                    tension: 0.4,
                    pointRadius: 0,
                    pointHoverRadius: 6,
                    pointBackgroundColor: "#007bff",
                },
                {
                    label: "Withdrawals (GHS)",
                    data: [0, 0, 0, <?php echo $total_withdrawal; ?>, 800, 600, 900, 1100, 950, 900, 850, 950],
                    borderColor: "#dc3545",
                    backgroundColor: "rgba(220,53,69,0.2)",
                    fill: true,
                    tension: 0.4,
                    pointRadius: 0,
                    pointHoverRadius: 6,
                    pointBackgroundColor: "#dc3545",
                }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                tooltip: {
                    enabled: true,
                    mode: "nearest",
                    intersect: false
                }
            },
            scales: {
                x: { grid: { display: false } },
                y: { beginAtZero: true }
            }
        }
    });
});
</script>



<script src="includes/js/notifications.js"></script>
</body>
</html>
