<?php
/**
 * Bildirim Geçmişi Sayfası
 * Gönderilen bildirimlerin listesi ve detayları
 */

require_once 'config/database.php';

$page_title = 'Bildirim Geçmişi';

// Database bağlantısı
$database = new Database();
$db = $database->getConnection();

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

// Filtreleme parametreleri
$status_filter = $_GET['status'] ?? '';
$date_filter = $_GET['date'] ?? '';
$search = $_GET['search'] ?? '';

// Toplam kayıt sayısını hesapla
$count_query = "SELECT COUNT(*) as total FROM sent_notifications sn LEFT JOIN admin_users au ON sn.sent_by = au.id WHERE 1=1";
$count_params = [];

if (!empty($status_filter)) {
    $count_query .= " AND sn.status = ?";
    $count_params[] = $status_filter;
}

if (!empty($date_filter)) {
    $count_query .= " AND DATE(sn.sent_at) = ?";
    $count_params[] = $date_filter;
}

if (!empty($search)) {
    $count_query .= " AND (sn.title LIKE ? OR sn.body LIKE ?)";
    $count_params[] = "%$search%";
    $count_params[] = "%$search%";
}

try {
    $count_stmt = $db->prepare($count_query);
    $count_stmt->execute($count_params);
    $total_records = $count_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    $total_pages = ceil($total_records / $limit);
} catch (Exception $e) {
    $total_records = 0;
    $total_pages = 0;
}

// Bildirimleri getir
$query = "
    SELECT sn.*, au.username, au.full_name,
           nt.name as template_name
    FROM sent_notifications sn 
    LEFT JOIN admin_users au ON sn.sent_by = au.id 
    LEFT JOIN notification_templates nt ON sn.template_id = nt.id
    WHERE 1=1
";

$params = [];

if (!empty($status_filter)) {
    $query .= " AND sn.status = ?";
    $params[] = $status_filter;
}

if (!empty($date_filter)) {
    $query .= " AND DATE(sn.sent_at) = ?";
    $params[] = $date_filter;
}

