<?php
require_once '../includes/constants.php';
require_once '../includes/session.php';

if (!isset($_SESSION['admin_id']) || !in_array($_SESSION['admin_role'], ['manager','superadmin'])) {
    die("Access denied");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | System Alerts'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
// Handle resolution
if (isset($_GET['resolve'])) {
    $stmt = $pdo->prepare("UPDATE admin_alerts SET is_resolved = 1 WHERE id = ?");
    $stmt->execute([$_GET['resolve']]);
    log_admin_action($pdo, 'resolve_alert', "Resolved alert #" . htmlspecialchars($_GET['resolve']));
    echo "<p class='success'>✅ Alert resolved.</p>";
}

// Filters
$type = $_GET['type'] ?? null;
$severity = $_GET['severity'] ?? null;

$query = "SELECT * FROM admin_alerts WHERE is_resolved = 0";
$params = [];

if ($type) {
    $query .= " AND alert_type = ?";
    $params[] = $type;
}
if ($severity) {
    $query .= " AND severity = ?";
    $params[] = $severity;
}

$query .= " ORDER BY created_at DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$alerts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// UI
echo "<h2>🚨 System Alerts</h2>
<form method='get'>
    <label>Type:
        <select name='type'>
            <option value=''>All Types</option>
            <option value='flag_affiliate'" . ($type === 'flag_affiliate' ? ' selected' : '') . ">Flagged Affiliate</option>
            <option value='postback_fail'" . ($type === 'postback_fail' ? ' selected' : '') . ">Postback Failure</option>
            <option value='conversion_spike'" . ($type === 'conversion_spike' ? ' selected' : '') . ">Conversion Spike</option>
        </select>
    </label>
    <label>Severity:
        <select name='severity'>
            <option value=''>All Severities</option>
            <option value='low'" . ($severity === 'low' ? ' selected' : '') . ">Low</option>
            <option value='medium'" . ($severity === 'medium' ? ' selected' : '') . ">Medium</option>
            <option value='high'" . ($severity === 'high' ? ' selected' : '') . ">High</option>
        </select>
    </label>
    <button type='submit'>Filter</button>
</form>";

echo "<table><tr>
    <th>Type</th><th>Message</th><th>Severity</th><th>Time</th><th>Action</th>
</tr>";
foreach ($alerts as $a) {
    echo "<tr>
        <td>" . htmlspecialchars($a['alert_type']) . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($a['message']) . "</textarea></td>
        <td>" . htmlspecialchars($a['severity']) . "</td>
        <td>{$a['created_at']}</td>
        <td><a href='?resolve=" . htmlspecialchars($a['id']) . "'>Mark Resolved</a></td>
    </tr>";
}
echo "</table>";
?>
</div>
</body>
</html>