<?php
include 'includes/db.php';
include 'includes/header.php';

// Static services definitions with rich imagery and descriptions
$static_services = [
    [
        'title' => 'Retail Outlet (Petrol Pump)',
        'category' => 'Petroleum',
        'image' => 'our servies image/Our Services/Petro-Pump-Retail-Outlet.jpeg',
        'desc' => 'Turnkey construction solutions for Petrol Pumps and Retail Outlets conforming to all technical norms and guidelines of IOCL, BPCL, and HPCL. End-to-end execution from canopy structural steel to underground tank pads.',
        'highlights' => ['PESO Compliant Fuel Systems', 'Heavy Duty Concrete Driveways', 'Canopy Structural Steel Erection']
    ],
    [
        'title' => 'Civil Engineering & Construction Services',
        'category' => 'Civil',
        'image' => 'our servies image/Our Services/Construction_of_Building.jpeg',
        'desc' => 'Comprehensive civil engineering solutions for residential, commercial, and government infrastructure projects. High-durability concrete framing, foundation casting, and seismic zone compliant designs.',
        'highlights' => ['CPWD & IS Code Standards', 'BIM 3D Architectural Planning', 'Raft & Deep Pile Foundations']
    ],
    [
        'title' => 'Fabrication Works',
        'category' => 'Fabrication',
        'image' => 'our servies image/Our Services/fabrication_wor.jpeg',
        'desc' => 'High-grade structural steel and metal fabrication services for industrial plants, warehouses, commercial complexes, and retail canopies using precision CNC cutting and welding equipment.',
        'highlights' => ['IS 2062 Structural Steel', 'Corrosion-Resistant Epoxy Coating', 'Heavy Load Bearing Trusses']
    ],
    [
        'title' => 'Furniture Design & Interior Works',
        'category' => 'Interior',
        'image' => 'our servies image/Our Services/interior_work.jpeg',
        'desc' => 'Bespoke furniture craftsmanship and modern interior fit-outs tailored for corporate offices, commercial showrooms, and luxury residences. Elegant space planning with false ceilings, lighting, and modular furniture.',
        'highlights' => ['Ergonomic Workstation Suites', 'Acoustic Ceilings & Lighting', 'Custom Handcrafted Woodwork']
    ],
    [
        'title' => 'Terminal & Depot Engineering Works',
        'category' => 'Depots',
        'image' => 'our servies image/Services php/d3/Terminal & Depot Engineering Works.jpeg',
        'desc' => 'Full-scale EPC engineering for oil and gas fuel terminals, logistics yards, and heavy vehicle depots. Complete site grading, storage tank pads, manifold piping, and automated safety systems.',
        'highlights' => ['Bulk Fuel Tank Farms', 'Automated Safety & Foam Deluge', 'Heavy Axle Circulation Pavements']
    ],
    [
        'title' => 'Aluminium Fabrication & Installation Works',
        'category' => 'Aluminium',
        'image' => 'our servies image/Our Services/Aluminium_work.jpeg',
        'desc' => 'State-of-the-art architectural aluminium fabrication including structural glass facades, slim-line acoustic sliding windows, aluminium composite panels (ACP), and office partition systems.',
        'highlights' => ['Structural Curtain Glazing', 'Anodised & PVDF Finish', 'Air & Water Tight Sealing']
    ],
    [
        'title' => 'PVC Fabrication & Installation Works',
        'category' => 'PVC',
        'image' => 'our servies image/Services php/d6 PVC Fabrication & Installation Works/PVC Fabrication & Installation Works.jpg',
        'desc' => 'Lightweight, waterproof, and termite-proof PVC solutions for ceilings, doors, partitions, and decorative wall paneling. Cost-effective, durable, and low-maintenance installations.',
        'highlights' => ['100% Waterproof & Termite-Proof', 'Modern Wood-Grain Textures', 'Quick Clean-Fit Installation']
    ],
    [
        'title' => 'Development Of Road',
        'category' => 'Roads',
        'image' => 'our servies image/Our Services/Development_road.jpeg',
        'desc' => 'Road infrastructure development including sub-grade soil stabilization, granular sub-base (GSB), dense bituminous macadam (DBM), and rigid concrete paving with precision drainage.',
        'highlights' => ['Rigid & Flexible Pavements', 'Digital Ride Quality Testing', 'Thermoplastic Reflective Markings']
    ]
];