if (!empty($search)) {
    $query .= " AND (sn.title LIKE ? OR sn.body LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$query .= " ORDER BY sn.sent_at DESC LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;

try {
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $notifications = [];
    $_SESSION['error_message'] = "Bildirimler yüklenirken hata oluştu: " . $e->getMessage();
}

// İstatistikler
$stats = [];
try {
    $stats_query = "
        SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent,
            SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed,
            SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
            SUM(sent_count) as total_sent,
            SUM(failed_count) as total_failed
        FROM sent_notifications
    ";
    $stats_stmt = $db->prepare($stats_query);
    $stats_stmt->execute();
    $stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $stats = [
        'total' => 0,
        'sent' => 0,
        'failed' => 0,
        'pending' => 0,
        'total_sent' => 0,
        'total_failed' => 0
    ];
}

include 'includes/header.php';
?>

<div class="page-header">
    <h2>Bildirim Geçmişi</h2>
    <p>Gönderilen bildirimlerin listesi ve detayları</p>
</div>

<!-- İstatistikler -->
<div class="stats-container">
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-bell"></i>
        </div>
        <div class="stat-content">
            <div class="stat-number"><?php echo number_format($stats['total']); ?></div>
            <div class="stat-label">Toplam Bildirim</div>
        </div>
    </div>
    
    <div class="stat-card success">
        <div class="stat-icon">
            <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-content">
            <div class="stat-number"><?php echo number_format($stats['sent']); ?></div>
            <div class="stat-label">Başarılı</div>
        </div>
    </div>
    
    <div class="stat-card error">
        <div class="stat-icon">
            <i class="fas fa-times-circle"></i>
        </div>
        <div class="stat-content">
            <div class="stat-number"><?php echo number_format($stats['failed']); ?></div>
            <div class="stat-label">Başarısız</div>
        </div>
    </div>
    
    <div class="stat-card warning">
        <div class="stat-icon">
            <i class="fas fa-clock"></i>
        </div>
        <div class="stat-content">
            <div class="stat-number"><?php echo number_format($stats['pending']); ?></div>
            <div class="stat-label">Beklemede</div>
        </div>
    </div>
</div>

<!-- Filtreler -->
<div class="filters-container">
    <form method="GET" class="filters-form">
        <div class="filter-group">
            <label for="search">Arama</label>
            <input type="text" id="search" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                   placeholder="Başlık veya mesaj ara...">
        </div>
        
        <div class="filter-group">
            <label for="status">Durum</label>
            <select id="status" name="status">
                <option value="">Tümü</option>
                <option value="sent" <?php echo $status_filter === 'sent' ? 'selected' : ''; ?>>Gönderildi</option>
                <option value="failed" <?php echo $status_filter === 'failed' ? 'selected' : ''; ?>>Başarısız</option>
                <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Beklemede</option>
            </select>
        </div>
        
        <div class="filter-group">
            <label for="date">Tarih</label>
            <input type="date" id="date" name="date" value="<?php echo htmlspecialchars($date_filter); ?>">
        </div>
        
        <div class="filter-actions">
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-search"></i>
                Filtrele
            </button>
            <a href="notification-history.php" class="btn btn-secondary">
                <i class="fas fa-times"></i>
                Temizle
            </a>
        </div>
    </form>
</div>

<!-- Bildirim Listesi -->
<div class="notifications-list">
    <?php if (empty($notifications)): ?>
        <div class="no-data">
            <i class="fas fa-bell-slash"></i>
            <h3>Bildirim bulunamadı</h3>
            <p>Henüz hiç bildirim gönderilmemiş veya arama kriterlerinize uygun bildirim yok.</p>
            <a href="notifications.php" class="btn btn-primary">
                <i class="fas fa-plus"></i>
                İlk Bildirimi Gönder
            </a>
        </div>
    <?php else: ?>
        <?php foreach ($notifications as $notification): ?>
            <div class="notification-item" data-id="<?php echo $notification['id']; ?>">
                <div class="notification-header">
                    <div class="notification-title-section">
                        <h3 class="notification-title"><?php echo htmlspecialchars($notification['title']); ?></h3>
                        <span class="status-badge status-<?php echo $notification['status']; ?>">
                            <?php echo ucfirst($notification['status']); ?>
                        </span>
                    </div>
                    <div class="notification-meta">
                        <span class="notification-date">
                            <i class="fas fa-calendar"></i>
                            <?php echo date('d.m.Y H:i', strtotime($notification['sent_at'])); ?>
                        </span>
                        <span class="notification-sender">
                            <i class="fas fa-user"></i>
                            <?php echo htmlspecialchars($notification['full_name'] ?: $notification['username']); ?>
                        </span>
                    </div>
                </div>
                
                <div class="notification-body">
                    <p><?php echo htmlspecialchars($notification['body']); ?></p>
                </div>
                
                <div class="notification-details">
                    <div class="detail-row">
                        <div class="detail-item">
                            <span class="detail-label">Hedef:</span>
                            <span class="detail-value">
                                <?php 
                                switch($notification['target_type']) {
                                    case 'all':
                                        echo 'Tüm Kullanıcılar';
                                        break;
                                    case 'topic':
                                        echo 'Topic: ' . htmlspecialchars($notification['target_value']);
                                        break;
                                    case 'token':
                                        echo 'Cihaz: ' . substr($notification['target_value'], 0, 20) . '...';
                                        break;
                                }
                                ?>
                            </span>
                        </div>
                        
                        <?php if ($notification['template_name']): ?>
                            <div class="detail-item">
                                <span class="detail-label">Şablon:</span>
                                <span class="detail-value"><?php echo htmlspecialchars($notification['template_name']); ?></span>
                            </div>
                        <?php endif; ?>
                        
                        <div class="detail-item">
                            <span class="detail-label">İkon:</span>
                            <span class="detail-value"><?php echo htmlspecialchars($notification['icon']); ?></span>
                        </div>
                        
                        <div class="detail-item">
                            <span class="detail-label">Ses:</span>
                            <span class="detail-value"><?php echo htmlspecialchars($notification['sound']); ?></span>
                        </div>
                    </div>
                    
                    <?php if ($notification['status'] === 'sent' && ($notification['sent_count'] > 0 || $notification['failed_count'] > 0)): ?>
                        <div class="delivery-stats">
                            <span class="delivery-success">
                                <i class="fas fa-check"></i>
                                <?php echo $notification['sent_count']; ?> başarılı
                            </span>
                            <?php if ($notification['failed_count'] > 0): ?>
                                <span class="delivery-failed">
                                    <i class="fas fa-times"></i>
                                    <?php echo $notification['failed_count']; ?> başarısız
                                </span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    
                    <div class="notification-actions">
                        <button class="btn btn-sm btn-outline" onclick="toggleDetails(<?php echo $notification['id']; ?>)">
                            <i class="fas fa-eye"></i>
                            Detayları Göster
                        </button>
                        
                        <?php if ($notification['status'] === 'failed'): ?>
                            <button class="btn btn-sm btn-warning" onclick="retryNotification(<?php echo $notification['id']; ?>)">
                                <i class="fas fa-redo"></i>
                                Tekrar Gönder
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="notification-response" id="response-<?php echo $notification['id']; ?>" style="display: none;">
                    <h4>Firebase Yanıtı:</h4>
                    <pre><?php echo htmlspecialchars($notification['response_data']); ?></pre>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- Sayfalama -->
<?php if ($total_pages > 1): ?>
    <div class="pagination">
        <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>&<?php echo http_build_query(array_filter($_GET, function($key) { return $key !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>" 
               class="pagination-btn">
                <i class="fas fa-chevron-left"></i>
                Önceki
            </a>
        <?php endif; ?>
        
        <div class="pagination-info">
            Sayfa <?php echo $page; ?> / <?php echo $total_pages; ?> 
            (<?php echo number_format($total_records); ?> kayıt)
        </div>
        
        <?php if ($page < $total_pages): ?>
            <a href="?page=<?php echo $page + 1; ?>&<?php echo http_build_query(array_filter($_GET, function($key) { return $key !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>" 
               class="pagination-btn">
                Sonraki
                <i class="fas fa-chevron-right"></i>
            </a>
        <?php endif; ?>
    </div>
<?php endif; ?>

<script>
function toggleDetails(notificationId) {
    const responseDiv = document.getElementById('response-' + notificationId);
    const button = event.target.closest('button');
    
    if (responseDiv.style.display === 'none') {
        responseDiv.style.display = 'block';
        button.innerHTML = '<i class="fas fa-eye-slash"></i> Detayları Gizle';
    } else {
        responseDiv.style.display = 'none';
        button.innerHTML = '<i class="fas fa-eye"></i> Detayları Göster';
    }
}

function retryNotification(notificationId) {
    if (confirm('Bu bildirimi tekrar göndermek istediğinizden emin misiniz?')) {
        // AJAX ile tekrar gönderme işlemi
        fetch('api/retry-notification.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ notification_id: notificationId })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Bildirim tekrar gönderildi');
                location.reload();
            } else {
                alert('Hata: ' + data.message);
            }
        })
        .catch(error => {
            alert('Bir hata oluştu: ' + error.message);
        });
    }
}
</script>

<style>
.stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}

