<?php
// UTF-8 encoding ayarı
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding('UTF-8');

session_start();
include 'auth.php';
include 'config.php'; // Woohdd klasöründeki config.php dosyasını kullan

// Admin kontrolü
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: index.php");
    exit;
}

// Sayfalama
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Filtreleme
$risk_filter = $_GET['risk'] ?? '';
$status_filter = $_GET['status'] ?? 'pending'; // Varsayılan olarak sadece bekleyen uyarıları göster
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

// Sorgu oluştur
$where_conditions = [];
$params = [];

if ($risk_filter) {
    $where_conditions[] = "dsa.risk_level = ?";
    $params[] = $risk_filter;
}

if ($status_filter) {
    $where_conditions[] = "dsa.status = ?";
    $params[] = $status_filter;
}

if ($date_from) {
    $where_conditions[] = "DATE(dsa.detected_at) >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $where_conditions[] = "DATE(dsa.detected_at) <= ?";
    $params[] = $date_to;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Toplam kayıt sayısı
$count_sql = "
    SELECT COUNT(*) as total
    FROM detected_suspicious_activities dsa
    $where_clause
";
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($params);
$total_records = $count_stmt->fetch(PDO::FETCH_ASSOC)['total'];
$total_pages = ceil($total_records / $per_page);

// Ana sorgu
$sql = "
    SELECT 
        dsa.*,
        k.username,
        k.email,
        ar.rule_name,
        ar.description as rule_description
    FROM detected_suspicious_activities dsa
    LEFT JOIN kullanicilar k ON dsa.user_id = k.id
    LEFT JOIN alert_rules ar ON dsa.rule_id = ar.id
    $where_clause
    ORDER BY dsa.detected_at DESC
    LIMIT $per_page OFFSET $offset
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$alerts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// İstatistikler
$stats_sql = "
    SELECT 
        risk_level,
        COUNT(*) as count
    FROM detected_suspicious_activities
    WHERE detected_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY risk_level
";
$stats_stmt = $pdo->query($stats_sql);
$risk_stats = $stats_stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// Günlük istatistikler
$daily_stats_sql = "
    SELECT 
        DATE(detected_at) as date,
        COUNT(*) as count
    FROM detected_suspicious_activities
    WHERE detected_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY DATE(detected_at)
    ORDER BY date DESC
";
$daily_stats_stmt = $pdo->query($daily_stats_sql);
$daily_stats = $daily_stats_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Şüpheli Aktivite Uyarıları</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" href="styles.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include 'sidebar.php'; ?>

            <div class="col-md-10 p-2">
                <?php include __DIR__ . '/topbar.php'; ?>
                <h2 class="mb-3"><i class="fas fa-shield-alt me-2"></i>Şüpheli Aktivite Uyarıları</h2>
                
                <!-- Otomatik Tespit Monitörü -->
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-radar me-2"></i>Otomatik Tespit Sistemi</h5>
                        <div class="d-flex align-items-center">
                            <span class="me-3" id="monitor-status">
                                <span class="badge bg-secondary">Başlatılıyor...</span>
                            </span>
                            <button class="btn btn-sm btn-outline-primary" onclick="suspiciousActivityMonitor.manualCheck()">
                                <i class="fas fa-sync-alt"></i> Manuel Kontrol
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <small class="text-muted">Son Kontrol: </small>
                                <span id="last-check" class="fw-bold">-</span>
                            </div>
                            <div class="col-md-6">
                                <div id="monitor-stats">
                                    <small class="text-muted">Sistem başlatılıyor...</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            
                <!-- İstatistikler -->
                <div class="row mb-3">
                    <div class="col-md-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="card-title"><?= $total_records ?></h3>
                                <p class="card-text mb-0">Toplam Uyarı</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="card-title text-danger"><?= $risk_stats['critical'] ?? 0 ?></h3>
                                <p class="card-text mb-0">Kritik Uyarılar</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="card-title text-warning"><?= $risk_stats['high'] ?? 0 ?></h3>
                                <p class="card-text mb-0">Yüksek Risk</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="card-title"><?= array_sum($risk_stats) ?></h3>
                                <p class="card-text mb-0">Son 7 Gün</p>
                            </div>
                        </div>
                    </div>
                </div>
            
                <!-- Filtreler -->
                <div class="card mb-3">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label">Risk Seviyesi</label>
                        <select name="risk" class="form-select">
                            <option value="">Tümü</option>
                            <option value="low" <?= $risk_filter === 'low' ? 'selected' : '' ?>>Düşük</option>
                            <option value="medium" <?= $risk_filter === 'medium' ? 'selected' : '' ?>>Orta</option>
                            <option value="high" <?= $risk_filter === 'high' ? 'selected' : '' ?>>Yüksek</option>
                            <option value="critical" <?= $risk_filter === 'critical' ? 'selected' : '' ?>>Kritik</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Durum</label>
                        <select name="status" class="form-select">
                            <option value="">Tümü</option>
                            <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Beklemede</option>
                            <option value="investigating" <?= $status_filter === 'investigating' ? 'selected' : '' ?>>İnceleniyor</option>
                            <option value="resolved" <?= $status_filter === 'resolved' ? 'selected' : '' ?>>Çözüldü</option>
                            <option value="false_positive" <?= $status_filter === 'false_positive' ? 'selected' : '' ?>>Yanlış Alarm</option>
                            <option value="confirmed" <?= $status_filter === 'confirmed' ? 'selected' : '' ?>>Onaylandı</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Başlangıç Tarihi</label>
                        <input type="date" name="date_from" class="form-control" value="<?= $date_from ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Bitiş Tarihi</label>
                        <input type="date" name="date_to" class="form-control" value="<?= $date_to ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary d-block">
                            <i class="fas fa-search me-1"></i>Filtrele
                        </button>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <a href="suspicious_alerts.php" class="btn btn-secondary d-block">
                            <i class="fas fa-times me-1"></i>Temizle
                        </a>
                    </div>
                        </form>
                    </div>
                </div>
            
            <!-- Uyarılar Listesi -->
            <div class="row">
                <div class="col-12">
                    <?php if (empty($alerts)): ?>
                        <div class="alert alert-info text-center">
                            <i class="fas fa-info-circle me-2"></i>
                            Seçilen kriterlere uygun şüpheli aktivite bulunamadı.
                        </div>
                    <?php else: ?>
                        <?php foreach ($alerts as $alert): ?>
                            <?php 
                            $activity_data = json_decode($alert['activity_data'], true);
                            $risk_colors = [
                                'low' => 'success',
                                'medium' => 'warning',
                                'high' => 'danger',
                                'critical' => 'dark'
                            ];
                            $risk_color = $risk_colors[$alert['risk_level']] ?? 'secondary';
                            ?>
                            <div class="card mb-3">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="d-flex justify-content-between align-items-start mb-2">
                                                <h5 class="card-title mb-0">
                                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                                    <?= htmlspecialchars($alert['rule_name'] ?? $alert['activity_type']) ?>
                                                </h5>
                                                <span class="badge bg-<?= $risk_color ?>">
                                                    <?= strtoupper($alert['risk_level']) ?>
                                                </span>
                                            </div>
                                            
                                            <p class="text-muted mb-2">
                                                <strong>Kullanıcı:</strong> <?= htmlspecialchars($alert['username']) ?> 
                                                (<?= htmlspecialchars($alert['email']) ?>)
                                            </p>
                                            
                                            <p class="text-muted mb-2">
                                                <strong>Zaman:</strong> <?= date('d.m.Y H:i:s', strtotime($alert['detected_at'])) ?>
                                                <strong class="ms-3">Risk Skoru:</strong> <?= $alert['risk_score'] ?>/100
                                            </p>
                                            
                                            <?php if ($activity_data): ?>
                                                <div class="card mt-2" style="background: var(--surface-2); border: 1px solid var(--border);">
                                                    <div class="card-body p-2">
                                                        <small><strong>Aktivite Detayları:</strong></small><br>
                                                        <small style="font-family: monospace;">
                                                            <?php foreach ($activity_data as $key => $value): ?>
                                                                <strong><?= htmlspecialchars($key) ?>:</strong> 
                                                                <?= is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : htmlspecialchars($value) ?><br>
                                                            <?php endforeach; ?>
                                                        </small>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="col-md-4 text-end">
                                            <div class="btn-group-vertical" role="group">
                                                <button class="btn btn-sm btn-outline-success" onclick="updateAlertStatus(<?= $alert['id'] ?>, 'resolved')">
                                                    <i class="fas fa-check me-1"></i>Çözüldü
                                                </button>
                                                <button class="btn btn-sm btn-outline-warning" onclick="updateAlertStatus(<?= $alert['id'] ?>, 'false_positive')">
                                                    <i class="fas fa-times me-1"></i>Yanlış Alarm
                                                </button>
                                                <button class="btn btn-sm btn-outline-info" onclick="viewUserDetails(<?= $alert['user_id'] ?>)">
                                                    <i class="fas fa-user me-1"></i>Kullanıcı Detayı
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        
                        <!-- Sayfalama -->
                        <?php if ($total_pages > 1): ?>
                            <nav aria-label="Sayfa navigasyonu">
                                <ul class="pagination justify-content-center">
                                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                        <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                            <a class="page-link" href="?page=<?= $i ?>&risk=<?= $risk_filter ?>&status=<?= $status_filter ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>">
                                                <?= $i ?>
                                            </a>
                                        </li>
                                    <?php endfor; ?>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        function updateAlertStatus(alertId, status) {
            const statusTexts = {
                'resolved': 'çözüldü olarak işaretlensin',
                'false_positive': 'yanlış alarm olarak işaretlensin'
            };
            
            Swal.fire({
                title: 'Emin misiniz?',
                text: `Bu uyarı ${statusTexts[status]}?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Evet',
                cancelButtonText: 'İptal'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch('../api/update_alert_status.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        credentials: 'same-origin',
                        body: JSON.stringify({
                            alert_id: alertId,
                            status: status
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            Swal.fire('Başarılı!', 'Uyarı durumu güncellendi.', 'success')
                                .then(() => location.reload());
                        } else {
                            Swal.fire('Hata!', data.message, 'error');
                        }
                    })
                    .catch(error => {
                        Swal.fire('Hata!', 'Bir hata oluştu.', 'error');
                    });
                }
            });
        }
        
        function viewUserDetails(userId) {
            window.open(`users.php?user_id=${userId}`, '_blank');
        }
        
        // Otomatik yenileme (5 dakikada bir)
        setInterval(() => {
            location.reload();
        }, 300000);
    </script>
    
    <!-- Şüpheli Aktivite Monitörü -->
    <script src="../js/suspicious_activity_monitor.js"></script>
</body>
</html>