// Fetch any published dynamic services from the DB
$dynamic_services = [];
try {
    $dyn_res = $conn->query("SELECT * FROM services WHERE deleted_at IS NULL AND (status = 'published' OR status IS NULL) ORDER BY created_at DESC");
    if ($dyn_res && $dyn_res->num_rows > 0) {
        while ($row = $dyn_res->fetch_assoc()) {
            $excerpt = '';
            $desc = $row['description'] ?? '';
            $decoded = json_decode($desc, true);
            if ($decoded && isset($decoded['blocks'])) {
                foreach ($decoded['blocks'] as $block) {
                    if (isset($block['data']['text']) && strlen(trim(strip_tags($block['data']['text']))) > 0) {
                        $excerpt = strip_tags($block['data']['text']);
                        break;
                    }
                }
            } else {
                $excerpt = strip_tags($desc);
            }
            $dynamic_services[] = [
                'title' => $row['title'],
                'category' => 'Engineering',
                'image' => !empty($row['image_url']) ? $row['image_url'] : 'our servies image/Our Services/Construction_of_Building.jpeg',
                'desc' => $excerpt,
                'highlights' => ['Professional Execution', 'Quality Assured Delivery', 'Engineered by Balimeen']
            ];
        }
    }
} catch (Exception $e) {}

// Merge lists
$all_services = array_merge($static_services, $dynamic_services);

// Active category filter
$category = isset($_GET['category']) ? trim($_GET['category']) : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
?>

<!-- Link Dedicated Design System Stylesheet -->
<link rel="stylesheet" href="/bm/assets/css/blog.css">

