<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

$search = $_GET['msisdn'] ?? '';
$status = $_GET['status'] ?? 'ALL';

$where = "t.status='SUCCESS'";

if ($search) {
    $where .= " AND t.sender_msisdn LIKE '%$search%'";
}

$sql = "
SELECT 
    t.sender_msisdn AS msisdn,
    u.user_type,
    SUM(CASE WHEN DATE(t.created_at)=CURDATE() THEN t.send_amount ELSE 0 END) AS daily_used,
    SUM(t.send_amount) AS cumulative_used,
    
    -- Resolve DAILY limit: MSISDN > USER_TYPE > ALL
    COALESCE(
        (SELECT max_amount FROM msisdn_limits WHERE applies_to='MSISDN' AND msisdn=t.sender_msisdn AND limit_type='DAILY' LIMIT 1),
        (SELECT max_amount FROM msisdn_limits WHERE applies_to='USER_TYPE' AND msisdn=u.user_type AND limit_type='DAILY' LIMIT 1),
        (SELECT max_amount FROM msisdn_limits WHERE applies_to='ALL' AND limit_type='DAILY' LIMIT 1)
    ) AS daily_limit,
    
    -- Resolve CUMULATIVE limit: MSISDN > USER_TYPE > ALL
    COALESCE(
        (SELECT max_amount FROM msisdn_limits WHERE applies_to='MSISDN' AND msisdn=t.sender_msisdn AND limit_type='CUMULATIVE' LIMIT 1),
        (SELECT max_amount FROM msisdn_limits WHERE applies_to='USER_TYPE' AND msisdn=u.user_type AND limit_type='CUMULATIVE' LIMIT 1),
        (SELECT max_amount FROM msisdn_limits WHERE applies_to='ALL' AND limit_type='CUMULATIVE' LIMIT 1)
    ) AS cumulative_limit,

    k.blocked,
    k.reason,
    k.updated_at
FROM transactions t
LEFT JOIN users u ON u.msisdn = t.sender_msisdn
LEFT JOIN msisdn_kill_switch k ON k.msisdn = t.sender_msisdn
WHERE 1=1
";

if ($search) {
    $sql .= " AND t.sender_msisdn LIKE '%$search%'";
}

$sql .= " GROUP BY t.sender_msisdn";



if ($status === 'BLOCKED') {
    $sql .= " HAVING blocked=1";
} elseif ($status === 'EXCEEDED') {
    $sql .= " HAVING daily_used > daily_limit OR cumulative_used > cumulative_limit";
}

$res = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Limit Violations</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{font-family:Inter;background:#f0f4f8;margin:0}
.main{padding:20px}
.card{background:#fff;padding:20px;border-radius:12px}
table{width:100%;border-collapse:collapse}
th,td{padding:10px;font-size:.9rem}
thead{background:#f3f4f6}
.blocked{background:#fee2e2}
.warning{background:#fff7ed}
.badge{padding:4px 10px;border-radius:999px;font-size:.75rem;font-weight:600}
.red{background:#dc2626;color:#fff}
.orange{background:#f97316;color:#fff}
.green{background:#16a34a;color:#fff}
</style>
</head>

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

<div class="main">
<div class="card">

<h2>MSISDN Limit Violations</h2>

<form method="GET" style="margin-bottom:15px">
<input type="text" name="msisdn" placeholder="Search MSISDN" value="<?= htmlspecialchars($search) ?>">
<select name="status">
    <option value="ALL">All</option>
    <option value="BLOCKED" <?= $status=='BLOCKED'?'selected':'' ?>>Blocked</option>
    <option value="EXCEEDED" <?= $status=='EXCEEDED'?'selected':'' ?>>Exceeded</option>
</select>
<button type="submit">Search</button>
<a href="export_violations.php">⬇ Export CSV</a>
</form>

<table>
<thead>
<tr>
<th>MSISDN</th>
<th>Daily Used</th>
<th>Daily Limit</th>
<th>Cum Used</th>
<th>Cum Limit</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php while($r=mysqli_fetch_assoc($res)):

$dailyPct = $r['daily_limit'] ? ($r['daily_used']/$r['daily_limit'])*100 : 0;
$cumPct   = $r['cumulative_limit'] ? ($r['cumulative_used']/$r['cumulative_limit'])*100 : 0;

if ($r['blocked']) {
    $row='blocked'; $badge='red'; $label='BLOCKED';
} elseif ($dailyPct>=100 || $cumPct>=100) {
    $row='warning'; $badge='orange'; $label='EXCEEDED';
} else {
    $row=''; $badge='green'; $label='OK';
}
?>
<tr class="<?= $row ?>">
<td>
<a href="msisdn_status.php?msisdn=<?= $r['msisdn'] ?>">
<?= $r['msisdn'] ?>
</a>
</td>
<td><?= number_format($r['daily_used'],2) ?></td>
<td><?= number_format($r['daily_limit'],2) ?></td>
<td><?= number_format($r['cumulative_used'],2) ?></td>
<td><?= number_format($r['cumulative_limit'],2) ?></td>
<td><span class="badge <?= $badge ?>"><?= $label ?></span></td>
<td>
<?php if($r['blocked']): ?>
<a href="actions_msisdn.php?action=unblock&msisdn=<?= $r['msisdn'] ?>">Unblock</a>
<?php else: ?>
<a href="actions_msisdn.php?action=block&msisdn=<?= $r['msisdn'] ?>">Block</a>
<?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>
</div>

<script>
setInterval(()=>location.reload(),15000);
</script>

</body>
</html>
