<?php
/**
 * Story Kartları Listeleme Sayfası
 * Namaz Vakitleri Admin Panel
 */

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

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

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

$category_filter = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$type_filter = isset($_GET['type']) ? $_GET['type'] : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

try {
    $db = getDB();
    
    // Kategorileri al
    $stmt = $db->query("SELECT * FROM story_categories WHERE is_active = 1 ORDER BY sort_order");
    $categories = $stmt->fetchAll();
    
    // WHERE koşullarını oluştur
    $where_conditions = ["st.is_active = 1"];
    $params = [];
    
    if ($category_filter > 0) {
        $where_conditions[] = "st.category_id = ?";
        $params[] = $category_filter;
    }
    
    if (!empty($type_filter)) {
        $where_conditions[] = "st.content_type = ?";
        $params[] = $type_filter;
    }
    
    if (!empty($search)) {
        $where_conditions[] = "(st.title LIKE ? OR st.content LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    
    // Toplam kayıt sayısını al
    $count_sql = "
        SELECT COUNT(*) as total 
        FROM story_cards st 
        JOIN story_categories sc ON st.category_id = sc.id 
        WHERE $where_clause
    ";
    $stmt = $db->prepare($count_sql);
    $stmt->execute($params);
    $total_records = $stmt->fetch()['total'];
    $total_pages = ceil($total_records / $per_page);
    
    // Story'leri al
    $sql = "
        SELECT st.*, sc.display_name as category_name, sc.name as category_key,
               au.full_name as created_by_name
        FROM story_cards st 
        JOIN story_categories sc ON st.category_id = sc.id 
        JOIN admin_users au ON st.created_by = au.id
        WHERE $where_clause
        ORDER BY st.created_at DESC 
        LIMIT $per_page OFFSET $offset
    ";
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $stories = $stmt->fetchAll();
    
} catch (PDOException $e) {
    $_SESSION['error_message'] = 'Veritabanı hatası: ' . $e->getMessage();
    $categories = [];
    $stories = [];
    $total_records = 0;
    $total_pages = 0;
}

// Story silme işlemi
if (isset($_POST['delete_story'])) {
    $story_id = (int)$_POST['story_id'];
    
    try {
        $db = getDB();
        
        // Önce görseli sil (varsa)
        $stmt = $db->prepare("SELECT image_path FROM story_cards WHERE id = ?");
        $stmt->execute([$story_id]);
        $story = $stmt->fetch();
        
        if ($story && !empty($story['image_path'])) {
            $image_path = 'uploads/' . $story['image_path'];
            if (file_exists($image_path)) {
                unlink($image_path);
            }
        }
        
        // Story'yi sil
        $stmt = $db->prepare("DELETE FROM story_cards WHERE id = ?");
        $stmt->execute([$story_id]);
        
        $_SESSION['success_message'] = 'Story başarıyla silindi.';
        
    } catch (PDOException $e) {
        $_SESSION['error_message'] = 'Story silinirken hata oluştu: ' . $e->getMessage();
    }
    
    header('Location: story-cards.php');
    exit();
}
?>

<!-- Filtreleme Formu -->
<div class="card">
    <div class="card-header">
        <h3><i class="fas fa-filter"></i> Filtreleme ve Arama</h3>
    </div>
    <div class="card-body">
        <form method="GET" class="row" style="align-items: end;">
            <div class="col-md-3">
                <label class="form-label">Kategori</label>
                <select name="category" class="form-control">
                    <option value="">Tüm Kategoriler</option>
                    <?php foreach ($categories as $category): ?>
                        <option value="<?php echo $category['id']; ?>" 
                                <?php echo $category_filter == $category['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($category['display_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-2">
                <label class="form-label">Tür</label>
                <select name="type" class="form-control">
                    <option value="">Tüm Türler</option>
                    <option value="text" <?php echo $type_filter === 'text' ? 'selected' : ''; ?>>Metin</option>
                    <option value="image" <?php echo $type_filter === 'image' ? 'selected' : ''; ?>>Görsel</option>
                </select>
            </div>
            
            <div class="col-md-4">
                <label class="form-label">Arama</label>
                <input type="text" name="search" class="form-control" 
                       placeholder="Başlık veya içerik ara..." 
                       value="<?php echo htmlspecialchars($search); ?>">
            </div>
            
            <div class="col-md-3">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-search"></i> Filtrele
                </button>
                <a href="story-cards.php" class="btn btn-secondary">
                    <i class="fas fa-times"></i> Temizle
                </a>
            </div>
        </form>
    </div>
</div>

<!-- Story Listesi -->
<div class="card">
    <div class="card-header">
        <h3><i class="fas fa-list"></i> Story Kartları (<?php echo number_format($total_records); ?> kayıt)</h3>
    </div>
    <div class="card-body">
        <?php if (!empty($stories)): ?>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Başlık</th>
                            <th>Kategori</th>
                            <th>Tür</th>
                            <th>Görüntülenme</th>
                            <th>Oluşturan</th>
                            <th>Tarih</th>
                            <th>Durum</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($stories as $story): ?>
                            <tr>
                                <td><strong>#<?php echo $story['id']; ?></strong></td>
                                <td>
                                    <div style="max-width: 200px;">
                                        <strong><?php echo htmlspecialchars(mb_substr($story['title'], 0, 40)); ?></strong>
                                        <?php if (strlen($story['title']) > 40): ?>...<?php endif; ?>
                                        <br>
                                        <small style="color: #7f8c8d;">
                                            <?php echo htmlspecialchars(mb_substr(strip_tags($story['content']), 0, 60)); ?>
                                            <?php if (strlen(strip_tags($story['content'])) > 60): ?>...<?php endif; ?>
                                        </small>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge badge-info">
                                        <?php echo htmlspecialchars($story['category_name']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($story['content_type'] === 'image'): ?>
                                        <span class="badge badge-success">
                                            <i class="fas fa-image"></i> Görsel
                                        </span>
                                    <?php else: ?>
                                        <span class="badge badge-primary">
                                            <i class="fas fa-font"></i> Metin
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong><?php echo number_format($story['view_count']); ?></strong>
                                </td>
                                <td>
                                    <small><?php echo htmlspecialchars($story['created_by_name']); ?></small>
                                </td>
                                <td>
                                    <small><?php echo date('d.m.Y H:i', strtotime($story['created_at'])); ?></small>
                                </td>
                                <td>
                                    <?php if ($story['is_active']): ?>
                                        <span class="badge badge-success">Aktif</span>
                                    <?php else: ?>
                                        <span class="badge badge-danger">Pasif</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div style="display: flex; gap: 5px;">
                                        <a href="story-edit.php?id=<?php echo $story['id']; ?>" 
                                           class="btn btn-sm btn-primary" title="Düzenle">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        
                                        <form method="POST" style="display: inline;" 
                                              onsubmit="return confirmDelete('Bu story\'yi silmek istediğinizden emin misiniz?')">
                                            <input type="hidden" name="story_id" value="<?php echo $story['id']; ?>">
                                            <button type="submit" name="delete_story" 
                                                    class="btn btn-sm btn-danger" title="Sil">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Sayfalama -->
            <?php if ($total_pages > 1): ?>
                <div class="pagination">
                    <?php
                    $query_params = $_GET;
                    
                    // İlk sayfa
                    if ($page > 1):
                        $query_params['page'] = 1;
                        $query_string = http_build_query($query_params);
                    ?>
                        <a href="?<?php echo $query_string; ?>">&laquo; İlk</a>
                    <?php endif; ?>
                    
                    <?php
                    // Önceki sayfa
                    if ($page > 1):
                        $query_params['page'] = $page - 1;
                        $query_string = http_build_query($query_params);
                    ?>
                        <a href="?<?php echo $query_string; ?>">&lsaquo; Önceki</a>
                    <?php endif; ?>
                    
                    <?php
                    // Sayfa numaraları
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $page + 2);
                    
                    for ($i = $start; $i <= $end; $i++):
                        $query_params['page'] = $i;
                        $query_string = http_build_query($query_params);
                    ?>
                        <a href="?<?php echo $query_string; ?>" 
                           class="<?php echo $i === $page ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                    <?php endfor; ?>
                    
                    <?php
                    // Sonraki sayfa
                    if ($page < $total_pages):
                        $query_params['page'] = $page + 1;
                        $query_string = http_build_query($query_params);
                    ?>
                        <a href="?<?php echo $query_string; ?>">Sonraki &rsaquo;</a>
                    <?php endif; ?>
                    
                    <?php
                    // Son sayfa
                    if ($page < $total_pages):
                        $query_params['page'] = $total_pages;
                        $query_string = http_build_query($query_params);
                    ?>
                        <a href="?<?php echo $query_string; ?>">Son &raquo;</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            
        <?php else: ?>
            <div style="text-align: center; padding: 40px; color: #7f8c8d;">
                <i class="fas fa-images" style="font-size: 48px; margin-bottom: 20px;"></i>
                <h4>Henüz story bulunmuyor</h4>
                <p>İlk story'nizi eklemek için aşağıdaki butona tıklayın.</p>
                <a href="story-add.php" class="btn btn-success">
                    <i class="fas fa-plus"></i> Yeni Story Ekle
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

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