<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/config.php';

// Pagination settings
$services_per_page = 12;
$current_page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

// Check if category filter is applied
$category_slug = isset($_GET['category']) ? trim($_GET['category']) : null;
$selected_category = null;
$category_id = null;

if ($category_slug) {
    $conn = get_db_connection();
    $cat_stmt = $conn->prepare("SELECT * FROM service_categories WHERE slug = ? LIMIT 1");
    $cat_stmt->bind_param("s", $category_slug);
    $cat_stmt->execute();
    $cat_result = $cat_stmt->get_result();
    if ($cat_result && $cat_row = $cat_result->fetch_assoc()) {
        $selected_category = $cat_row;
        $category_id = $cat_row['id'];
    }
    $cat_stmt->close();
}

$all_services = get_services($category_id);
$total_services = count($all_services);
$total_pages = ceil($total_services / $services_per_page);

if ($current_page > $total_pages && $total_pages > 0) {
    $current_page = $total_pages;
}

$offset = ($current_page - 1) * $services_per_page;
$services = array_slice($all_services, $offset, $services_per_page);

include BASE_PATH . '/include/header.php';

function get_service_image($service)
{
    if (!empty($service['image']))
        return $service['image'];
    $slug = $service['slug'] ?? '';
    $image_map = [
        'chimney-animal-removal' => '/wp-content/uploads/2022/08/chimney-animal-removal.jpg',
        'chimney-bricks-repair' => '/wp-content/uploads/2022/08/chimney-bricks-repair.jpg',
        'chimney-cap-installation' => '/wp-content/uploads/2022/08/chimney-cap-installation.jpg',
        'chimney-cap-repair' => '/wp-content/uploads/2022/08/chimney-cap-repair.jpg',
        'chimney-chase-covering' => '/wp-content/uploads/2022/08/chimney-chase-covering.jpg',
        'chimney-deep-cleaning-pcr' => '/wp-content/uploads/2022/08/chimney-deep-cleaning-pcr.jpg',
        'chimney-exterior-wood-replacement' => '/wp-content/uploads/2023/12/chimney-exterior-wood-replacement.jpg',
        'chimney-fan-installation' => '/wp-content/uploads/2022/08/chimney-fan-installation.jpg',
        'chimney-flashing' => '/wp-content/uploads/2022/08/chimney-flashing.jpg',
        'chimney-framing-rebuild' => '/wp-content/uploads/2022/08/chimney-framing-rebuild.jpg',
        'chimney-nest-removal' => '/wp-content/uploads/2022/08/chimney-nest-removal.jpg',
        'chimney-rebuild' => '/wp-content/uploads/2022/08/chimney-rebuild.jpg',
        'chimney-restoration' => '/wp-content/uploads/2022/08/chimney-restoration.jpg',
        'chimney-siding-replace' => '/wp-content/uploads/2022/08/chimney-siding-replace.jpg',
        'chimney-sweep' => '/wp-content/uploads/2022/08/chimney-sweep.jpg',
        'smoke-chamber-rebuild' => '/wp-content/uploads/2022/08/smoke-chamber-rebuild.jpg',
    ];
    return isset($image_map[$slug]) ? $image_map[$slug] : '/wp-content/uploads/2022/08/chimney-sweep.jpg';
}

function get_service_excerpt($service)
{
    if (!empty($service['description']))
        return substr(strip_tags($service['description']), 0, 100);
    if (!empty($service['content']))
        return substr(strip_tags($service['content']), 0, 100);
    return 'Professional chimney service';
}
?>

<main id="content">
    <!-- Hero Section -->
    <section class="subpage-hero">
        <div class="container">
            <h1><?php echo $selected_category ? '<span>' . htmlspecialchars($selected_category['name']) . '</span> Services' : 'Our <span>Services</span>'; ?>
            </h1>
            <p>Professional chimney & fireplace services to keep your home safe, warm, and efficient all year round.</p>
            <div class="mt-4">
                <a href="tel:<?php echo get_phone_number_tel(); ?>"
                    class="btn-pro"><?php echo get_phone_number(); ?></a>
            </div>
        </div>
    </section>

    <!-- Breadcrumbs -->
    <div class="breadcrumb-container">
        <div class="container">
            <a href="/"><i class="fas fa-home"></i> Home</a> / <span>Our Services</span>
        </div>
    </div>

    <!-- Services Grid Section -->
    <section class="section-padding bg-light">
        <div class="container">
            <div class="row g-4">
                <?php if (empty($services)): ?>
                    <div class="col-12 text-center py-5">
                        <div class="pro-card">
                            <h3>No Services Available</h3>
                            <p class="text-muted">Please check back later or contact us for more information.</p>
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach ($services as $service):
                        $service_url = '/service.php?slug=' . urlencode($service['slug']);
                        $image_url = get_service_image($service);
                        $excerpt = get_service_excerpt($service);
                        ?>
                        <div class="col-lg-3 col-md-6">
                            <div class="pro-card p-0 h-100 overflow-hidden">
                                <a href="<?php echo htmlspecialchars($service_url); ?>" class="d-block overflow-hidden"
                                    style="height: 200px;">
                                    <img src="<?php echo htmlspecialchars($image_url); ?>"
                                        alt="<?php echo htmlspecialchars($service['name']); ?>"
                                        class="w-100 h-100 object-fit-cover transition-transform"
                                        style="transition: transform 0.5s ease;">
                                </a>
                                <div class="p-4 d-flex flex-column h-100">
                                    <h3 class="fs-5 mb-3">
                                        <a href="<?php echo htmlspecialchars($service_url); ?>"
                                            class="text-dark text-decoration-none hover-primary transition-all">
                                            <?php echo htmlspecialchars($service['name']); ?>
                                        </a>
                                    </h3>
                                    <p class="text-muted small mb-4 flex-grow-1"><?php echo htmlspecialchars($excerpt); ?>...
                                    </p>
                                    <a href="<?php echo htmlspecialchars($service_url); ?>"
                                        class="text-primary fw-bold text-decoration-none small">READ MORE <i
                                            class="fas fa-arrow-right ms-1"></i></a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="mt-5 d-flex justify-content-center align-items-center gap-2">
                    <?php if ($current_page > 1): ?>
                        <a href="?<?php echo $category_slug ? 'category=' . urlencode($category_slug) . '&' : ''; ?>page=<?php echo $current_page - 1; ?>"
                            class="btn btn-white shadow-sm border px-4 py-2 rounded-3">
                            <i class="fas fa-chevron-left me-2"></i> Previous
                        </a>
                    <?php endif; ?>

                    <div class="d-flex gap-1">
                        <?php
                        for ($i = 1; $i <= $total_pages; $i++) {
                            $active = ($i == $current_page) ? 'bg-primary text-white border-primary' : 'bg-white text-dark border';
                            echo '<a href="?' . ($category_slug ? 'category=' . urlencode($category_slug) . '&' : '') . 'page=' . $i . '" class="btn ' . $active . ' shadow-sm px-3 py-2 rounded-3 fw-bold">' . $i . '</a>';
                        }
                        ?>
                    </div>

                    <?php if ($current_page < $total_pages): ?>
                        <a href="?<?php echo $category_slug ? 'category=' . urlencode($category_slug) . '&' : ''; ?>page=<?php echo $current_page + 1; ?>"
                            class="btn btn-white shadow-sm border px-4 py-2 rounded-3">
                            Next <i class="fas fa-chevron-right ms-2"></i>
                        </a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </section>
</main>

<style>
    .pro-card:hover img {
        transform: scale(1.1);
    }

    .hover-primary:hover {
        color: var(--primary-color) !important;
    }
</style>

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