<?php
/**
 * صفحة المدونة - عرض المنشورات
 */

session_start();
require_once '../includes/product-card.php';
require_once '../config/database.php';

$database = new Database();
$conn = $database->getConnection();

// جلب إعدادات الموقع
$site_name = 'Roz Skin';
$logo_text = 'Roz Skin';

// الفلترة
$category = $_GET['category'] ?? '';
$search = $_GET['search'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 9;
$offset = ($page - 1) * $per_page;

$where = ["status = 'published'"];
$params = [];

if ($category) {
    $where[] = "category = ?";
    $params[] = $category;
}

if ($search) {
    $where[] = "(title LIKE ? OR content LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = implode(' AND ', $where);

// جلب المنشورات
$stmt = $conn->prepare("SELECT * FROM posts WHERE $where_clause ORDER BY is_featured DESC, published_at DESC LIMIT $per_page OFFSET $offset");
$stmt->execute($params);
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// عدد المنشورات للترقيم
$count_stmt = $conn->prepare("SELECT COUNT(*) FROM posts WHERE $where_clause");
$count_stmt->execute($params);
$total_posts = $count_stmt->fetchColumn();
$total_pages = ceil($total_posts / $per_page);

// جلب الفئات
try {
    $categories = $conn->query("SELECT * FROM post_categories WHERE is_active = 1 ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Fallback: جلب الفئات من المنشورات مباشرة
    $categories = [];
    $cats = $conn->query("SELECT DISTINCT category FROM posts WHERE status = 'published' AND category IS NOT NULL AND category != '' ORDER BY category")->fetchAll(PDO::FETCH_COLUMN);
    foreach ($cats as $cat_name) {
        $categories[] = [
            'name' => $cat_name,
            'icon' => '📝',
            'color' => '#E57393'
        ];
    }
}

// جلب المنشورات المميزة
$featured_posts = $conn->query("SELECT * FROM posts WHERE status = 'published' AND is_featured = 1 ORDER BY published_at DESC LIMIT 3")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>المدونة - <?php echo $site_name; ?></title>
    
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/pinterest-style.css">
    
    <style>
        * { font-family: 'Tajawal', sans-serif; }
        
        .blog-hero {
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            color: white;
            padding: 80px 20px;
            text-align: center;
        }
        
        .blog-hero h1 {
            font-size: 48px;
            margin-bottom: 20px;
        }
        
        .blog-hero p {
            font-size: 20px;
            opacity: 0.9;
        }
        
        .search-box {
            max-width: 600px;
            margin: 30px auto 0;
            position: relative;
        }
        
        .search-box input {
            width: 100%;
            padding: 15px 50px 15px 20px;
            border: none;
            border-radius: 50px;
            font-size: 16px;
        }
        
        .search-box button {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: #E57393;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 50px;
            cursor: pointer;
        }
        
        .categories-bar {
            background: white;
            padding: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 40px;
        }
        
        .categories-scroll {
            display: flex;
            gap: 15px;
            overflow-x: auto;
            padding: 10px 0;
        }
        
        .category-chip {
            padding: 10px 20px;
            border-radius: 50px;
            border: 2px solid #E57393;
            background: white;
            color: #E57393;
            text-decoration: none;
            white-space: nowrap;
            transition: all 0.3s;
        }
        
        .category-chip:hover,
        .category-chip.active {
            background: #E57393;
            color: white;
        }
        
        .posts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 30px;
            margin-bottom: 60px;
        }
        
        .post-card {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
        }
        
        .post-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .post-image {
            width: 100%;
            height: 220px;
            object-fit: cover;
        }
        
        .post-content {
            padding: 20px;
        }
        
        .post-category {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 10px;
        }
        
        .post-title {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 10px;
            color: #333;
        }
        
        .post-excerpt {
            color: #666;
            font-size: 14px;
            line-height: 1.6;
            margin-bottom: 15px;
        }
        
        .post-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #999;
            font-size: 13px;
        }
        
        .featured-badge {
            position: absolute;
            top: 15px;
            right: 15px;
            background: #F39C12;
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin: 40px 0;
        }
        
        .pagination a,
        .pagination span {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            text-decoration: none;
            color: #333;
        }
        
        .pagination a:hover {
            background: #E57393;
            color: white;
            border-color: #E57393;
        }
        
        .pagination .active {
            background: #E57393;
            color: white;
            border-color: #E57393;
        }
    </style>
    <link rel="stylesheet" href="../assets/css/product-cards.css">
</head>
<body>

    <!-- Navigation -->
    <nav class="nav-pinterest">
        <div class="container-pinterest">
            <div class="nav-content">
                <a href="index.php" class="nav-logo"><?php echo $logo_text; ?></a>
                <div class="nav-actions">
                    <a href="index.php" class="nav-icon-btn">الرئيسية</a>
                    <a href="products.php" class="nav-icon-btn">المنتجات</a>
                    <a href="blog.php" class="nav-icon-btn" style="color: #E57393;">المدونة</a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Hero -->
    <section class="blog-hero">
        <h1>📰 مدونة روز سكين</h1>
        <p>نصائح جمالية، أخبار المتجر، وكل ما يهمك في عالم العناية بالبشرة</p>
        
        <form method="GET" class="search-box">
            <input type="text" name="search" placeholder="ابحث في المدونة..." value="<?php echo htmlspecialchars($search); ?>">
            <button type="submit">بحث</button>
        </form>
    </section>

    <!-- Categories -->
    <section class="categories-bar">
        <div class="container-pinterest">
            <div class="categories-scroll">
                <a href="blog.php" class="category-chip <?php echo !$category ? 'active' : ''; ?>">
                    الكل
                </a>
                <?php foreach ($categories as $cat): ?>
                    <a href="?category=<?php echo urlencode($cat['name']); ?>" 
                       class="category-chip <?php echo $category == $cat['name'] ? 'active' : ''; ?>">
                        <?php echo $cat['icon'] . ' ' . $cat['name']; ?>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
    </section>

    <!-- Posts Grid -->
    <section style="padding: 40px 20px;">
        <div class="container-pinterest">
            <?php if (empty($posts)): ?>
                <div style="text-align: center; padding: 60px 20px; color: #999;">
                    <h2>لا توجد منشورات</h2>
                    <p>جرب البحث بكلمات أخرى أو تصفح فئة مختلفة</p>
                </div>
            <?php else: ?>
                <div class="posts-grid">
                    <?php foreach ($posts as $post): ?>
                        <div class="post-card" onclick="window.location.href='blog-post.php?slug=<?php echo $post['slug']; ?>'">
                            <?php if ($post['is_featured']): ?>
                                <span class="featured-badge">⭐ مميز</span>
                            <?php endif; ?>
                            
                            <?php if ($post['featured_image']): ?>
                                <img src="../<?php echo $post['featured_image']; ?>" class="post-image" alt="<?php echo htmlspecialchars($post['title']); ?>">
                            <?php else: ?>
                                <div class="post-image" style="background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); display: flex; align-items: center; justify-content: center; color: white; font-size: 48px;">
                                    📝
                                </div>
                            <?php endif; ?>
                            
                            <div class="post-content">
                                <?php 
                                $cat = array_filter($categories, fn($c) => $c['name'] == $post['category']);
                                $cat = reset($cat);
                                if ($cat): ?>
                                    <span class="post-category" style="background: <?php echo $cat['color']; ?>; color: white;">
                                        <?php echo $cat['icon'] . ' ' . $cat['name']; ?>
                                    </span>
                                <?php endif; ?>
                                
                                <h3 class="post-title"><?php echo htmlspecialchars($post['title']); ?></h3>
                                <p class="post-excerpt"><?php echo htmlspecialchars(substr($post['excerpt'], 0, 120)) . '...'; ?></p>
                                
                                <div class="post-meta">
                                    <span>👁️ <?php echo number_format($post['views_count']); ?> مشاهدة</span>
                                    <span><?php echo date('Y-m-d', strtotime($post['published_at'])); ?></span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): 
                    // Build query parameters
                    $query_params = [];
                    if ($category) $query_params['category'] = $category;
                    if ($search) $query_params['search'] = $search;
                ?>
                    <div class="pagination">
                        <?php if ($page > 1): 
                            $prev_params = array_merge($query_params, ['page' => $page - 1]);
                        ?>
                            <a href="?<?php echo http_build_query($prev_params); ?>">السابق</a>
                        <?php endif; ?>
                        
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <?php if ($i == $page): ?>
                                <span class="active"><?php echo $i; ?></span>
                            <?php else: 
                                $page_params = array_merge($query_params, ['page' => $i]);
                            ?>
                                <a href="?<?php echo http_build_query($page_params); ?>"><?php echo $i; ?></a>
                            <?php endif; ?>
                        <?php endfor; ?>
                        
                        <?php if ($page < $total_pages): 
                            $next_params = array_merge($query_params, ['page' => $page + 1]);
                        ?>
                            <a href="?<?php echo http_build_query($next_params); ?>">التالي</a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </section>

</body>
</html>
