<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include("check_installation.php");
include("fetch_settings.php");

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $deleteId = intval($_POST['delete_id']);
    $stmt = $con->prepare("DELETE FROM customers WHERE customerid = ?");
    $stmt->bind_param("i", $deleteId);
    $stmt->execute();
    $stmt->close();
    $deleteSuccess = true;
}

// Total Users
$stmt = $con->prepare("SELECT COUNT(*) FROM customers");
$stmt->execute();
$stmt->bind_result($totalUsers);
$stmt->fetch();
$stmt->close();

$stmt = $con->prepare("SELECT COUNT(*) FROM customers WHERE accopendate < DATE_FORMAT(CURDATE(), '%Y-%m-01')");
$stmt->execute();
$stmt->bind_result($prevUsers);
$stmt->fetch();
$stmt->close();
$growthUsers = $prevUsers > 0 ? (($totalUsers - $prevUsers) / $prevUsers) * 100 : 0;

// Active Sessions
$stmt = $con->prepare("SELECT COUNT(*) FROM customers WHERE DATE(lastlogin) = CURDATE()");
$stmt->execute();
$stmt->bind_result($activeSessions);
$stmt->fetch();
$stmt->close();

// Revenue
$stmt = $con->prepare("SELECT IFNULL(SUM(amount),0) FROM transactions WHERE DATE_FORMAT(paymentdate, '%Y-%m') = DATE_FORMAT(CURDATE(), '%Y-%m')");
$stmt->execute();
$stmt->bind_result($totalRevenue);
$stmt->fetch();
$stmt->close();

$stmt = $con->prepare("SELECT IFNULL(SUM(amount),0) FROM transactions WHERE DATE_FORMAT(paymentdate, '%Y-%m') = DATE_FORMAT(CURDATE() - INTERVAL 1 MONTH, '%Y-%m')");
$stmt->execute();
$stmt->bind_result($prevRevenue);
$stmt->fetch();
$stmt->close();
$growthRevenue = $prevRevenue > 0 ? (($totalRevenue - $prevRevenue) / $prevRevenue) * 100 : 0;

// New Signups
$stmt = $con->prepare("SELECT COUNT(*) FROM customers WHERE accopendate >= (NOW() - INTERVAL 1 DAY)");
$stmt->execute();
$stmt->bind_result($newSignups);
$stmt->fetch();
$stmt->close();

// Pagination
$limit = 5; 
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

$stmt = $con->prepare("SELECT COUNT(*) FROM customers");
$stmt->execute();
$stmt->bind_result($totalUsersCount);
$stmt->fetch();
$stmt->close();
$totalPages = ceil($totalUsersCount / $limit);

