<?php 
include 'config.php'; 
if(!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'SuperAdmin') { 
    header("Location: login.php"); exit(); 
}

// 1. HANDLE MONTH FILTER
$selected_month = $_GET['month'] ?? date('Y-m'); // Default to current month

// 2. FETCH CORE STATS (All time)
$total_agencies = $conn->query("SELECT COUNT(id) as total FROM agencies WHERE id > 1")->fetch_assoc()['total'];
$active_agencies = $conn->query("SELECT COUNT(id) as total FROM agencies WHERE status = 'Active' AND id > 1")->fetch_assoc()['total'];
$total_vouchers = $conn->query("SELECT (SELECT COUNT(id) FROM umrah_vouchers) + (SELECT COUNT(id) FROM ticket_vouchers) as total")->fetch_assoc()['total'];

// 3. FINANCIAL INTELLIGENCE (Based on Month Filter)
// Revenue Collected (Cash in hand)
$revenue_collected = $conn->query("SELECT SUM(amount_paid) as total FROM saas_payments WHERE DATE_FORMAT(payment_date, '%Y-%m') = '$selected_month'")->fetch_assoc()['total'] ?? 0;

// Revenue Invoiced (Bills sent)
$revenue_invoiced = $conn->query("SELECT SUM(amount) as total FROM invoices WHERE DATE_FORMAT(created_at, '%Y-%m') = '$selected_month'")->fetch_assoc()['total'] ?? 0;

// Total Debt from all agencies (Historical)
$total_outstanding = $conn->query("SELECT SUM(balance_due) as total FROM agencies WHERE id > 1")->fetch_assoc()['total'] ?? 0;

