<?php
session_start();
require_once 'config.php';
require_once 'auth.php';

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

$page_title = "Tetikleyici İzleme";

// Tarih filtresi
$start_date = isset($_GET['start']) ? $_GET['start'] : date('Y-m-d', strtotime('-7 days'));
$end_date = isset($_GET['end']) ? $_GET['end'] : date('Y-m-d');

// Admin bildirimleri
try {
    $stmt = $pdo->prepare("
        SELECT notification_type, title, message, priority, created_at, is_read
        FROM admin_notifications 
        WHERE DATE(created_at) BETWEEN ? AND ?
        ORDER BY created_at DESC 
        LIMIT 50
    ");
    $stmt->execute([$start_date, $end_date]);
    $admin_notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $admin_notifications = [];
}

// Alert bildirimleri
try {
    $stmt = $pdo->prepare("
        SELECT alert_type, title, message, user_id, created_at
        FROM alert_notifications 
        WHERE DATE(created_at) BETWEEN ? AND ?
        ORDER BY created_at DESC 
        LIMIT 50
    ");
    $stmt->execute([$start_date, $end_date]);
    $alert_notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $alert_notifications = [];
}

// Loyalty istatistikleri
try {
    $stmt = $pdo->prepare("
        SELECT stat_type, COUNT(*) as count, AVG(stat_value) as avg_value
        FROM loyalty_statistics 
        WHERE DATE(recorded_at) BETWEEN ? AND ?
        GROUP BY stat_type
        ORDER BY count DESC
    ");
    $stmt->execute([$start_date, $end_date]);
    $loyalty_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $loyalty_stats = [];
}

// Suspicious activities
try {
    $stmt = $pdo->prepare("
        SELECT activity_type, COUNT(*) as count, risk_score
        FROM suspicious_activities 
        WHERE DATE(detected_at) BETWEEN ? AND ?
        GROUP BY activity_type, risk_score
        ORDER BY count DESC
    ");
    $stmt->execute([$start_date, $end_date]);
    $suspicious_activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $suspicious_activities = [];
}

// Tetikleyici istatistikleri
try {
    $stmt = $pdo->query("
        SELECT 
            TRIGGER_NAME as name,
            EVENT_MANIPULATION as event_type,
            EVENT_OBJECT_TABLE as table_name,
            ACTION_TIMING as timing
        FROM information_schema.TRIGGERS 
        WHERE TRIGGER_SCHEMA = 'blacrhdy_bet1'
        ORDER BY EVENT_OBJECT_TABLE, TRIGGER_NAME
    ");
    $triggers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $triggers = [];
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <style>
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            transition: transform 0.3s ease;
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
        }
        
        .stats-card.danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
        }
        
        .stats-card.success {
            background: linear-gradient(135deg, #00d2d3 0%, #54a0ff 100%);
        }
        
        .stats-card.warning {
            background: linear-gradient(135deg, #feca57 0%, #ff9ff3 100%);
        }
        
        .priority-high { color: #dc3545; font-weight: bold; }
        .priority-medium { color: #fd7e14; }
        .priority-low { color: #6c757d; }
        
        .alert-type-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 0.375rem;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .table-responsive {
            max-height: 400px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            
            <div class="col-md-10 p-4">
                <?php include 'topbar.php'; ?>
                
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1><i class="fas fa-bell"></i> <?php echo $page_title; ?></h1>
                    
                    <!-- Tarih Filtresi -->
                    <form method="GET" class="d-flex gap-2">
                        <input type="date" name="start" value="<?php echo $start_date; ?>" class="form-control">
                        <input type="date" name="end" value="<?php echo $end_date; ?>" class="form-control">
                        <button type="submit" class="btn btn-primary">Filtrele</button>
                    </form>
                </div>

                <!-- İstatistik Kartları -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="stats-card">
                            <h5><i class="fas fa-exclamation-triangle"></i> Admin Bildirimleri</h5>
                            <h2><?php echo count($admin_notifications); ?></h2>
                            <small>Son <?php echo (strtotime($end_date) - strtotime($start_date)) / 86400; ?> gün</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card danger">
                            <h5><i class="fas fa-shield-alt"></i> Güvenlik Uyarıları</h5>
                            <h2><?php echo count($alert_notifications); ?></h2>
                            <small>Tespit edilen aktiviteler</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card success">
                            <h5><i class="fas fa-star"></i> Sadakat Aktiviteleri</h5>
                            <h2><?php echo count($loyalty_stats); ?></h2>
                            <small>Farklı aktivite türü</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card warning">
                            <h5><i class="fas fa-cogs"></i> Aktif Tetikleyiciler</h5>
                            <h2><?php echo count($triggers); ?></h2>
                            <small>Veritabanında çalışan</small>
                        </div>
                    </div>
                </div>

                <!-- Tabs -->
                <ul class="nav nav-tabs" id="monitoringTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="admin-notifications-tab" data-bs-toggle="tab" data-bs-target="#admin-notifications" type="button" role="tab">
                            <i class="fas fa-bell"></i> Admin Bildirimleri
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="security-alerts-tab" data-bs-toggle="tab" data-bs-target="#security-alerts" type="button" role="tab">
                            <i class="fas fa-shield-alt"></i> Güvenlik Uyarıları
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="loyalty-stats-tab" data-bs-toggle="tab" data-bs-target="#loyalty-stats" type="button" role="tab">
                            <i class="fas fa-star"></i> Sadakat İstatistikleri
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="triggers-tab" data-bs-toggle="tab" data-bs-target="#triggers" type="button" role="tab">
                            <i class="fas fa-cogs"></i> Tetikleyici Listesi
                        </button>
                    </li>
                </ul>

                <div class="tab-content" id="monitoringTabsContent">
                    <!-- Admin Bildirimleri -->
                    <div class="tab-pane fade show active" id="admin-notifications" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-bell"></i> Admin Bildirimleri</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="adminNotificationsTable">
                                        <thead>
                                            <tr>
                                                <th>Tür</th>
                                                <th>Başlık</th>
                                                <th>Mesaj</th>
                                                <th>Öncelik</th>
                                                <th>Tarih</th>
                                                <th>Durum</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($admin_notifications as $notification): ?>
                                            <tr>
                                                <td>
                                                    <span class="alert-type-badge bg-primary text-white">
                                                        <?php echo htmlspecialchars($notification['notification_type']); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo htmlspecialchars($notification['title']); ?></td>
                                                <td><?php echo htmlspecialchars(substr($notification['message'], 0, 100)) . '...'; ?></td>
                                                <td>
                                                    <span class="priority-<?php echo $notification['priority']; ?>">
                                                        <?php echo strtoupper($notification['priority']); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo date('d.m.Y H:i', strtotime($notification['created_at'])); ?></td>
                                                <td>
                                                    <?php if ($notification['is_read']): ?>
                                                        <span class="badge bg-success">Okundu</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-warning">Okunmadı</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Güvenlik Uyarıları -->
                    <div class="tab-pane fade" id="security-alerts" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-shield-alt"></i> Güvenlik Uyarıları</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="securityAlertsTable">
                                        <thead>
                                            <tr>
                                                <th>Uyarı Türü</th>
                                                <th>Başlık</th>
                                                <th>Mesaj</th>
                                                <th>Kullanıcı ID</th>
                                                <th>Tarih</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($alert_notifications as $alert): ?>
                                            <tr>
                                                <td>
                                                    <span class="alert-type-badge bg-danger text-white">
                                                        <?php echo htmlspecialchars($alert['alert_type']); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo htmlspecialchars($alert['title']); ?></td>
                                                <td><?php echo htmlspecialchars(substr($alert['message'], 0, 100)) . '...'; ?></td>
                                                <td><?php echo $alert['user_id'] ? $alert['user_id'] : 'Sistem'; ?></td>
                                                <td><?php echo date('d.m.Y H:i', strtotime($alert['created_at'])); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Sadakat İstatistikleri -->
                    <div class="tab-pane fade" id="loyalty-stats" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-star"></i> Sadakat İstatistikleri</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="loyaltyStatsTable">
                                        <thead>
                                            <tr>
                                                <th>İstatistik Türü</th>
                                                <th>Toplam Sayı</th>
                                                <th>Ortalama Değer</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($loyalty_stats as $stat): ?>
                                            <tr>
                                                <td>
                                                    <span class="alert-type-badge bg-success text-white">
                                                        <?php echo htmlspecialchars($stat['stat_type']); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo number_format($stat['count']); ?></td>
                                                <td><?php echo number_format($stat['avg_value'], 2); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Tetikleyici Listesi -->
                    <div class="tab-pane fade" id="triggers" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-cogs"></i> Aktif Tetikleyiciler</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="triggersTable">
                                        <thead>
                                            <tr>
                                                <th>Tetikleyici Adı</th>
                                                <th>Olay Türü</th>
                                                <th>Tablo</th>
                                                <th>Zamanlama</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($triggers as $trigger): ?>
                                            <tr>
                                                <td><code><?php echo htmlspecialchars($trigger['name']); ?></code></td>
                                                <td>
                                                    <span class="badge bg-info">
                                                        <?php echo $trigger['event_type']; ?>
                                                    </span>
                                                </td>
                                                <td><?php echo htmlspecialchars($trigger['table_name']); ?></td>
                                                <td>
                                                    <span class="badge bg-secondary">
                                                        <?php echo $trigger['timing']; ?>
                                                    </span>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </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://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // DataTables başlat
            $('#adminNotificationsTable').DataTable({
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/tr.json"
                },
                "order": [[ 4, "desc" ]]
            });
            
            $('#securityAlertsTable').DataTable({
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/tr.json"
                },
                "order": [[ 4, "desc" ]]
            });
            
            $('#loyaltyStatsTable').DataTable({
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/tr.json"
                },
                "order": [[ 1, "desc" ]]
            });
            
            $('#triggersTable').DataTable({
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/tr.json"
                },
                "order": [[ 2, "asc" ]]
            });
        });
    </script>
</body>
</html>