<?php
/**
 * Admin Panel Dashboard
 * Namaz Vakitleri Admin Panel
 */

$page_title = 'Dashboard';
$header_actions = '<a href="story-add.php" class="btn btn-primary"><i class="fas fa-plus"></i> Yeni Story Ekle</a>';

require_once 'config/database.php';
require_once 'includes/header.php';

try {
    $db = getDB();
    
    // İstatistikleri al
    $stats = [];
    
    // Toplam story sayısı
    $stmt = $db->query("SELECT COUNT(*) as total FROM story_cards WHERE is_active = 1");
    $stats['total_stories'] = $stmt->fetch()['total'];
    
    // Kategori bazlı story sayıları
    $stmt = $db->query("
        SELECT sc.display_name, COUNT(st.id) as count 
        FROM story_categories sc 
        LEFT JOIN story_cards st ON sc.id = st.category_id AND st.is_active = 1
        WHERE sc.is_active = 1 
        GROUP BY sc.id, sc.display_name 
        ORDER BY sc.sort_order
    ");
    $category_stats = $stmt->fetchAll();
    
    // Toplam görüntülenme sayısı
    $stmt = $db->query("SELECT SUM(view_count) as total_views FROM story_cards WHERE is_active = 1");
    $stats['total_views'] = $stmt->fetch()['total_views'] ?? 0;
    
    // Bu ayki görüntülenme sayısı
    $stmt = $db->query("
        SELECT SUM(view_count) as monthly_views 
        FROM story_stats 
        WHERE MONTH(date_viewed) = MONTH(CURRENT_DATE()) 
        AND YEAR(date_viewed) = YEAR(CURRENT_DATE())
    ");
    $stats['monthly_views'] = $stmt->fetch()['monthly_views'] ?? 0;
    
    // Son eklenen story'ler
    $stmt = $db->query("
        SELECT st.*, sc.display_name as category_name 
        FROM story_cards st 
        JOIN story_categories sc ON st.category_id = sc.id 
        WHERE st.is_active = 1 
        ORDER BY st.created_at DESC 
        LIMIT 5
    ");
    $recent_stories = $stmt->fetchAll();
    
    // En popüler story'ler
    $stmt = $db->query("
        SELECT st.*, sc.display_name as category_name 
        FROM story_cards st 
        JOIN story_categories sc ON st.category_id = sc.id 
        WHERE st.is_active = 1 
        ORDER BY st.view_count DESC 
        LIMIT 5
    ");
    $popular_stories = $stmt->fetchAll();
    
} catch (PDOException $e) {
    $_SESSION['error_message'] = 'Veritabanı hatası: ' . $e->getMessage();
    $stats = ['total_stories' => 0, 'total_views' => 0, 'monthly_views' => 0];
    $category_stats = [];
    $recent_stories = [];
    $popular_stories = [];
}
?>

<!-- Dark Mode Toggle -->
<div class="card" style="margin-bottom: 20px;">
    <div class="card-header">
        <h3><i class="fas fa-palette"></i> Tema Ayarları</h3>
    </div>
    <div class="card-body">
        <div class="theme-toggle">
            <label class="toggle-label">
                <input type="radio" name="theme" value="light" <?php echo (!isset($_COOKIE['dark_mode']) || $_COOKIE['dark_mode'] !== 'true') ? 'checked' : ''; ?> onchange="toggleTheme('light')">
                <i class="fas fa-sun"></i> Light Mode
            </label>
            <label class="toggle-label">
                <input type="radio" name="theme" value="dark" <?php echo (isset($_COOKIE['dark_mode']) && $_COOKIE['dark_mode'] === 'true') ? 'checked' : ''; ?> onchange="toggleTheme('dark')">
                <i class="fas fa-moon"></i> Dark Mode
            </label>
        </div>
    </div>
</div>

<!-- Stats Cards -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-number"><?php echo number_format($stats['total_stories']); ?></div>
        <div class="stat-label">Toplam Story</div>
    </div>
    
    <div class="stat-card">
        <div class="stat-number"><?php echo number_format($stats['total_views']); ?></div>
        <div class="stat-label">Toplam Görüntülenme</div>
    </div>
    
    <div class="stat-card">
        <div class="stat-number"><?php echo number_format($stats['monthly_views']); ?></div>
        <div class="stat-label">Bu Ay Görüntülenme</div>
    </div>
    
    <div class="stat-card">
        <div class="stat-number"><?php echo count($category_stats); ?></div>
        <div class="stat-label">Aktif Kategori</div>
    </div>
</div>

<!-- Content Grid -->
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 30px;">
    <!-- Kategori İstatistikleri -->
    <div class="card">
        <div class="card-header">
            <h3><i class="fas fa-chart-pie"></i> Kategori İstatistikleri</h3>
        </div>
        <div class="card-body">
            <?php if (!empty($category_stats)): ?>
                <?php foreach ($category_stats as $category): ?>
                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid #ecf0f1;">
                        <span style="font-weight: 500;"><?php echo htmlspecialchars($category['display_name']); ?></span>
                        <span class="badge badge-info"><?php echo $category['count']; ?> story</span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <p style="text-align: center; color: #7f8c8d; margin: 20px 0;">Henüz kategori bulunmuyor.</p>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Hızlı İşlemler -->
    <div class="card">
        <div class="card-header">
            <h3><i class="fas fa-bolt"></i> Hızlı İşlemler</h3>
        </div>
        <div class="card-body">
            <div style="display: grid; gap: 15px;">
                <a href="story-add.php" class="btn btn-success" style="justify-content: center;">
                    <i class="fas fa-plus-circle"></i> Yeni Story Ekle
                </a>
                
                <a href="story-cards.php" class="btn btn-primary" style="justify-content: center;">
                    <i class="fas fa-list"></i> Tüm Story'leri Görüntüle
                </a>
                
                <a href="categories.php" class="btn btn-secondary" style="justify-content: center;">
                    <i class="fas fa-tags"></i> Kategorileri Yönet
                </a>
                
                <a href="statistics.php" class="btn btn-info" style="justify-content: center;">
                    <i class="fas fa-chart-bar"></i> Detaylı İstatistikler
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Son Eklenen Story'ler -->
<div class="card">
    <div class="card-header">
        <h3><i class="fas fa-clock"></i> Son Eklenen Story'ler</h3>
    </div>
    <div class="card-body">
        <?php if (!empty($recent_stories)): ?>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Başlık</th>
                            <th>Kategori</th>
                            <th>Tür</th>
                            <th>Görüntülenme</th>
                            <th>Tarih</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recent_stories as $story): ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars(mb_substr($story['title'], 0, 50)); ?></strong>
                                    <?php if (strlen($story['title']) > 50): ?>...<?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge badge-info"><?php echo htmlspecialchars($story['category_name']); ?></span>
                                </td>
                                <td>
                                    <?php if ($story['content_type'] === 'image'): ?>
                                        <i class="fas fa-image" style="color: #27ae60;"></i> Görsel
                                    <?php else: ?>
                                        <i class="fas fa-font" style="color: #3498db;"></i> Metin
                                    <?php endif; ?>
                                </td>
                                <td><?php echo number_format($story['view_count']); ?></td>
                                <td><?php echo date('d.m.Y H:i', strtotime($story['created_at'])); ?></td>
                                <td>
                                    <a href="story-edit.php?id=<?php echo $story['id']; ?>" class="btn btn-sm btn-primary">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <p style="text-align: center; color: #7f8c8d; margin: 20px 0;">Henüz story eklenmemiş.</p>
        <?php endif; ?>
    </div>
</div>

<!-- En Popüler Story'ler -->
<div class="card">
    <div class="card-header">
        <h3><i class="fas fa-fire"></i> En Popüler Story'ler</h3>
    </div>
    <div class="card-body">
        <?php if (!empty($popular_stories)): ?>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Başlık</th>
                            <th>Kategori</th>
                            <th>Tür</th>
                            <th>Görüntülenme</th>
                            <th>Tarih</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($popular_stories as $story): ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars(mb_substr($story['title'], 0, 50)); ?></strong>
                                    <?php if (strlen($story['title']) > 50): ?>...<?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge badge-info"><?php echo htmlspecialchars($story['category_name']); ?></span>
                                </td>
                                <td>
                                    <?php if ($story['content_type'] === 'image'): ?>
                                        <i class="fas fa-image" style="color: #27ae60;"></i> Görsel
                                    <?php else: ?>
                                        <i class="fas fa-font" style="color: #3498db;"></i> Metin
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong style="color: #e74c3c;"><?php echo number_format($story['view_count']); ?></strong>
                                </td>
                                <td><?php echo date('d.m.Y H:i', strtotime($story['created_at'])); ?></td>
                                <td>
                                    <a href="story-edit.php?id=<?php echo $story['id']; ?>" class="btn btn-sm btn-primary">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <p style="text-align: center; color: #7f8c8d; margin: 20px 0;">Henüz story eklenmemiş.</p>
        <?php endif; ?>
    </div>
</div>

<script>
function toggleTheme(theme) {
    if (theme === 'dark') {
        document.cookie = "dark_mode=true; path=/; max-age=" + (365*24*60*60);
        location.reload();
    } else {
        document.cookie = "dark_mode=false; path=/; max-age=" + (365*24*60*60);
        location.reload();
    }
}
</script>

<style>
/* Theme Toggle Styles */
.theme-toggle {
    display: flex;
    gap: 20px;
    align-items: center;
}

.toggle-label {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    padding: 10px 15px;
    border-radius: 8px;
    transition: all 0.3s ease;
    border: 2px solid transparent;
}

.toggle-label:hover {
    background: rgba(52, 152, 219, 0.1);
    border-color: rgba(52, 152, 219, 0.3);
}

.toggle-label input[type="radio"] {
    margin: 0;
}

.toggle-label input[type="radio"]:checked {
    accent-color: #3498db;
}

.toggle-label i {
    font-size: 16px;
    transition: color 0.3s ease;
}

.toggle-label input[type="radio"]:checked ~ i {
    color: #3498db;
}

@media (max-width: 768px) {
    .theme-toggle {
        flex-direction: column;
        gap: 10px;
    }
}
</style>

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