// 4. RECENT ACTIVITY
$recent_agencies = $conn->query("SELECT * FROM agencies WHERE id > 1 ORDER BY id DESC LIMIT 5");
$recent_payments = $conn->query("SELECT p.*, a.agency_name FROM saas_payments p JOIN agencies a ON p.agency_id = a.id ORDER BY p.id DESC LIMIT 5");

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SaaS Master Controller | Super Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #4e73df; --success: #1cc88a; --info: #36b9cc; --warning: #f6c23e; --danger: #e74a3b; --secondary: #1e293b; --bg: #f8f9fc; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg); display: flex; }
        
        /* Sidebar */
        .sidebar { width: 260px; background: var(--secondary); height: 100vh; position: fixed; color: #fff; padding: 20px 0; }
        .nav-link { display: flex; align-items: center; padding: 12px 15px; color: rgba(255,255,255,0.7); text-decoration: none; border-radius: 10px; margin: 5px 20px; transition: 0.3s; }
        .active { background: rgba(255,255,255,0.1); color: #fff; border-left: 4px solid var(--primary); }
        .sidebar-brand { padding: 0 25px 30px; font-size: 20px; font-weight: 700; color: var(--primary); }

        .main-content { margin-left: 260px; width: calc(100% - 260px); padding: 40px; }
        
        /* Top Bar & Filter */
        .top-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        .month-filter { background: white; padding: 10px 20px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); display: flex; align-items: center; gap: 10px; }
        .month-filter input { border: 1px solid #ddd; padding: 8px; border-radius: 8px; outline: none; }

        /* Stats Cards */
        .stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 30px; }
        .stat-card { background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); border-bottom: 4px solid var(--primary); transition: 0.3s; }
        .stat-card:hover { transform: translateY(-5px); }
        .stat-card small { color: #64748b; text-transform: uppercase; font-size: 10px; font-weight: 700; letter-spacing: 1px; }
        .stat-card h3 { font-size: 24px; color: var(--secondary); margin-top: 5px; }
        .icon-circle { float: right; width: 45px; height: 45px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 20px; }

        /* Dashboard Layout */
        .dashboard-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 25px; }
        .card { background: white; padding: 25px; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); margin-bottom: 25px; }
        .card h4 { margin-bottom: 20px; color: var(--secondary); display: flex; align-items: center; gap: 10px; }
        
        table { width: 100%; border-collapse: collapse; }
        th { text-align: left; font-size: 11px; color: #94a3b8; text-transform: uppercase; padding-bottom: 12px; border-bottom: 1px solid #f1f5f9; }
        td { padding: 12px 0; border-bottom: 1px solid #f8fafc; font-size: 13px; }
        
        .btn { background: var(--primary); color: white; padding: 10px 20px; border: none; border-radius: 10px; cursor: pointer; font-weight: 600; width: 100%; transition: 0.3s; }
        .btn:hover { opacity: 0.9; }
    </style>
</head>
<body>

    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-brand"><i class="fas fa-rocket"></i> SAAS ADMIN</div>
        <a href="admin_dashboard.php" class="nav-link active"><i class="fas fa-chart-line"></i> Dashboard</a>
        <a href="manage_agencies.php" class="nav-link"><i class="fas fa-building"></i> Manage Agencies</a>
        <a href="saas_revenue.php" class="nav-link"><i class="fas fa-wallet"></i> Revenue Control</a>
        <a href="admin_group_tickets.php" class="nav-link"><i class="fas fa-plane"></i> Ticket Inventory</a>
        <a href="broadcast.php" class="nav-link"><i class="fas fa-bullhorn"></i> Announcements</a>
        <div style="margin-top: 50px; padding: 0 20px;"><small style="color: #64748b;">SYSTEM</small></div>
        <a href="dashboard.php" class="nav-link"><i class="fas fa-arrow-left"></i> Agency View</a>
        <a href="logout.php" class="nav-link" style="color:var(--danger);"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <div class="main-content">
        <!-- Top Header -->
        <div class="top-header">
            <div>
                <h1 style="font-weight: 700; color: var(--secondary);">Business Overview</h1>
                <p style="color: #64748b;">Track global SaaS performance and financial health.</p>
            </div>
            <form class="month-filter" id="monthForm">
                <i class="fas fa-calendar-alt" style="color: var(--primary);"></i>
                <input type="month" name="month" value="<?php echo $selected_month; ?>" onchange="document.getElementById('monthForm').submit()">
            </form>
        </div>

        <!-- 4 Major Stats -->
        <div class="stats-grid">
            <div class="stat-card" style="border-color: var(--success);">
                <div class="icon-circle" style="background: #dcfce7; color: var(--success);"><i class="fas fa-cash-register"></i></div>
                <small>Monthly Revenue</small>
                <h3>PKR <?php echo number_format($revenue_collected); ?></h3>
            </div>
            <div class="stat-card" style="border-color: var(--primary);">
                <div class="icon-circle" style="background: #e0e7ff; color: var(--primary);"><i class="fas fa-file-invoice-dollar"></i></div>
                <small>Monthly Invoiced</small>
                <h3>PKR <?php echo number_format($revenue_invoiced); ?></h3>
            </div>
            <div class="stat-card" style="border-color: var(--danger);">
                <div class="icon-circle" style="background: #fee2e2; color: var(--danger);"><i class="fas fa-hand-holding-usd"></i></div>
                <small>Total Outstanding</small>
                <h3>PKR <?php echo number_format($total_outstanding); ?></h3>
            </div>
            <div class="stat-card" style="border-color: var(--info);">
                <div class="icon-circle" style="background: #e0f2fe; color: var(--info);"><i class="fas fa-users"></i></div>
                <small>Total Agencies</small>
                <h3><?php echo $total_agencies; ?> Users</h3>
            </div>
        </div>

        <div class="dashboard-grid">
            <!-- Left Side: Reports -->
            <div>
                <div class="card">
                    <h4><i class="fas fa-user-plus" style="color:var(--primary);"></i> Recent Signups</h4>
                    <table>
                        <thead><tr><th>Agency Name</th><th>Owner</th><th>Status</th><th>Expiry</th></tr></thead>
                        <tbody>
                            <?php while($row = $recent_agencies->fetch_assoc()): ?>
                            <tr>
                                <td><b><?php echo $row['agency_name']; ?></b></td>
                                <td><?php echo $row['owner_name']; ?></td>
                                <td><span style="color:var(--success);">● <?php echo $row['status']; ?></span></td>
                                <td><?php echo date('d M Y', strtotime($row['expiry_date'])); ?></td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>

                <div class="card">
                    <h4><i class="fas fa-history" style="color:var(--success);"></i> Recent Cash Inflow</h4>
                    <table>
                        <thead><tr><th>Date</th><th>Agency</th><th>Method</th><th>Amount</th></tr></thead>
                        <tbody>
                            <?php while($pay = $recent_payments->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo date('d M', strtotime($pay['payment_date'])); ?></td>
                                <td><b><?php echo $pay['agency_name']; ?></b></td>
                                <td><?php echo $pay['payment_method']; ?></td>
                                <td style="color:var(--success); font-weight:600;">+ PKR <?php echo number_format($pay['amount_paid']); ?></td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Right Side: Tools -->
            <div>
                <div class="card">
                    <h4><i class="fas fa-bullhorn" style="color:var(--warning);"></i> System Broadcast</h4>
                    <form action="handle_broadcast.php" method="POST">
                        <input type="text" name="title" placeholder="Announcement Title" style="width:100%; padding:10px; margin-bottom:10px; border:1px solid #ddd; border-radius:8px;">
                        <textarea name="message" rows="4" placeholder="Write message to all agencies..." style="width:100%; padding:10px; margin-bottom:15px; border:1px solid #ddd; border-radius:8px;"></textarea>
                        <button type="submit" class="btn">Send Notification</button>
                    </form>
                </div>

                <div class="card" style="background: var(--secondary); color: white;">
                    <h4><i class="fas fa-chart-pie"></i> Usage Overview</h4>
                    <div style="margin-bottom:15px;">
                        <small style="opacity:0.7;">Vouchers in System</small>
                        <h2 style="font-size:32px;"><?php echo $total_vouchers; ?></h2>
                    </div>
                    <hr style="opacity:0.1; margin-bottom:15px;">
                    <a href="manage_agencies.php" style="color:var(--primary); font-size:12px; text-decoration:none; font-weight:700;">VIEW DETAILED USAGE ➔</a>
                </div>
            </div>
        </div>
    </div>
</body>
</html>