.stat-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    display: flex;
    align-items: center;
    gap: 1rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border-left: 4px solid #e5e7eb;
}

.stat-card.success {
    border-left-color: #10b981;
}

.stat-card.error {
    border-left-color: #ef4444;
}

.stat-card.warning {
    border-left-color: #f59e0b;
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: #f3f4f6;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    color: #6b7280;
}

.stat-card.success .stat-icon {
    background: #d1fae5;
    color: #065f46;
}

.stat-card.error .stat-icon {
    background: #fee2e2;
    color: #991b1b;
}

.stat-card.warning .stat-icon {
    background: #fef3c7;
    color: #92400e;
}

.stat-number {
    font-size: 2rem;
    font-weight: 700;
    color: #1f2937;
}

.stat-label {
    color: #6b7280;
    font-size: 0.9rem;
}

.filters-container {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 2rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.filters-form {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr auto;
    gap: 1rem;
    align-items: end;
}

.filter-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 600;
    color: #333;
}

.filter-group input, .filter-group select {
    width: 100%;
    padding: 0.75rem;
    border: 2px solid #e1e5e9;
    border-radius: 8px;
    font-size: 0.9rem;
}

.filter-actions {
    display: flex;
    gap: 0.5rem;
}

.notifications-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.notification-item {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border-left: 4px solid #e5e7eb;
}

