<?php
session_start();
if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';

// Safe query function
function safeCount($conn, $table, $where = '') {
    $sql = "SELECT COUNT(*) as cnt FROM $table $where";
    $result = $conn->query($sql);
    return $result ? $result->fetch_assoc()['cnt'] : 0;
}

// Get pending approvals count
$pendingNurses = safeCount($conn, 'nurses', "WHERE approval_status = 'pending'");
$pendingStaff = safeCount($conn, 'staff', "WHERE approval_status = 'pending'");
$totalPendingApprovals = $pendingNurses + $pendingStaff;

// Core counts
$totalPatients = safeCount($conn, 'patients');
$totalDoctors = safeCount($conn, 'doctors');
$totalNurses = safeCount($conn, 'nurses');
$totalStaff = safeCount($conn, 'staff');
$totalAppointments = safeCount($conn, 'appointments');
$pendingAppointments = safeCount($conn, 'appointments', "WHERE status='pending'");
$totalHospitals = safeCount($conn, 'hospitals', "WHERE status='active'");
$pendingConsults = safeCount($conn, 'consultations', "WHERE status='scheduled'");

// Payment Stats
$totalRevenue = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE status = 'completed'")->fetch_assoc()['total'] ?? 0;
$thisMonthRevenue = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE status = 'completed' AND MONTH(created_at) = MONTH(NOW())")->fetch_assoc()['total'] ?? 0;
$pendingPayments = $conn->query("SELECT COUNT(*) as cnt FROM transactions WHERE status = 'pending'")->fetch_assoc()['cnt'] ?? 0;

// HPS Stats
$hps_users = $conn->query("SELECT COUNT(DISTINCT user_id) as cnt FROM hps_subscriptions")->fetch_assoc()['cnt'] ?? 0;
$active_subscriptions = safeCount($conn, 'hps_subscriptions', "WHERE status='active'");
$total_invested = $conn->query("SELECT SUM(amount_invested) as total FROM hps_user_investments WHERE status='active'")->fetch_assoc()['total'] ?? 0;
$pending_withdrawals = $conn->query("SELECT SUM(amount) as total FROM withdrawal_requests WHERE status='pending'")->fetch_assoc()['total'] ?? 0;

// Card issuance stats
$totalCardsIssued = safeCount($conn, 'issued_cards');
$totalPartnerHospitals = safeCount($conn, 'partner_hospitals', "WHERE status='active'");

// Message counts
$unreadMessages = $conn->query("SELECT COUNT(*) as cnt FROM patient_doctor_messages WHERE is_read = 0")->fetch_assoc()['cnt'] ?? 0;
$totalNotifications = safeCount($conn, 'patient_notifications');

