<?php
// Connect to the database using the existing config
require_once 'admin/config/db.php';

// Fetch all categories for filtering (optional but good for UI)
$cat_stmt = $pdo->query("SELECT * FROM portfolio_categories WHERE status = 'active' ORDER BY name ASC");
$categories = $cat_stmt->fetchAll();

// Fetch all subcategories to nest within the sidebar
$sub_stmt = $pdo->query("SELECT * FROM portfolio_subcategories WHERE status = 'active' ORDER BY name ASC");
$subcats_raw = $sub_stmt->fetchAll();

// Group subcategories by category_id for easier looping in the view
$subcategories = [];
foreach ($subcats_raw as $sub) {
    $subcategories[$sub['category_id']][] = $sub;
}

// Fetch categorized project counts for sidebar
$cat_count_stmt = $pdo->query("
    SELECT c.*, COUNT(p.id) as project_count 
    FROM portfolio_categories c 
    LEFT JOIN portfolio_items p ON c.id = p.category_id AND p.status = 'published'
    WHERE c.status = 'active'
    GROUP BY c.id 
    ORDER BY c.name ASC
");
$categories_with_count = $cat_count_stmt->fetchAll();

// Fetch all subcategories to nest within the sidebar
$sub_stmt = $pdo->query("SELECT * FROM portfolio_subcategories WHERE status = 'active' ORDER BY name ASC");
$subcats_raw = $sub_stmt->fetchAll();

// Group subcategories by category_id
$subcategories = [];
foreach ($subcats_raw as $sub) {
    $subcategories[$sub['category_id']][] = $sub;
}

// Fetch "Recent Posts" (Top 4 latest)
$recent_stmt = $pdo->query("
    SELECT * FROM portfolio_items 
    WHERE status = 'published' 
    ORDER BY created_at DESC 
    LIMIT 4
");
$recent_posts = $recent_stmt->fetchAll();

// Pagination and Filtering logic
$page = isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0 ? (int)$_GET['page'] : 1;
$per_page = 4;
$offset = ($page - 1) * $per_page;

$category_filter = isset($_GET['category']) ? trim($_GET['category']) : '';
$subcategory_filter = isset($_GET['subcategory']) ? trim($_GET['subcategory']) : '';
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';

$where_clause = "WHERE p.status = 'published'";
$params = [];

if ($category_filter) {
    $where_clause .= " AND c.slug = ?";
    $params[] = $category_filter;
}
if ($subcategory_filter) {
    $where_clause .= " AND s.slug = ?";
    $params[] = $subcategory_filter;
}
if ($search_query) {
    $where_clause .= " AND (p.title LIKE ? OR p.description LIKE ?)";
    $params[] = "%$search_query%";
    $params[] = "%$search_query%";
}

// Count total for pagination
$count_sql = "
    SELECT COUNT(p.id) 
    FROM portfolio_items p
    LEFT JOIN portfolio_categories c ON p.category_id = c.id
    LEFT JOIN portfolio_subcategories s ON p.subcategory_id = s.id
    $where_clause
";
$total_stmt = $pdo->prepare($count_sql);
$total_stmt->execute($params);
$total_items = $total_stmt->fetchColumn();
$total_pages = ceil($total_items / $per_page);

// Fetch items
$sql = "
    SELECT p.*, c.name as category_name, c.slug as category_slug, s.name as subcategory_name, s.slug as subcategory_slug
    FROM portfolio_items p
    LEFT JOIN portfolio_categories c ON p.category_id = c.id
    LEFT JOIN portfolio_subcategories s ON p.subcategory_id = s.id
    $where_clause
    ORDER BY p.created_at DESC
    LIMIT $per_page OFFSET $offset
";
$item_stmt = $pdo->prepare($sql);
$item_stmt->execute($params);
$portfolio_items = $item_stmt->fetchAll();
?>
<?php
$pageTitle = "Our Portfolio | MK Construction & Builder";
$pageDesc = "Explore our latest completed construction, architecture, and interior design projects in Krishnagiri. MK Construction & Builder showcase.";
$pageKeywords = "construction projects krishnagiri, mk construction portfolio, interior design gallery, building projects";
include 'includes/header.php';
?>


    <!-- Page Header (Mirrors the Dark Blue Background from mockup) -->
    <div class="page-header" style="background-image: linear-gradient(rgba(17, 24, 39, 0.8), rgba(17, 24, 39, 0.9)), url('assets/img/hero-construction.jpg'); text-align: left; padding: 120px 0;">
        <div class="container">
            <h1 class="page-title" style="font-size: 3rem; margin-bottom: 10px;">Portfolio</h1>
            <div class="breadcrumb" style="justify-content: flex-start; gap: 8px;">
                <a href="index.php" style="color: rgba(255,255,255,0.8);">Home</a>
                <i class="fa-solid fa-chevron-right" style="font-size: 0.8rem; color: rgba(255,255,255,0.6);"></i>
                <span style="color: var(--primary-color); font-weight: 500;">Portfolio</span>
            </div>
        </div>
    </div>

    <!-- Portfolio/Blog Layout Section -->
    <section class="section-padding bg-light" style="padding: 80px 0;">
        <div class="container">
            <div class="blog-layout" style="display: grid; grid-template-columns: 1fr 350px; gap: 40px; align-items: start;">
                
                <!-- Left Side: Main Content (List View) -->
                <div class="blog-main-content">
                    <?php if(count($portfolio_items) > 0): ?>
                        <?php foreach($portfolio_items as $item): 
                            $date = new DateTime($item['created_at']);
                            $formatted_date = $date->format('d M, Y');
                        ?>
                            <div class="blog-card portfolio-item" data-category="cat-<?= htmlspecialchars($item['category_slug']) ?>" data-subcategory="<?= !empty($item['subcategory_slug']) ? 'sub-' . htmlspecialchars($item['subcategory_slug']) : '' ?>" style="background: var(--white); border-radius: 12px; overflow: hidden; box-shadow: var(--shadow-sm); margin-bottom: 40px; border: 1px solid rgba(0,0,0,0.05);">
                                <!-- Cover Image -->
                                <div class="blog-image">
                                    <a href="portfolio-details.php?slug=<?= htmlspecialchars($item['slug']) ?>">
                                        <img src="<?= htmlspecialchars($item['image_path']) ?>" alt="<?= htmlspecialchars($item['title']) ?>" style="width: 100%; height: auto; max-height: 450px; object-fit: cover; display: block;">
                                    </a>
                                </div>
                                
                                <!-- Meta & Content -->
                                <div class="blog-content" style="padding: 35px;">
                                    <div class="blog-meta" style="display: flex; gap: 20px; font-size: 0.9rem; color: var(--text-muted); margin-bottom: 15px; font-weight: 500;">
                                        <span><i class="fa-regular fa-user" style="color: var(--primary-color); margin-right: 6px;"></i> By Admin</span>
                                        <span><i class="fa-regular fa-calendar" style="color: var(--primary-color); margin-right: 6px;"></i> <?= $formatted_date ?></span>
                                    </div>
                                    
                                    <h2 class="blog-title" style="font-family: var(--font-serif); font-size: 1.8rem; margin-bottom: 18px; line-height: 1.3;">
                                        <a href="portfolio-details.php?slug=<?= htmlspecialchars($item['slug']) ?>" style="color: var(--dark-nav); text-decoration: none; transition: var(--transition);">
                                            <?= htmlspecialchars($item['title']) ?>
                                        </a>
                                    </h2>
                                    
                                    <p class="blog-excerpt" style="color: var(--text-muted); line-height: 1.7; margin-bottom: 25px; font-size: 1rem;">
                                        <?php
                                            $excerpt = strip_tags($item['description']);
                                            if (empty($excerpt)) {
                                                echo "Discover details about our highly-rated " . htmlspecialchars($item['category_name']) . " project successfully delivered with utmost craftsmanship and standards.";
                                            } else {
                                                echo (strlen($excerpt) > 150) ? substr($excerpt, 0, 150) . '...' : $excerpt;
                                            }
                                        ?>
                                    </p>
                                    
                                    <a href="portfolio-details.php?slug=<?= htmlspecialchars($item['slug']) ?>" class="btn-read-more" style="display: inline-flex; align-items: center; gap: 8px; font-weight: 700; color: var(--dark-nav); text-decoration: none; border: 1px solid #e2e8f0; padding: 10px 24px; border-radius: 6px; font-size: 0.9rem; transition: var(--transition); text-transform: uppercase;">
                                        READ MORE <i class="fa-solid fa-arrow-right" style="color: var(--text-muted); font-size: 0.8rem; transition: var(--transition);"></i>
                                    </a>
                                </div>
                            </div>
                        <?php endforeach; ?>

                        <!-- Pagination -->
                        <?php if($total_pages > 1): ?>
                            <div class="pagination" style="display: flex; justify-content: center; gap: 10px; margin-top: 50px;">
                                <?php if($page > 1): ?>
                                    <a href="?page=<?= $page - 1 ?><?= $category_filter ? '&category=' . $category_filter : '' ?><?= $subcategory_filter ? '&subcategory=' . $subcategory_filter : '' ?><?= $search_query ? '&search=' . urlencode($search_query) : '' ?>" class="page-link" style="width: 45px; height: 45px; display: flex; align-items: center; justify-content: center; border: 1px solid #e2e8f0; border-radius: 50%; color: var(--dark-nav); text-decoration: none; transition: var(--transition);"><i class="fa-solid fa-chevron-left"></i></a>
                                <?php endif; ?>
                                
                                <?php for($i = 1; $i <= $total_pages; $i++): ?>
                                    <a href="?page=<?= $i ?><?= $category_filter ? '&category=' . $category_filter : '' ?><?= $subcategory_filter ? '&subcategory=' . $subcategory_filter : '' ?><?= $search_query ? '&search=' . urlencode($search_query) : '' ?>" class="page-link <?= ($i == $page) ? 'active' : '' ?>" style="width: 45px; height: 45px; display: flex; align-items: center; justify-content: center; border: 1px solid <?= ($i == $page) ? 'var(--primary-color)' : '#e2e8f0' ?>; background-color: <?= ($i == $page) ? 'var(--primary-color)' : 'transparent' ?>; color: <?= ($i == $page) ? 'var(--white)' : 'var(--dark-nav)' ?>; border-radius: 50%; text-decoration: none; transition: var(--transition); font-weight: 600;"><?= $i ?></a>
                                <?php endfor; ?>
                                
                                <?php if($page < $total_pages): ?>
                                    <a href="?page=<?= $page + 1 ?><?= $category_filter ? '&category=' . $category_filter : '' ?><?= $subcategory_filter ? '&subcategory=' . $subcategory_filter : '' ?><?= $search_query ? '&search=' . urlencode($search_query) : '' ?>" class="page-link" style="width: 45px; height: 45px; display: flex; align-items: center; justify-content: center; border: 1px solid #e2e8f0; border-radius: 50%; color: var(--dark-nav); text-decoration: none; transition: var(--transition);"><i class="fa-solid fa-chevron-right"></i></a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                    <?php else: ?>
                        <div class="no-results text-center" style="padding: 100px 20px; background: var(--white); border-radius: 12px; border: 1px dashed #e2e8f0;">
                            <i class="fa-solid fa-folder-open" style="font-size: 4rem; color: #e2e8f0; margin-bottom: 20px;"></i>
                            <h3 style="color: var(--dark-nav);">No Projects Found</h3>
                            <p style="color: var(--text-muted);">Try adjusting your filters or search terms.</p>
                            <a href="portfolio.php" class="btn btn-primary mt-4">View All Projects</a>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Right Side: Sidebar Widgets -->
                <aside class="blog-sidebar">
                    <!-- Search Widget -->
                    <div class="sidebar-widget" style="background: var(--white); padding: 30px; border-radius: 12px; box-shadow: var(--shadow-sm); margin-bottom: 30px; border: 1px solid rgba(0,0,0,0.05);">
                        <h3 class="widget-title" style="font-size: 1.3rem; font-family: var(--font-serif); margin-bottom: 25px; color: var(--dark-nav); border-left: 4px solid var(--primary-color); padding-left: 15px;">Search Projects</h3>
                        <form action="portfolio.php" method="GET" style="position: relative;">
                            <input type="text" name="search" placeholder="Enter keywords..." value="<?= htmlspecialchars($search_query) ?>" style="width: 100%; padding: 14px 20px; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.95rem; transition: var(--transition); outline: none;">
                            <button type="submit" style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); background: var(--primary-color); color: var(--white); border: none; width: 42px; height: 42px; border-radius: 6px; cursor: pointer; transition: var(--transition);"><i class="fa-solid fa-magnifying-glass"></i></button>
                        </form>
                    </div>
                    
                    <!-- Categories Widget -->
                    <div class="sidebar-widget" style="background: var(--white); padding: 30px; border-radius: 12px; box-shadow: var(--shadow-sm); margin-bottom: 30px; border: 1px solid rgba(0,0,0,0.05);">
                        <h3 class="widget-title" style="font-size: 1.3rem; font-family: var(--font-serif); margin-bottom: 25px; color: var(--dark-nav); border-left: 4px solid var(--primary-color); padding-left: 15px;">Project Categories</h3>
                        <div class="category-list" style="display: flex; flex-direction: column; gap: 12px;">
                            <a href="portfolio.php" class="<?= empty($category_filter) ? 'active' : '' ?>" style="display: flex; justify-content: space-between; align-items: center; color: var(--text-muted); text-decoration: none; padding-bottom: 8px; border-bottom: 1px solid #f8fafc; font-weight: 500; transition: var(--transition); <?= empty($category_filter) ? 'color: var(--primary-color); font-weight: 700;' : '' ?>">
                                <span>All Projects</span>
                                <span class="count" style="background: #f1f5f9; padding: 2px 10px; border-radius: 20px; font-size: 0.8rem;"><?= array_sum(array_column($categories_with_count, 'project_count')) ?></span>
                            </a>
                            <?php foreach($categories_with_count as $cat): ?>
                                <a href="?category=<?= htmlspecialchars($cat['slug']) ?>" class="<?= ($category_filter == $cat['slug']) ? 'active' : '' ?>" style="display: flex; justify-content: space-between; align-items: center; color: var(--text-muted); text-decoration: none; padding-bottom: 8px; border-bottom: 1px solid #f8fafc; font-weight: 500; transition: var(--transition); <?= ($category_filter == $cat['slug']) ? 'color: var(--primary-color); font-weight: 700;' : '' ?>">
                                    <span><?= htmlspecialchars($cat['name']) ?></span>
                                    <span class="count" style="background: #f1f5f9; padding: 2px 10px; border-radius: 20px; font-size: 0.8rem;"><?= $cat['project_count'] ?></span>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <!-- Recent Projects Widget -->
                    <div class="sidebar-widget" style="background: var(--white); padding: 30px; border-radius: 12px; box-shadow: var(--shadow-sm); margin-bottom: 30px; border: 1px solid rgba(0,0,0,0.05);">
                        <h3 class="widget-title" style="font-size: 1.3rem; font-family: var(--font-serif); margin-bottom: 25px; color: var(--dark-nav); border-left: 4px solid var(--primary-color); padding-left: 15px;">Recent Projects</h3>
                        <div class="recent-posts" style="display: flex; flex-direction: column; gap: 20px;">
                            <?php foreach($recent_posts as $post): 
                                $date = new DateTime($post['created_at']);
                            ?>
                                <div class="recent-post-item" style="display: flex; gap: 15px; align-items: center;">
                                    <div class="recent-post-thumb" style="width: 80px; height: 80px; flex-shrink: 0; border-radius: 8px; overflow: hidden;">
                                        <a href="portfolio-details.php?slug=<?= htmlspecialchars($post['slug']) ?>"><img src="<?= htmlspecialchars($post['image_path']) ?>" alt="<?= htmlspecialchars($post['title']) ?>" style="width: 100%; height: 100%; object-fit: cover;"></a>
                                    </div>
                                    <div class="recent-post-content">
                                        <h4 style="font-size: 0.95rem; line-height: 1.4; margin-bottom: 5px; font-family: var(--font-serif);"><a href="portfolio-details.php?slug=<?= htmlspecialchars($post['slug']) ?>" style="color: var(--dark-nav); text-decoration: none; transition: var(--transition);" class="hover-primary"><?= htmlspecialchars($post['title']) ?></a></h4>
                                        <span style="font-size: 0.8rem; color: var(--text-muted);"><i class="fa-regular fa-calendar-days" style="margin-right: 5px;"></i> <?= $date->format('M d, Y') ?></span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </aside>
            </div>
        </div>
    </section>

    <!-- Custom CSS for Blog Card Interactive Elements -->
    <style>
        .btn-read-more:hover {
            background-color: var(--primary-color);
            color: var(--white) !important;
            border-color: var(--primary-color) !important;
        }
        .btn-read-more:hover i {
            color: var(--white) !important;
            transform: translateX(5px);
        }
        .blog-title a:hover {
            color: var(--primary-color) !important;
        }
        .category-list a:hover {
            color: var(--primary-color) !important;
        }
        .category-list a:hover .count {
            background-color: var(--primary-color);
            color: var(--white);
        }
        .tags-list a:hover {
            background-color: var(--primary-color);
            color: var(--white) !important;
            border-color: var(--primary-color);
        }
        .recent-post-content .hover-primary:hover {
            color: var(--primary-color) !important;
        }
        
        /* Responsive Blog Layout */
        @media (max-width: 991px) {
            .blog-layout {
                grid-template-columns: 1fr !important;
            }
        }
    </style>
<?php include 'includes/footer.php'; ?>
