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

// 1. Overall Business Stats
$total_revenue = $conn->query("SELECT SUM(amount_paid) as total FROM saas_payments")->fetch_assoc()['total'] ?? 0;
$total_pending = $conn->query("SELECT SUM(balance_due) as total FROM agencies WHERE id > 1")->fetch_assoc()['total'] ?? 0;
$active_agencies = $conn->query("SELECT COUNT(id) as total FROM agencies WHERE id > 1 AND status = 'Active'")->fetch_assoc()['total'] ?? 0;

// 2. Search Logic
$search = $_GET['search'] ?? '';
$sql = "SELECT * FROM agencies WHERE id > 1";
if(!empty($search)) {
    $sql .= " AND (agency_name LIKE '%$search%' OR owner_name LIKE '%$search%' OR phone LIKE '%$search%')";
}
$sql .= " ORDER BY balance_due DESC"; // Show agencies who owe most at the top
$agencies = $conn->query($sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Agency Account Overview | 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; --danger: #e74a3b; --warning: #f6c23e; --secondary: #1e293b; --bg: #f8f9fc; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg); padding: 40px; }
        .container { max-width: 1300px; margin: auto; }
        
        .top-nav { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        .btn-back { text-decoration: none; color: #64748b; font-weight: 600; font-size: 14px; }

        /* Stats Section */
        .stats-grid { display: grid; grid-template-columns: repeat(3, 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-left: 5px solid var(--primary); }
        .stat-card h3 { font-size: 24px; color: var(--secondary); margin-top: 5px; }
        .stat-card small { color: #64748b; text-transform: uppercase; font-size: 11px; font-weight: 700; }

        /* Main Table Card */
        .card { background: white; padding: 30px; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); }
        .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
        
        .search-box { padding: 12px; border: 1px solid #e2e8f0; border-radius: 10px; width: 350px; outline: none; }
        .btn-pay { background: var(--success); color: white; padding: 12px 20px; border-radius: 10px; text-decoration: none; font-weight: 700; font-size: 14px; }

        table { width: 100%; border-collapse: collapse; }
        th { text-align: left; padding: 15px; background: #f8f9fc; color: #64748b; font-size: 11px; text-transform: uppercase; border-bottom: 2px solid #edf2f7; }
        td { padding: 18px 15px; border-bottom: 1px solid #f1f5f9; font-size: 14px; vertical-align: middle; }
        
        /* Balance Styling */
        .bal-danger { color: var(--danger); font-weight: 700; background: #fff5f5; padding: 5px 10px; border-radius: 6px; }
        .bal-ok { color: var(--success); font-weight: 700; background: #f0fff4; padding: 5px 10px; border-radius: 6px; }

        /* Days Remaining Badge */
        .days-badge { padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: 600; }
        .days-urgent { background: #fee2e2; color: #b91c1c; }
        .days-warning { background: #fef3c7; color: #92400e; }
        .days-good { background: #dcfce7; color: #15803d; }

        .btn-history { background: #f1f5f9; color: var(--primary); padding: 8px 15px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 12px; transition: 0.3s; }
        .btn-history:hover { background: var(--primary); color: white; }
    </style>
</head>
<body>

<div class="container">
    <div class="top-nav">
        <div>
            <a href="dashboard.php" class="btn-back"><i class="fas fa-arrow-left"></i> Back to Dashboard</a>
            <h1 style="margin-top:10px;">Agency Accounts Control</h1>
        </div>
        <a href="record_saas_payment.php" class="btn-pay"><i class="fas fa-plus"></i> Record Agency Payment</a>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <small>Total Received Revenue</small>
            <h3 style="color: var(--success);">PKR <?php echo number_format($total_revenue); ?></h3>
        </div>
        <div class="stat-card" style="border-left-color: var(--danger);">
            <small>Outstanding (Uncollected)</small>
            <h3 style="color: var(--danger);">PKR <?php echo number_format($total_pending); ?></h3>
        </div>
        <div class="stat-card" style="border-left-color: var(--info);">
            <small>Active Paying Agencies</small>
            <h3><?php echo $active_agencies; ?> Agencies</h3>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <form method="GET">
                <input type="text" name="search" class="search-box" placeholder="Search by Agency Name or Phone..." value="<?php echo htmlspecialchars($search); ?>">
            </form>
            <p style="font-size: 12px; color: #64748b;">Sorted by: <b>Highest Balance Due</b></p>
        </div>

        <table>
            <thead>
                <tr>
                    <th>Agency & Contact</th>
                    <th>Remaining Amount</th>
                    <th>Expiry Date</th>
                    <th>Days Left</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while($row = $agencies->fetch_assoc()): 
                    // Calculate Days Remaining
                    $now = new DateTime();
                    $expiry = new DateTime($row['expiry_date']);
                    $diff = $now->diff($expiry);
                    $days_left = (int)$diff->format("%r%a");

                    // Styling logic
                    $days_class = 'days-good';
                    if($days_left < 3) $days_class = 'days-urgent';
                    elseif($days_left < 10) $days_class = 'days-warning';
                ?>
                <tr>
                    <td>
                        <b><?php echo $row['agency_name']; ?></b><br>
                        <small style="color: #64748b;"><i class="fas fa-phone"></i> <?php echo $row['phone']; ?></small>
                    </td>
                    <td>
                        <span class="<?php echo ($row['balance_due'] > 0 ? 'bal-danger' : 'bal-ok'); ?>">
                            PKR <?php echo number_format($row['balance_due']); ?>
                        </span>
                    </td>
                    <td>
                        <span style="font-weight: 500;"><?php echo date('d M Y', strtotime($row['expiry_date'])); ?></span>
                    </td>
                    <td>
                        <span class="days-badge <?php echo $days_class; ?>">
                            <?php echo ($days_left < 0) ? "EXPIRED" : $days_left . " Days"; ?>
                        </span>
                    </td>
                    <td>
                        <span style="font-size: 12px; font-weight: 600; color: <?php echo ($row['status'] == 'Active' ? 'var(--success)' : 'var(--danger)'); ?>;">
                            ● <?php echo strtoupper($row['status']); ?>
                        </span>
                    </td>
                    <td>
                        <div style="display:flex; gap: 5px;">
                            <a href="agency_ledger.php?id=<?php echo $row['id']; ?>" class="btn-history" title="View Full Ledger">
                                <i class="fas fa-book"></i> Ledger
                            </a>
                            <a href="edit_agency.php?id=<?php echo $row['id']; ?>" class="btn-history" style="color: #64748b;">
                                <i class="fas fa-edit"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
                <?php if($agencies->num_rows == 0) echo "<tr><td colspan='6' style='text-align:center; padding:50px;'>No agencies found.</td></tr>"; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>