<div class="bm-blog-wrapper">

    <!-- 1. BREADCRUMBS -->
    <nav class="bm-breadcrumb-nav" aria-label="breadcrumb">
        <div class="container">
            <ul class="bm-breadcrumb-list">
                <li><a href="/bm/"><i class="fas fa-home me-1"></i> Home</a></li>
                <li class="bm-breadcrumb-sep"><i class="fas fa-chevron-right"></i></li>
                <li><span class="bm-breadcrumb-current">Our Services</span></li>
                <?php if ($category && strtolower($category) !== 'all'): ?>
                    <li class="bm-breadcrumb-sep"><i class="fas fa-chevron-right"></i></li>
                    <li><span class="bm-breadcrumb-current"><?php echo htmlspecialchars($category); ?></span></li>
                <?php endif; ?>
            </ul>
        </div>
    </nav>

    <!-- 2. HERO TOP BANNER (ROYAL BLUE LAKSHYA STYLE) -->
    <div class="bannerTopInnerPage bgPrimary">
        <div class="containerFull">
            <div class="banner-row">
                <div class="leftInnerPagePr">
                    <span class="badge-tag"><i class="fas fa-hard-hat"></i> Balimeen Expertise</span>
                    <h1 class="heading bannerHeading">Our Services</h1>
                    <p>End-to-end turnkey solutions across Civil Engineering, Petroleum Outlets, Structural Fabrication, Aluminium Architecture &amp; Interior Design.</p>
                </div>
                <div class="rightInnerPagePr">
                    <div class="blogMobileImg">
                        <img src="/bm/our servies image/Our Services/Construction_of_Building.jpeg" alt="Balimeen Services Banner" loading="eager">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 3. FILTER, CATEGORY TABS & SEARCH SECTION -->
    <section class="blog-filter-section">
        <div class="filter-header-row">
            <h2 class="filter-title">All Services &amp; Solutions</h2>
            
            <div class="filter-controls">
                <!-- Search Box with Live / Form Support -->
                <div class="blog-search-box">
                    <i class="fas fa-search blog-search-icon"></i>
                    <input type="text" 
                           id="serviceSearchInput"
                           class="blog-search-input" 
                           placeholder="Search services..." 
                           value="<?php echo htmlspecialchars($search); ?>">
                </div>

                <!-- Category Pills (Desktop) -->
                <div class="category-filter-nav">
                    <button type="button" onclick="filterCategory('all', this)" class="category-btn active">All</button>
                    <button type="button" onclick="filterCategory('petroleum', this)" class="category-btn">Petroleum Outlets</button>
                    <button type="button" onclick="filterCategory('civil', this)" class="category-btn">Civil &amp; Building</button>
                    <button type="button" onclick="filterCategory('fabrication', this)" class="category-btn">Fabrication &amp; Steel</button>
                    <button type="button" onclick="filterCategory('aluminium', this)" class="category-btn">Aluminium Work</button>
                    <button type="button" onclick="filterCategory('interior', this)" class="category-btn">Interior &amp; Furniture</button>
                    <button type="button" onclick="filterCategory('depots', this)" class="category-btn">Depots &amp; Terminals</button>
                    <button type="button" onclick="filterCategory('roads', this)" class="category-btn">Roads</button>
                </div>
            </div>
        </div>
    </section>

    <!-- 4. SERVICES GRID (2-COLUMN CARDS LIKE LAKSHYA COMMERCE) -->
    <div class="blog-grid-container">
        <div class="blog-grid-2col" id="serviceGrid">
            <?php foreach ($all_services as $s): 
                $detailUrl = '/bm/service-detail/' . urlencode($s['title']);
                $imgSrc = $s['image'];
                if (!empty($imgSrc) && !preg_match('#^https?://#', $imgSrc) && strpos($imgSrc, '/') !== 0) {
                    $imgSrc = '/bm/' . str_replace('\\', '/', $imgSrc);
                }
            ?>
            <article class="careerBox trainingProgramBox blogBox service-item" 
                     data-title="<?php echo htmlspecialchars(strtolower($s['title'])); ?>" 
                     data-cat="<?php echo htmlspecialchars(strtolower($s['category'])); ?>"
                     data-desc="<?php echo htmlspecialchars(strtolower($s['desc'])); ?>">
                <div class="head">
                    <span class="card-category-tag"><?php echo htmlspecialchars($s['category']); ?></span>
                    <a href="<?php echo $detailUrl; ?>">
                        <img src="<?php echo htmlspecialchars($imgSrc); ?>" 
                             alt="<?php echo htmlspecialchars($s['title']); ?>" 
                             loading="lazy" 
                             onerror="this.src='/bm/our servies image/Our Services/Construction_of_Building.jpeg'">
                    </a>
                </div>
                <div class="body">
                    <a class="title" href="<?php echo $detailUrl; ?>">
                        <?php echo htmlspecialchars($s['title']); ?>
                    </a>
                    
                    <p class="blog-card-excerpt" style="margin-bottom: 16px;">
                        <?php echo htmlspecialchars($s['desc']); ?>
                    </p>

                    <?php if (!empty($s['highlights'])): ?>
                    <ul style="list-style: none; padding: 0; margin: 0 0 20px 0; font-size: 13.5px; color: #475569;">
                        <?php foreach ($s['highlights'] as $hl): ?>
                        <li style="margin-bottom: 6px; display: flex; align-items: center; gap: 8px;">
                            <i class="fas fa-check-circle" style="color: var(--bm-blue-primary); font-size: 13px;"></i>
                            <span><?php echo htmlspecialchars($hl); ?></span>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                    <?php endif; ?>

                    <div class="blog-card-footer">
                        <a href="<?php echo $detailUrl; ?>" class="btn-read-more">
                            Explore Service Details <i class="fas fa-arrow-right"></i>
                        </a>
                    </div>
                </div>
            </article>
            <?php endforeach; ?>
        </div>
    </div>

</div>

<script>
let currentFilter = 'all';

function filterCategory(cat, btn) {
    currentFilter = cat.toLowerCase();
    
    // Update active button
    document.querySelectorAll('.category-btn').forEach(b => b.classList.remove('active'));
    if (btn) btn.classList.add('active');

    applyFilters();
}

function applyFilters() {
    const query = (document.getElementById('serviceSearchInput').value || '').toLowerCase().trim();
    const serviceItems = document.querySelectorAll('.service-item');

    serviceItems.forEach(item => {
        const title = item.getAttribute('data-title') || '';
        const cat = item.getAttribute('data-cat') || '';
        const desc = item.getAttribute('data-desc') || '';

        const matchesCat = (currentFilter === 'all') || cat.includes(currentFilter) || title.includes(currentFilter);
        const matchesSearch = !query || title.includes(query) || desc.includes(query) || cat.includes(query);

        if (matchesCat && matchesSearch) {
            item.style.display = 'flex';
        } else {
            item.style.display = 'none';
        }
    });
}

document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('serviceSearchInput');
    if (searchInput) {
        searchInput.addEventListener('input', applyFilters);
    }
});
</script>

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