$page_title = 'Admin Dashboard | UHD';
include '../include/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Admin Dashboard - Unity Healthcare Database</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: linear-gradient(135deg, #0a3d2f, #064e3b); font-family: 'Segoe UI', sans-serif; min-height: 100vh; }
        
        .stat-card { background: rgba(255,255,255,0.12); backdrop-filter: blur(8px); border-radius: 20px; padding: 20px; text-align: center; color: white; transition: 0.3s; cursor: pointer; border: 1px solid rgba(255,255,255,0.1); }
        .stat-card:hover { transform: translateY(-5px); background: rgba(212,160,23,0.3); border-color: #d4a017; }
        .stat-card h3 { font-size: 1.8rem; font-weight: 700; margin: 10px 0; }
        
        .section-title { color: white; font-size: 1.3rem; font-weight: 700; margin: 30px 0 20px; padding-bottom: 10px; border-bottom: 2px solid #d4a017; display: inline-block; }
        
        .feature-card { background: white; border-radius: 20px; padding: 20px 12px; text-align: center; transition: 0.3s; height: 100%; cursor: pointer; border-bottom: 3px solid #dc3545; }
        .feature-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.15); }
        .feature-card i { font-size: 2rem; margin-bottom: 10px; color: #d4a017; }
        .feature-card h6 { font-size: 0.85rem; font-weight: 700; margin: 5px 0; }
        .feature-card p { font-size: 0.7rem; color: #6c757d; margin: 0; }
        
        .pending-card { background: linear-gradient(135deg, #dc3545, #c82333); border-radius: 20px; padding: 20px; color: white; margin-bottom: 25px; cursor: pointer; transition: 0.3s; }
        .pending-card:hover { transform: translateY(-3px); box-shadow: 0 10px 25px rgba(0,0,0,0.2); }
        
        .hps-card { background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 20px; padding: 20px; color: white; border-left: 4px solid #d4a017; }
        
        @media (max-width: 768px) {
            .stat-card h3 { font-size: 1.3rem; }
            .feature-card { padding: 15px 8px; }
            .feature-card i { font-size: 1.5rem; }
        }
    </style>
</head>
<body>

<div class="container mt-4">
    <!-- Header Stats Row 1 -->
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='manage_patients.php'"><i class="fas fa-users fa-2x"></i><h3><?= $totalPatients ?></h3><p>Total Patients</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='manage_doctor.php'"><i class="fas fa-user-md fa-2x"></i><h3><?= $totalDoctors ?></h3><p>Doctors</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='manage_nurses.php'"><i class="fas fa-user-nurse fa-2x"></i><h3><?= $totalNurses ?></h3><p>Nurses</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='manage_staff.php'"><i class="fas fa-user-tie fa-2x"></i><h3><?= $totalStaff ?></h3><p>Staff</p></div></div>
    </div>

    <!-- Pending Approvals Alert -->
    <?php if($totalPendingApprovals > 0): ?>
    <div class="pending-card" onclick="location.href='approve_users.php'">
        <div class="row align-items-center">
            <div class="col-auto"><i class="fas fa-user-clock fa-3x"></i></div>
            <div class="col"><h4 class="mb-0"><?= $totalPendingApprovals ?> Pending Approval(s)</h4><p class="mb-0"><?= $pendingNurses ?> nurse(s) and <?= $pendingStaff ?> staff member(s) need approval</p></div>
            <div class="col-auto"><i class="fas fa-arrow-right fa-2x"></i></div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Payment Overview Section (NEW) -->
    <div class="d-flex justify-content-between align-items-center">
        <h5 class="section-title"><i class="fas fa-credit-card me-2"></i> Payment Overview</h5>
        <a href="payments/index.php" class="btn btn-sm btn-outline-light rounded-pill">
            <i class="fas fa-chart-line me-1"></i> Payment Dashboard →
        </a>
    </div>
    <div class="row g-3 mb-4">
        <div class="col-md-4 col-6">
            <div class="stat-card" style="background: rgba(40,167,69,0.2);" onclick="location.href='payments/transactions.php'">
                <i class="fas fa-chart-line fa-2x"></i>
                <h3>₦<?= number_format($totalRevenue, 2) ?></h3>
                <p>Total Revenue</p>
            </div>
        </div>
        <div class="col-md-4 col-6">
            <div class="stat-card" style="background: rgba(23,162,184,0.2);" onclick="location.href='payments/transactions.php?filter=month'">
                <i class="fas fa-calendar-alt fa-2x"></i>
                <h3>₦<?= number_format($thisMonthRevenue, 2) ?></h3>
                <p>This Month</p>
            </div>
        </div>
        <div class="col-md-4 col-6">
            <div class="stat-card" style="background: rgba(220,53,69,0.2);" onclick="location.href='payments/transactions.php?status=pending'">
                <i class="fas fa-clock fa-2x"></i>
                <h3><?= $pendingPayments ?></h3>
                <p>Pending Payments</p>
            </div>
        </div>
    </div>

    <!-- HPS Section -->
    <div class="d-flex justify-content-between align-items-center">
        <h5 class="section-title"><i class="fas fa-shield-alt me-2"></i> HPS Financial Overview</h5>
        <a href="hps/dashboard.php" class="btn btn-sm btn-outline-light rounded-pill">Manage HPS →</a>
    </div>
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-6"><div class="stat-card" style="background: rgba(212,160,23,0.2);" onclick="location.href='hps/subscriptions.php'"><i class="fas fa-users fa-2x"></i><h3><?= $hps_users ?></h3><p>HPS Members</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" style="background: rgba(40,167,69,0.2);" onclick="location.href='hps/subscriptions.php'"><i class="fas fa-check-circle fa-2x"></i><h3><?= $active_subscriptions ?></h3><p>Active Plans</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" style="background: rgba(23,162,184,0.2);" onclick="location.href='hps/investments.php'"><i class="fas fa-chart-line fa-2x"></i><h3>₦<?= number_format($total_invested, 2) ?></h3><p>Total Invested</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" style="background: rgba(220,53,69,0.2);" onclick="location.href='hps/withdrawals.php'"><i class="fas fa-clock fa-2x"></i><h3>₦<?= number_format($pending_withdrawals, 2) ?></h3><p>Pending Withdrawals</p></div></div>
    </div>

    <!-- Appointments & Consultations -->
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='manage_appointments.php'"><i class="fas fa-calendar-check fa-2x"></i><h3><?= $totalAppointments ?></h3><p>Appointments</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='manage_appointments.php?status=pending'"><i class="fas fa-hourglass-half fa-2x"></i><h3><?= $pendingAppointments ?></h3><p>Pending Appointments</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='manage_consultations.php'"><i class="fas fa-video fa-2x"></i><h3><?= $pendingConsults ?></h3><p>Pending Consults</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='manage_hospitals.php'"><i class="fas fa-hospital fa-2x"></i><h3><?= $totalHospitals ?></h3><p>Partner Hospitals</p></div></div>
    </div>

    <!-- Card Management -->
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-6"><div class="stat-card" style="background: linear-gradient(135deg, #d4a017, #b8860b);" onclick="location.href='card_issuance.php'"><i class="fas fa-id-card fa-2x"></i><h3><?= $totalCardsIssued ?></h3><p>Cards Issued</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='hospital_card_management.php'"><i class="fas fa-hospital-user fa-2x"></i><h3><?= $totalPartnerHospitals ?></h3><p>Partner Hospitals</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='manage_messages.php'"><i class="fas fa-envelope fa-2x"></i><h3><?= $unreadMessages ?></h3><p>Unread Messages</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='manage_notifications.php'"><i class="fas fa-bell fa-2x"></i><h3><?= $totalNotifications ?></h3><p>Notifications</p></div></div>
    </div>

    <!-- Quick Actions Grid -->
    <h5 class="section-title"><i class="fas fa-bolt me-2"></i> Quick Actions</h5>
    <div class="row g-3 mb-5">
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='manage_patients.php'"><i class="fas fa-users"></i><h6>Manage Patients</h6><p>View, edit, approve</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='manage_doctor.php'"><i class="fas fa-user-md"></i><h6>Manage Doctors</h6><p>Add, edit, remove</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='manage_nurses.php'"><i class="fas fa-user-nurse"></i><h6>Manage Nurses</h6><p>Approve, edit</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='manage_staff.php'"><i class="fas fa-user-tie"></i><h6>Manage Staff</h6><p>Approve, edit</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='card_issuance.php'"><i class="fas fa-id-card"></i><h6>Card Issuance</h6><p>Issue plastic cards</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='generate_qr.php'"><i class="fas fa-qrcode"></i><h6>QR Generator</h6><p>Generate QR codes</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='broadcast_message.php'"><i class="fas fa-broadcast-tower"></i><h6>Broadcast</h6><p>Send notifications</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='hps/dashboard.php'"><i class="fas fa-shield-alt"></i><h6>HPS Management</h6><p>Insurance & Invest</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='payments/index.php'"><i class="fas fa-credit-card"></i><h6>Payment Dashboard</h6><p>Manage transactions</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='payment_settings.php'"><i class="fas fa-tags"></i><h6>Price Settings</h6><p>Set product prices</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='manage_appointments.php'"><i class="fas fa-calendar-alt"></i><h6>Appointments</h6><p>Schedule & status</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='manage_consultations.php'"><i class="fas fa-video"></i><h6>Consultations</h6><p>Virtual consults</p></div></div>
        <div class="col-md-3 col-6"><div class="feature-card" onclick="location.href='manage_hospitals.php'"><i class="fas fa-hospital"></i><h6>Hospitals</h6><p>Network management</p></div></div>
    </div>
</div>

<?php include '../include/footer.php'; ?>