$recentActivity = [];
$stmt = $con->prepare("SELECT customerid, firstname, lastname, lastlogin FROM customers ORDER BY lastlogin DESC LIMIT ? OFFSET ?");
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $recentActivity[] = $row;
}
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Core Banking Dashboard | Admin</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">

    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap">
    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <style>
        :root {
            --bank-navy: #0f172a;
            --bank-blue: #2563eb;
            --bank-surface: #ffffff;
            --bank-bg: #f8fafc;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--bank-bg);
            color: #1e293b;
        }

        /* Banking Metric Cards */
        .stat-card {
            border: none;
            border-radius: 12px;
            transition: transform 0.2s ease;
            background: var(--bank-surface);
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .icon-box {
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
        }

        /* Activity Table Styling */
        .table-card {
            border: none;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .activity-header {
            background: white;
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
        }

        .user-avatar {
            width: 35px;
            height: 35px;
            background: #e2e8f0;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: #475569;
            font-size: 0.8rem;
        }

        .status-pill {
            padding: 0.25rem 0.75rem;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .btn-action {
            width: 32px;
            height: 32px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
        }

        /* Sidebar & Topbar adjustments for Banking feel */
        .page-content { background: var(--bank-bg); }
        .navbar-top { box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
    </style>
</head>

<body>

<main>
    <?php include "include/sidebar.php" ?>
    
    <div class="page-content">
        <?php include "include/topbar.php" ?>
    
        <div class="page-content-wrapper p-3 p-lg-4">
            
            <div class="row align-items-center mb-4">
                <div class="col-sm-6">
                    <h1 class="h3 fw-bold mb-0">System Overview</h1>
                    <p class="text-muted small mb-0">Real-time analytics and user management portal.</p>
                </div>
                <div class="col-sm-6 text-sm-end mt-3 mt-sm-0">
                    <a href="systemsettings.php" class="btn btn-dark btn-sm rounded-pill px-3">
                        <i class="bi bi-gear-fill me-2"></i>System Settings
                    </a>
                </div>
            </div>

            <div class="row g-4 mb-4">
                <div class="col-md-6 col-xl-3">
                    <div class="card stat-card p-3">
                        <div class="d-flex align-items-center">
                            <div class="icon-box bg-primary bg-opacity-10 text-primary me-3">
                                <i class="bi bi-people-fill fs-5"></i>
                            </div>
                            <div>
                                <small class="text-muted d-block fw-medium">Total Accounts</small>
                                <h4 class="mb-0 fw-bold"><?= number_format($totalUsers) ?></h4>
                            </div>
                        </div>
                        <div class="mt-3 pt-2 border-top">
                            <span class="badge bg-<?= $growthUsers >= 0 ? 'success' : 'danger'; ?>-soft">
                                <i class="bi bi-graph-<?= $growthUsers >= 0 ? 'up' : 'down'; ?> me-1"></i>
                                <?= round($growthUsers, 1); ?>%
                            </span>
                            <small class="text-muted ms-1">vs last month</small>
                        </div>
                    </div>
                </div>

                <div class="col-md-6 col-xl-3">
                    <div class="card stat-card p-3">
                        <div class="d-flex align-items-center">
                            <div class="icon-box bg-info bg-opacity-10 text-info me-3">
                                <i class="bi bi-broadcast fs-5"></i>
                            </div>
                            <div>
                                <small class="text-muted d-block fw-medium">Active Now</small>
                                <h4 class="mb-0 fw-bold"><?= number_format($activeSessions) ?></h4>
                            </div>
                        </div>
                        <div class="mt-3 pt-2 border-top">
                            <span class="small text-success fw-medium"><i class="bi bi-circle-fill me-1 small"></i> System Live</span>
                        </div>
                    </div>
                </div>

                <div class="col-md-6 col-xl-3">
                    <div class="card stat-card p-3">
                        <div class="d-flex align-items-center">
                            <div class="icon-box bg-success bg-opacity-10 text-success me-3">
                                <i class="bi bi-wallet2 fs-5"></i>
                            </div>
                            <div>
                                <small class="text-muted d-block fw-medium">Monthly Volume</small>
                                <h4 class="mb-0 fw-bold"><?= htmlspecialchars($cur) . number_format((float)$totalRevenue, 2) ?></h4>
                            </div>
                        </div>
                        <div class="mt-3 pt-2 border-top">
                            <span class="text-<?= $growthRevenue >= 0 ? 'success' : 'danger'; ?> small fw-bold">
                                <?= $growthRevenue >= 0 ? '+' : ''; ?><?= round($growthRevenue, 1); ?>%
                            </span>
                            <small class="text-muted ms-1">Trend analysis</small>
                        </div>
                    </div>
                </div>

                <div class="col-md-6 col-xl-3">
                    <div class="card stat-card p-3">
                        <div class="d-flex align-items-center">
                            <div class="icon-box bg-warning bg-opacity-10 text-warning me-3">
                                <i class="bi bi-person-plus fs-5"></i>
                            </div>
                            <div>
                                <small class="text-muted d-block fw-medium">New Onboarding</small>
                                <h4 class="mb-0 fw-bold"><?= number_format($newSignups) ?></h4>
                            </div>
                        </div>
                        <div class="mt-3 pt-2 border-top">
                            <small class="text-muted">Last 24 hours</small>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card table-card">
                <div class="activity-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold">Recent User Activity</h5>
                    <div class="dropdown">
                        <button class="btn btn-light btn-sm" type="button" data-bs-toggle="dropdown">
                            <i class="bi bi-filter me-1"></i> Filter
                        </button>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="bg-light">
                            <tr class="small text-uppercase fw-bold text-muted">
                                <th class="ps-4">Client</th>
                                <th>Account ID</th>
                                <th>Last Access</th>
                                <th>Security Status</th>
                                <th class="text-end pe-4">Operations</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($recentActivity)): ?>
                                <?php foreach ($recentActivity as $activity): ?>
                                    <tr>
                                        <td class="ps-4">
                                            <div class="d-flex align-items-center">
                                                <div class="user-avatar me-3">
                                                    <?= strtoupper(substr($activity['firstname'], 0, 1) . substr($activity['lastname'], 0, 1)); ?>
                                                </div>
                                                <div>
                                                    <div class="fw-bold mb-0"><?= htmlspecialchars($activity['firstname'] . ' ' . $activity['lastname']); ?></div>
                                                    <small class="text-muted">Customer Account</small>
                                                </div>
                                            </div>
                                        </td>
                                        <td><span class="badge bg-light text-dark border">#<?= $activity['customerid']; ?></span></td>
                                        <td>
                                            <div class="small fw-medium">
                                                <?php
                                                $lastLogin = $activity['lastlogin'];
                                                if (empty($lastLogin) || $lastLogin == '0000-00-00 00:00:00') {
                                                    echo '<span class="text-warning">First Login Pending</span>';
                                                } else {
                                                    echo htmlspecialchars($lastLogin);
                                                }
                                                ?>
                                            </div>
                                        </td>
                                        <td><span class="status-pill bg-success bg-opacity-10 text-success">Verified</span></td>
                                        <td class="text-end pe-4">
                                            <div class="d-flex justify-content-end gap-2">
                                                <a href="edit_account.php?custid=<?= $activity['customerid']; ?>" class="btn btn-light btn-action" title="Edit Profile">
                                                    <i class="bi bi-pencil-square text-primary"></i>
                                                </a>
                                                <form method="post" onsubmit="return confirmDelete(this);" class="d-inline">
                                                    <input type="hidden" name="delete_id" value="<?= $activity['customerid']; ?>">
                                                    <button type="submit" class="btn btn-light btn-action" title="Close Account">
                                                        <i class="bi bi-trash3 text-danger"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="5" class="text-center py-5 text-muted">No recent banking activity found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="card-footer bg-white border-top py-3">
                    <div class="row align-items-center">
                        <div class="col-sm-6 text-center text-sm-start mb-3 mb-sm-0">
                            <span class="small text-muted">Showing records <?= $offset + 1 ?> - <?= min($offset + $limit, $totalUsersCount) ?> of <?= $totalUsersCount ?></span>
                        </div>
                        <div class="col-sm-6">
                            <nav aria-label="Page navigation">
                                <ul class="pagination pagination-sm justify-content-center justify-content-sm-end mb-0">
                                    <li class="page-item <?= ($page <= 1) ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?= $page - 1 ?>">Previous</a>
                                    </li>
                                    <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                                        <li class="page-item <?= ($p == $page) ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?= $p ?>"><?= $p ?></a>
                                        </li>
                                    <?php endfor; ?>
                                    <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?= $page + 1 ?>">Next</a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</main>

<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="assets/js/functions.js"></script>

<script>
function confirmDelete(form) {
    Swal.fire({
        title: 'Terminate Account?',
        text: "This action will permanently revoke user access and data!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e11d48',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Yes, Terminate',
        customClass: {
            confirmButton: 'rounded-pill px-4',
            cancelButton: 'rounded-pill px-4'
        }
    }).then((result) => {
        if (result.isConfirmed) {
            form.submit();
        }
    });
    return false;
}
</script>

<?php if (isset($deleteSuccess) && $deleteSuccess): ?>
<script>
    Swal.fire({
        icon: 'success',
        title: 'Account Terminated',
        text: 'The customer records have been wiped from the core system.',
        timer: 2000,
        showConfirmButton: false
    });
</script>
<?php endif; ?>

</body>
</html>