<?php
// admin/dashboard.php - Dashboard with sidebar and full layout
require_once '../src/Database.php';
require_once '../src/Auth.php';

$auth = new Auth();
$auth->requireLogin();

$db = new Database();
$conn = $db->getConnection();
$currentUser = $auth->getCurrentUser();

// Get statistics
try {
    // Count paybills
    $stmt = $conn->query('SELECT COUNT(*) as total FROM ussd_mpesa_credentials');
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalPaybills = $row['total'] ?? 0;

    // Total customers
    $stmt = $conn->query('SELECT COUNT(*) as total FROM contacts');
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalCustomers = $row['total'] ?? 0;

    // Today's collections
    $today = date('Y-m-d');
    $stmt = $conn->prepare("SELECT SUM(amount) as total_collections FROM mpesa_stk_queue WHERE is_paid = 'yes' AND DATE(created_at) = ?");
    $stmt->execute([$today]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalCollections = $row['total_collections'] ?? 0;

    // Yesterday's income
    $yesterday = date('Y-m-d', strtotime('-1 day'));
    $stmt = $conn->prepare("SELECT SUM(amount) as total_income FROM mpesa_stk_queue WHERE is_paid = 'yes' AND DATE(created_at) = ?");
    $stmt->execute([$yesterday]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $incomeYesterday = $row['total_income'] ?? 0;

    // Today's income (same as collections)
    $incomeToday = $totalCollections;

    // Last 30 days income
    $thirtyDaysAgo = date('Y-m-d', strtotime('-30 days'));
    $stmt = $conn->prepare("SELECT SUM(amount) as total_income FROM mpesa_stk_queue WHERE is_paid = 'yes' AND DATE(created_at) >= ?");
    $stmt->execute([$thirtyDaysAgo]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalIncome30Days = $row['total_income'] ?? 0;

    // Recent payments
    $stmt = $conn->query("SELECT phone, amount, created_at FROM mpesa_stk_queue WHERE is_paid = 'yes' ORDER BY created_at DESC LIMIT 5");
    $recentPayments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Recent paybill updates
    $stmt = $conn->query('SELECT * FROM ussd_mpesa_credentials ORDER BY id DESC LIMIT 5');
    $recent = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $recentPayments = [];
    $recent = [];
    $incomeYesterday = 0;
    $incomeToday = 0;
    $totalIncome30Days = 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - USSD System</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <!-- Sidebar -->
    <?php include 'sidebar.php'; ?>

    <!-- Main Content -->
    <div class="md:ml-64 min-h-screen">
        <!-- Top Navigation -->
        <div class="bg-white shadow-md">
            <div class="flex items-center justify-between p-4 md:p-6">
                <h1 class="text-2xl font-bold text-gray-800">Dashboard</h1>
                <div class="flex items-center gap-4">
                    <span class="text-gray-600 hidden sm:inline">Welcome, <span class="font-semibold"><?php echo htmlspecialchars($currentUser['full_name'] ?? $currentUser['username']); ?></span></span>
                    <a href="/ussd/admin/logout.php" class="text-red-600 hover:text-red-800 font-semibold text-sm">Logout</a>
                </div>
            </div>
        </div>

        <!-- Page Content -->
        <div class="p-4 md:p-8">
            <!-- Statistics Cards -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <!-- Total Paybills Card -->
                <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-blue-600">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Total Paybills</p>
                            <p class="text-3xl font-bold text-blue-600 mt-2"><?php echo number_format($totalPaybills); ?></p>
                        </div>
                        <svg class="w-12 h-12 text-blue-100" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v2h8v-2zM2 8a2 2 0 11-4 0 2 2 0 014 0zM18 15v2h-2v-2a4 4 0 00-4-4H9a4 4 0 00-4 4v2H3v-2a6 6 0 0112 0z"></path>
                        </svg>
                    </div>
                </div>

                <!-- Total Customers Card -->
                <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-green-600">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Total Customers</p>
                            <p class="text-3xl font-bold text-green-600 mt-2"><?php echo number_format($totalCustomers); ?></p>
                        </div>
                        <svg class="w-12 h-12 text-green-100" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                </div>

                <!-- Today's Collections Card -->
                <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-purple-600">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Today's Collections</p>
                            <p class="text-3xl font-bold text-purple-600 mt-2">KES <?php echo number_format($totalCollections, 2); ?></p>
                        </div>
                        <svg class="w-12 h-12 text-purple-100" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M4 4a2 2 0 00-2 2v4a2 2 0 002 2V6h10a2 2 0 00-2-2H4zm2 6a2 2 0 012-2h8a2 2 0 012 2v4a2 2 0 01-2 2H8a2 2 0 01-2-2v-4zm6 4a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                </div>

                <!-- Active Sessions Card -->
                <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-orange-600">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">System Status</p>
                            <p class="text-3xl font-bold text-orange-600 mt-2">Active</p>
                        </div>
                        <svg class="w-12 h-12 text-orange-100" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M13.828 10.172a4 4 0 00-8.656 0l-3.36 3.36a2 2 0 101.414 1.414l2.121-2.121A4 4 0 1013.828 10.172z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Income Statistics Cards -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                <!-- Income Yesterday Card -->
                <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-teal-600">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Income Yesterday</p>
                            <p class="text-3xl font-bold text-teal-600 mt-2">KES <?php echo number_format($incomeYesterday, 2); ?></p>
                            <p class="text-xs text-gray-500 mt-1"><?php echo date('M d, Y', strtotime('-1 day')); ?></p>
                        </div>
                        <svg class="w-12 h-12 text-teal-100" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                </div>

                <!-- Income Today Card -->
                <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-emerald-600">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Income Today</p>
                            <p class="text-3xl font-bold text-emerald-600 mt-2">KES <?php echo number_format($incomeToday, 2); ?></p>
                            <p class="text-xs text-gray-500 mt-1"><?php echo date('M d, Y'); ?></p>
                        </div>
                        <svg class="w-12 h-12 text-emerald-100" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M12.316 3.051a1 1 0 01.633 1.265l-4 12a1 1 0 11-1.898-.632l4-12a1 1 0 011.265-.633zM5.707 6.293a1 1 0 010 1.414L3.414 10l2.293 2.293a1 1 0 11-1.414 1.414l-3-3a1 1 0 010-1.414l3-3a1 1 0 011.414 0zm8.586 0a1 1 0 011.414 0l3 3a1 1 0 010 1.414l-3 3a1 1 0 11-1.414-1.414L16.586 10l-2.293-2.293a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                </div>

                <!-- Total Income (30 Days) Card -->
                <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-cyan-600">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Total Income</p>
                            <p class="text-3xl font-bold text-cyan-600 mt-2">KES <?php echo number_format($totalIncome30Days, 2); ?></p>
                            <div class="flex items-center gap-1 mt-1">
                                <span class="text-xs text-gray-500">30 Days</span>
                                <svg class="w-4 h-4 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                                    <path d="M8 16.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0zM15 16.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0z"></path>
                                    <path d="M3 4a1 1 0 00-1 1v10a1 1 0 001 1h1.05a2.5 2.5 0 014.9 0H10a1 1 0 001-1V5a1 1 0 00-1-1H3zM14 7a1 1 0 00-1 1v6.05A2.5 2.5 0 0115.95 16H17a1 1 0 001-1v-5a1 1 0 00-.293-.707l-2-2A1 1 0 0015 7h-1z"></path>
                                </svg>
                            </div>
                        </div>
                        <svg class="w-12 h-12 text-cyan-100" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M2 11a1 1 0 011-1h2a1 1 0 011 1v5a1 1 0 01-1 1H3a1 1 0 01-1-1v-5zM8 7a1 1 0 011-1h2a1 1 0 011 1v9a1 1 0 01-1 1H9a1 1 0 01-1-1V7zM14 4a1 1 0 011-1h2a1 1 0 011 1v12a1 1 0 01-1 1h-2a1 1 0 01-1-1V4z"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Recent Activity Section -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <!-- Recent Payments -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-4">Recent Payments</h2>
                    <?php if (!empty($recentPayments)): ?>
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm">
                            <thead class="bg-gray-100 border-b">
                                <tr>
                                    <th class="px-4 py-2 text-left text-gray-600 font-semibold">Phone</th>
                                    <th class="px-4 py-2 text-left text-gray-600 font-semibold">Amount</th>
                                    <th class="px-4 py-2 text-left text-gray-600 font-semibold">Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recentPayments as $payment): ?>
                                <tr class="border-b hover:bg-gray-50">
                                    <td class="px-4 py-2 text-gray-800"><?php echo htmlspecialchars($payment['phone']); ?></td>
                                    <td class="px-4 py-2 font-semibold text-green-600">KES <?php echo number_format($payment['amount'], 2); ?></td>
                                    <td class="px-4 py-2 text-gray-600"><?php echo date('M d, Y H:i', strtotime($payment['created_at'])); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <p class="text-gray-500 text-center py-8">No recent payments</p>
                    <?php endif; ?>
                </div>

                <!-- Recent Paybill Updates -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h2 class="text-xl font-bold text-gray-800 mb-4">Recent Paybill Updates</h2>
                    <?php if (!empty($recent)): ?>
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm">
                            <thead class="bg-gray-100 border-b">
                                <tr>
                                    <th class="px-4 py-2 text-left text-gray-600 font-semibold">Business</th>
                                    <th class="px-4 py-2 text-left text-gray-600 font-semibold">Paybill</th>
                                    <th class="px-4 py-2 text-left text-gray-600 font-semibold">Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recent as $paybill): ?>
                                <tr class="border-b hover:bg-gray-50">
                                    <td class="px-4 py-2 text-gray-800"><?php echo htmlspecialchars($paybill['business_name'] ?? 'N/A'); ?></td>
                                    <td class="px-4 py-2 font-semibold text-blue-600"><?php echo htmlspecialchars($paybill['paybill_number']); ?></td>
                                    <td class="px-4 py-2 text-gray-600"><?php echo date('M d, Y', strtotime($paybill['created_at'])); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <p class="text-gray-500 text-center py-8">No recent updates</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