.notification-item[data-status="sent"] {
    border-left-color: #10b981;
}

.notification-item[data-status="failed"] {
    border-left-color: #ef4444;
}

.notification-item[data-status="pending"] {
    border-left-color: #f59e0b;
}

.notification-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 1rem;
}

.notification-title-section {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.notification-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: #1f2937;
    margin: 0;
}

.notification-meta {
    display: flex;
    gap: 1rem;
    font-size: 0.9rem;
    color: #6b7280;
}

.notification-body {
    margin-bottom: 1rem;
    color: #374151;
    line-height: 1.6;
}

.notification-details {
    border-top: 1px solid #e5e7eb;
    padding-top: 1rem;
}

.detail-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 1rem;
}

.detail-item {
    display: flex;
    gap: 0.5rem;
}

.detail-label {
    font-weight: 600;
    color: #6b7280;
    min-width: 60px;
}

.detail-value {
    color: #1f2937;
}

.delivery-stats {
    display: flex;
    gap: 1rem;
    margin-bottom: 1rem;
    font-size: 0.9rem;
}

.delivery-success {
    color: #065f46;
}

.delivery-failed {
    color: #991b1b;
}

.notification-actions {
    display: flex;
    gap: 0.5rem;
}

.notification-response {
    margin-top: 1rem;
    padding: 1rem;
    background: #f9fafb;
    border-radius: 8px;
    border: 1px solid #e5e7eb;
}

.notification-response h4 {
    margin: 0 0 0.5rem 0;
    color: #374151;
}

.notification-response pre {
    background: #1f2937;
    color: #f9fafb;
    padding: 1rem;
    border-radius: 6px;
    overflow-x: auto;
    font-size: 0.8rem;
    margin: 0;
}

.pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 2rem;
    padding: 1rem;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.pagination-btn {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1rem;
    background: #4f46e5;
    color: white;
    text-decoration: none;
    border-radius: 8px;
    font-weight: 600;
    transition: all 0.3s;
}

.pagination-btn:hover {
    background: #4338ca;
    transform: translateY(-2px);
}

.pagination-info {
    color: #6b7280;
    font-weight: 600;
}

.no-data {
    text-align: center;
    padding: 3rem;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.no-data i {
    font-size: 4rem;
    color: #d1d5db;
    margin-bottom: 1rem;
}

.no-data h3 {
    color: #374151;
    margin-bottom: 0.5rem;
}

.no-data p {
    color: #6b7280;
    margin-bottom: 2rem;
}

.btn {
    padding: 0.75rem 1.5rem;
    border: none;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    text-decoration: none;
    transition: all 0.3s;
}

.btn-sm {
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
}

.btn-primary {
    background: linear-gradient(135deg, #4f46e5, #7c3aed);
    color: white;
}

.btn-secondary {
    background: #f3f4f6;
    color: #374151;
}

.btn-outline {
    background: transparent;
    border: 2px solid #e5e7eb;
    color: #374151;
}

.btn-warning {
    background: #f59e0b;
    color: white;
}

.status-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-weight: 600;
    text-transform: uppercase;
    font-size: 0.7rem;
}

.status-sent {
    background: #d1fae5;
    color: #065f46;
}

.status-failed {
    background: #fee2e2;
    color: #991b1b;
}

.status-pending {
    background: #fef3c7;
    color: #92400e;
}

@media (max-width: 768px) {
    .filters-form {
        grid-template-columns: 1fr;
    }
    
    .notification-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 1rem;
    }
    
    .notification-meta {
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .detail-row {
        grid-template-columns: 1fr;
    }
    
    .pagination {
        flex-direction: column;
        gap: 1rem;
    }
}
</style>

<?php include 'includes/footer.php'; ?>
