<?php
include "includes/db_connect.php";
include "includes/auth.php";
checkAdmin();

// ===========================
// AJAX REFRESH (CONTENT ONLY)
// ===========================
if (isset($_GET['ajax'])) {

   $limits_res = mysqli_query($conn,"
    SELECT l.*, u.msisdn AS user_msisdn, u.user_type
    FROM msisdn_limits l
    LEFT JOIN users u
        ON (
            (l.applies_to = 'MSISDN' AND l.msisdn = u.msisdn)
            OR
            (l.applies_to = 'USER_TYPE' AND l.msisdn = u.user_type)
            OR
            (l.applies_to = 'ALL')
        )
    ORDER BY l.applies_to, l.limit_type
");


    // Daily usage
    $daily_usage = [];
 $res = mysqli_query($conn,"
    SELECT sender_msisdn, SUM(send_amount) AS total
    FROM transactions
    WHERE DATE(created_at) = CURDATE()
      AND status IN ('QUEUED','SETTLED')
    GROUP BY sender_msisdn
");


    while($r = mysqli_fetch_assoc($res)) {
        $daily_usage[$r['sender_msisdn']] = $r['total'];
    }

    // Cumulative usage
    $cum_usage = [];
  $res = mysqli_query($conn,"
    SELECT sender_msisdn, SUM(send_amount) AS total
    FROM transactions
    WHERE status IN ('QUEUED','SETTLED')
    GROUP BY sender_msisdn
");

    while($r = mysqli_fetch_assoc($res)) {
        $cum_usage[$r['sender_msisdn']] = $r['total'];
    }
    ?>

    <div class="card">
        <h2>MSISDN Limits & Live Usage</h2>

        <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th>MSISDN</th>
                    <th>Limit Type</th>
                    <th>Max Amount</th>
                    <th>Used</th>
                    <th>Progress</th>
                </tr>
            </thead>
            <tbody>
            <?php while($row = mysqli_fetch_assoc($limits_res)):
                $limitTarget = $row['applies_to'] == 'MSISDN'
    ? $row['msisdn']
    : ($row['applies_to'] == 'USER_TYPE'
        ? "USER TYPE: ".$row['msisdn']
        : "ALL USERS");

$type = $row['limit_type'];

                $max    = (float)$row['max_amount'];

               $used = 0;

if ($row['applies_to'] == 'MSISDN') {
    $key = $row['msisdn'];
    $used = ($type == 'DAILY')
        ? ($daily_usage[$key] ?? 0)
        : ($cum_usage[$key] ?? 0);
}


                $percent = $max > 0 ? min(100, ($used / $max) * 100) : 0;
                $row_style = $percent >= 80 ? 'style="background:#fff1f2"' : '';
            ?>
                <tr <?= $row_style ?>>
                   <td><?= htmlspecialchars($limitTarget) ?></td>

                    <td><?= $type ?></td>
                    <td><?= number_format($max,2) ?></td>
                    <td><?= number_format($used,2) ?></td>
                    <td>
                        <div class="progress-bar">
                            <div class="fill" style="width:<?= $percent ?>%; background:<?= $percent>=80?'#dc2626':'#16a34a' ?>"></div>
                        </div>
                    </td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
        </div>
    </div>

    <?php
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mobex ADR Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">

<style>
body{font-family:Inter,sans-serif;background:#f0f4f8;margin:0;}
.card{background:#fff;padding:20px;border-radius:12px;box-shadow:0 10px 20px rgba(0,0,0,.05);margin-bottom:20px;}
h2{font-size:1.1rem;margin-bottom:15px;color:#1f2937;}
table{width:100%;border-collapse:collapse;}
th,td{padding:12px;font-size:.9rem;text-align:left;}
thead{background:#f3f4f6;}
tr:hover{background:#f9fafb;}
.progress-bar{height:14px;background:#e5e7eb;border-radius:6px;}
.progress-bar .fill{height:100%;border-radius:6px;}
.table-responsive{overflow-x:auto;}
</style>
</head>

<body>

<?php include "includes/mobex_sidebar.php"; ?>

<div id="liveDashboard" class="content"></div>

<script>
function refreshDashboard(){
    fetch('dashboard.php?ajax=1')
        .then(r => r.text())
        .then(html => document.getElementById('liveDashboard').innerHTML = html);
}
refreshDashboard();
setInterval(refreshDashboard, 10000);
</script>

</body>
</html>
