<?php
/**
 * OPPULENT CHEMICALLS EXCELLENCE INNOVATION
 * File: blogs.php
 * Premium Dynamic Blog Listing
 */

$page_title = 'Blogs & Insights | OPPULENT CHEMICALLS EXCELLENCE INNOVATION';

require_once __DIR__ . '/header.php';

/*
|--------------------------------------------------------------------------
| Database Connection
|--------------------------------------------------------------------------
| Supports common connection variables from admin/includes/db.php
| and config.php if already loaded by header.php.
*/

if (!isset($pdo) && !isset($conn) && !isset($con) && !isset($mysqli)) {
    $dbFile = __DIR__ . '/admin/includes/db.php';

    if (is_file($dbFile)) {
        require_once $dbFile;
    }
}

/*
|--------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------
*/

if (!function_exists('opp_blog_escape')) {
    function opp_blog_escape($value): string
    {
        return htmlspecialchars((string)($value ?? ''), ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('opp_blog_table_exists')) {
    function opp_blog_table_exists($db, string $table): bool
    {
        try {
            if ($db instanceof PDO) {
                $stmt = $db->prepare(
                    "SELECT COUNT(*) FROM information_schema.tables
                     WHERE table_schema = DATABASE() AND table_name = ?"
                );
                $stmt->execute([$table]);
                return (int)$stmt->fetchColumn() > 0;
            }

            if ($db instanceof mysqli) {
                $stmt = $db->prepare(
                    "SELECT COUNT(*) AS total
                     FROM information_schema.tables
                     WHERE table_schema = DATABASE() AND table_name = ?"
                );

                if (!$stmt) {
                    return false;
                }

                $stmt->bind_param('s', $table);
                $stmt->execute();
                $result = $stmt->get_result();
                $row = $result ? $result->fetch_assoc() : null;
                $stmt->close();

                return (int)($row['total'] ?? 0) > 0;
            }
        } catch (Throwable $e) {
            return false;
        }

        return false;
    }
}

if (!function_exists('opp_blog_columns')) {
    function opp_blog_columns($db, string $table): array
    {
        $columns = [];

        try {
            if ($db instanceof PDO) {
                $stmt = $db->query("SHOW COLUMNS FROM `$table`");

                foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                    $columns[] = $row['Field'];
                }
            } elseif ($db instanceof mysqli) {
                $result = $db->query("SHOW COLUMNS FROM `$table`");

                if ($result) {
                    while ($row = $result->fetch_assoc()) {
                        $columns[] = $row['Field'];
                    }
                    $result->free();
                }
            }
        } catch (Throwable $e) {
            return [];
        }

        return $columns;
    }
}

if (!function_exists('opp_blog_pick')) {
    function opp_blog_pick(array $columns, array $candidates): ?string
    {
        foreach ($candidates as $candidate) {
            if (in_array($candidate, $columns, true)) {
                return $candidate;
            }
        }

        return null;
    }
}

if (!function_exists('opp_blog_query')) {
    function opp_blog_query($db, string $sql, array $params = []): array
    {
        try {
            if ($db instanceof PDO) {
                $stmt = $db->prepare($sql);
                $stmt->execute($params);
                return $stmt->fetchAll(PDO::FETCH_ASSOC);
            }

            if ($db instanceof mysqli) {
                $stmt = $db->prepare($sql);

                if (!$stmt) {
                    return [];
                }

                if ($params) {
                    $types = '';
                    $values = [];

                    foreach ($params as $value) {
                        if (is_int($value)) {
                            $types .= 'i';
                        } elseif (is_float($value)) {
                            $types .= 'd';
                        } else {
                            $types .= 's';
                        }

                        $values[] = $value;
                    }

                    $stmt->bind_param($types, ...$values);
                }

                if (!$stmt->execute()) {
                    $stmt->close();
                    return [];
                }

                $result = $stmt->get_result();
                $rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
                $stmt->close();

                return $rows;
            }
        } catch (Throwable $e) {
            error_log('Oppulent blogs query error: ' . $e->getMessage());
        }

        return [];
    }
}

if (!function_exists('opp_blog_image')) {
    function opp_blog_image(?string $path): string
    {
        $path = trim((string)$path);

        if ($path === '') {
            return '';
        }

        // Permit remote images and local relative paths.
        if (preg_match('~^https?://~i', $path)) {
            return $path;
        }

        if (strpos($path, '//') === 0) {
            return '';
        }

        if (strpos($path, '/') === 0) {
            return $path;
        }

        return $path;
    }
}

if (!function_exists('opp_blog_excerpt')) {
    function opp_blog_excerpt(?string $text, int $length = 145): string
    {
        $text = trim(strip_tags((string)$text));
        $text = preg_replace('/\s+/u', ' ', $text) ?? $text;

        if (function_exists('mb_strlen') && function_exists('mb_substr')) {
            if (mb_strlen($text, 'UTF-8') > $length) {
                return mb_substr($text, 0, $length, 'UTF-8') . '...';
            }
        } elseif (strlen($text) > $length) {
            return substr($text, 0, $length) . '...';
        }

        return $text;
    }
}

/*
|--------------------------------------------------------------------------
| Resolve Database Connection
|--------------------------------------------------------------------------
*/

$blogDb = null;

foreach (['pdo', 'conn', 'con', 'mysqli', 'db'] as $connectionName) {
    if (
        isset($GLOBALS[$connectionName]) &&
        ($GLOBALS[$connectionName] instanceof PDO ||
         $GLOBALS[$connectionName] instanceof mysqli)
    ) {
        $blogDb = $GLOBALS[$connectionName];
        break;
    }
}

$blogPosts = [];
$blogCategories = [];
$featuredBlog = null;
$blogError = false;

$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 9;
$search = trim((string)($_GET['q'] ?? ''));
$selectedCategory = trim((string)($_GET['category'] ?? ''));

/*
|--------------------------------------------------------------------------
| Load Categories and Blog Posts
|--------------------------------------------------------------------------
*/

if ($blogDb && opp_blog_table_exists($blogDb, 'blog_posts')) {
    $postColumns = opp_blog_columns($blogDb, 'blog_posts');

    $idColumn = opp_blog_pick($postColumns, ['id', 'post_id']);
    $titleColumn = opp_blog_pick($postColumns, ['title', 'name', 'post_title']);
    $slugColumn = opp_blog_pick($postColumns, ['slug', 'post_slug']);
    $excerptColumn = opp_blog_pick($postColumns, ['excerpt', 'summary', 'short_description', 'description', 'content', 'body']);
    $contentColumn = opp_blog_pick($postColumns, ['content', 'body', 'post_content', 'description']);
    $imageColumn = opp_blog_pick($postColumns, ['featured_image', 'image', 'thumbnail', 'cover_image', 'image_url', 'banner_image']);
    $dateColumn = opp_blog_pick($postColumns, ['published_at', 'publish_date', 'published_date', 'created_at', 'date']);
    $statusColumn = opp_blog_pick($postColumns, ['status', 'post_status']);
    $categoryIdColumn = opp_blog_pick($postColumns, ['category_id', 'blog_category_id']);
    $authorColumn = opp_blog_pick($postColumns, ['author_name', 'author', 'created_by_name']);
    $featuredColumn = opp_blog_pick($postColumns, ['is_featured', 'featured']);
    $viewsColumn = opp_blog_pick($postColumns, ['views', 'view_count', 'hits']);

    if ($idColumn && $titleColumn) {
        $categoryJoin = '';
        $categorySelect = "'' AS category_name";
        $categorySlugSelect = "'' AS category_slug";

        $hasCategories = opp_blog_table_exists($blogDb, 'blog_categories');
        $categoryColumns = $hasCategories
            ? opp_blog_columns($blogDb, 'blog_categories')
            : [];

        $categoryTableId = opp_blog_pick($categoryColumns, ['id', 'category_id']);
        $categoryNameColumn = opp_blog_pick($categoryColumns, ['name', 'title', 'category_name']);
        $categorySlugColumn = opp_blog_pick($categoryColumns, ['slug', 'category_slug']);

        if (
            $hasCategories &&
            $categoryIdColumn &&
            $categoryTableId &&
            $categoryNameColumn
        ) {
            $categoryJoin = " LEFT JOIN blog_categories bc
                              ON bp.`$categoryIdColumn` = bc.`$categoryTableId` ";

            $categorySelect = "bc.`$categoryNameColumn` AS category_name";

            if ($categorySlugColumn) {
                $categorySlugSelect = "bc.`$categorySlugColumn` AS category_slug";
            }
        }

        if (
            $hasCategories &&
            $categoryTableId &&
            $categoryNameColumn
        ) {
            $categorySql = "SELECT
                                bc.`$categoryTableId` AS id,
                                bc.`$categoryNameColumn` AS name" .
                                ($categorySlugColumn
                                    ? ", bc.`$categorySlugColumn` AS slug"
                                    : ", '' AS slug") .
                           " FROM blog_categories bc ";

            if (in_array('status', $categoryColumns, true)) {
                $categorySql .= " WHERE bc.status = 'active'
                                  OR bc.status = 'published'
                                  OR bc.status = '1' ";
            }

            $categorySql .= " ORDER BY bc.`$categoryNameColumn` ASC";

            $blogCategories = opp_blog_query($blogDb, $categorySql);
        }

        $selectParts = [
            "bp.`$idColumn` AS id",
            "bp.`$titleColumn` AS title",
            $slugColumn ? "bp.`$slugColumn` AS slug" : "'' AS slug",
            $excerptColumn ? "bp.`$excerptColumn` AS excerpt" : "'' AS excerpt",
            $contentColumn ? "bp.`$contentColumn` AS content" : "'' AS content",
            $imageColumn ? "bp.`$imageColumn` AS image" : "'' AS image",
            $dateColumn ? "bp.`$dateColumn` AS published_at" : "NULL AS published_at",
            $authorColumn ? "bp.`$authorColumn` AS author_name" : "'' AS author_name",
            $viewsColumn ? "bp.`$viewsColumn` AS views" : "0 AS views",
            $featuredColumn ? "bp.`$featuredColumn` AS is_featured" : "0 AS is_featured",
            $categorySelect,
            $categorySlugSelect
        ];

        $where = [];
        $params = [];

        if ($statusColumn) {
            $where[] = "(bp.`$statusColumn` = 'published'
                         OR bp.`$statusColumn` = 'active'
                         OR bp.`$statusColumn` = '1')";
        }

        $searchableColumns = array_filter([
            $titleColumn,
            $excerptColumn,
            $contentColumn
        ]);

        if ($search !== '' && $searchableColumns) {
            $searchParts = [];

            foreach (array_unique($searchableColumns) as $column) {
                $searchParts[] = "bp.`$column` LIKE ?";
                $params[] = '%' . $search . '%';
            }

            $where[] = '(' . implode(' OR ', $searchParts) . ')';
        }

        if ($selectedCategory !== '' && $categoryJoin !== '') {
            $categoryIdentifier = ctype_digit($selectedCategory)
                ? $categoryTableId
                : $categorySlugColumn;

            if ($categoryIdentifier) {
                $where[] = "bc.`$categoryIdentifier` = ?";
                $params[] = ctype_digit($selectedCategory)
                    ? (int)$selectedCategory
                    : $selectedCategory;
            }
        }

        $whereSql = $where ? ' WHERE ' . implode(' AND ', $where) : '';

        $countSql = "SELECT COUNT(*)
                     FROM blog_posts bp
                     $categoryJoin
                     $whereSql";

        try {
            if ($blogDb instanceof PDO) {
                $countStmt = $blogDb->prepare($countSql);
                $countStmt->execute($params);
                $totalPosts = (int)$countStmt->fetchColumn();
            } else {
                $countStmt = $blogDb->prepare($countSql);
                $types = '';
                $values = [];

                foreach ($params as $value) {
                    $types .= is_int($value) ? 'i' : 's';
                    $values[] = $value;
                }

                if ($values) {
                    $countStmt->bind_param($types, ...$values);
                }

                $countStmt->execute();
                $countResult = $countStmt->get_result();
                $countRow = $countResult ? $countResult->fetch_row() : [0];
                $totalPosts = (int)($countRow[0] ?? 0);
                $countStmt->close();
            }
        } catch (Throwable $e) {
            error_log('Oppulent blog count error: ' . $e->getMessage());
            $totalPosts = 0;
            $blogError = true;
        }

        $totalPages = max(1, (int)ceil(($totalPosts ?? 0) / $perPage));
        $page = min($page, $totalPages);
        $offset = ($page - 1) * $perPage;

        $orderColumn = $dateColumn ?: $idColumn;
        $orderDirection = 'DESC';

        $blogSql = "SELECT " . implode(', ', $selectParts) . "
                    FROM blog_posts bp
                    $categoryJoin
                    $whereSql
                    ORDER BY bp.`$orderColumn` $orderDirection
                    LIMIT $perPage OFFSET $offset";

        $blogPosts = opp_blog_query($blogDb, $blogSql, $params);

        /*
         * Optional media-table fallback for posts whose featured image is empty.
         * Uses only columns that exist in the current database.
         */
        if (
            $blogPosts &&
            opp_blog_table_exists($blogDb, 'blog_post_media')
        ) {
            $mediaColumns = opp_blog_columns($blogDb, 'blog_post_media');
            $mediaPostId = opp_blog_pick($mediaColumns, ['post_id', 'blog_post_id']);
            $mediaPath = opp_blog_pick($mediaColumns, ['file_path', 'image_path', 'media_url', 'path', 'image', 'url']);
            $mediaType = opp_blog_pick($mediaColumns, ['media_type', 'type', 'file_type']);
            $mediaSort = opp_blog_pick($mediaColumns, ['sort_order', 'position', 'id']);

            if ($mediaPostId && $mediaPath) {
                foreach ($blogPosts as &$post) {
                    if (!empty($post['image'])) {
                        continue;
                    }

                    $mediaSql = "SELECT `$mediaPath` AS image
                                 FROM blog_post_media
                                 WHERE `$mediaPostId` = ?";

                    $mediaParams = [(int)$post['id']];

                    if ($mediaType) {
                        $mediaSql .= " AND (`$mediaType` LIKE '%image%'
                                            OR `$mediaType` LIKE '%photo%'
                                            OR `$mediaType` = 'img')";
                    }

                    $mediaSql .= $mediaSort
                        ? " ORDER BY `$mediaSort` ASC LIMIT 1"
                        : " LIMIT 1";

                    $mediaRows = opp_blog_query($blogDb, $mediaSql, $mediaParams);

                    if (!empty($mediaRows[0]['image'])) {
                        $post['image'] = $mediaRows[0]['image'];
                    }
                }

                unset($post);
            }
        }

        if ($featuredColumn) {
            foreach ($blogPosts as $post) {
                if (!empty($post['is_featured'])) {
                    $featuredBlog = $post;
                    break;
                }
            }
        }
    } else {
        $totalPosts = 0;
        $totalPages = 1;
        $blogError = true;
    }
} else {
    $totalPosts = 0;
    $totalPages = 1;
    $blogError = true;
}

/*
|--------------------------------------------------------------------------
| URL Helpers
|--------------------------------------------------------------------------
*/

$currentQuery = [];

if ($search !== '') {
    $currentQuery['q'] = $search;
}

if ($selectedCategory !== '') {
    $currentQuery['category'] = $selectedCategory;
}

$blogUrl = function (array $overrides = []) use ($currentQuery): string {
    $query = array_merge($currentQuery, $overrides);

    foreach ($query as $key => $value) {
        if ($value === '' || $value === null) {
            unset($query[$key]);
        }
    }

    return 'blogs.php' . ($query ? '?' . http_build_query($query) : '');
};

$blogDetailUrl = function (array $post): string {
    /*
     * Change this destination if your project uses a different detail filename.
     */
    $slug = trim((string)($post['slug'] ?? ''));

    if ($slug !== '') {
        return 'blog-details.php?slug=' . rawurlencode($slug);
    }

    return 'blog-details.php?id=' . (int)($post['id'] ?? 0);
};
?>

<!-- Bootstrap & External CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;700;800&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">

<style>
/* =========================================================
   OPPULENT BLOGS — PREMIUM RESPONSIVE DESIGN
========================================================= */

#oppBlogs,
#oppBlogs * {
    box-sizing: border-box;
}

#oppBlogs {
    --ob-navy: #102b46;
    --ob-blue: #145da0;
    --ob-red: #c52b32;
    --ob-text: #263648;
    --ob-muted: #728196;
    --ob-line: #e5ebf2;
    --ob-bg: #f5f8fc;

    color: var(--ob-text);
    background: #fff;
    font-family: "Inter", "Segoe UI", Arial, sans-serif;
    overflow: hidden;
}

#oppBlogs a {
    text-decoration: none;
}

#oppBlogs .ob-container {
    width: min(1200px, calc(100% - 40px));
    margin: 0 auto;
}

#oppBlogs .ob-hero {
    position: relative;
    padding: 82px 0 75px;
    background:
        radial-gradient(circle at 86% 18%, rgba(43, 114, 174, .18), transparent 29%),
        linear-gradient(130deg, #0b2239, #173f63);
    overflow: hidden;
}

#oppBlogs .ob-hero::before,
#oppBlogs .ob-hero::after {
    content: "";
    position: absolute;
    border: 1px solid rgba(255,255,255,.09);
    border-radius: 50%;
    pointer-events: none;
}

#oppBlogs .ob-hero::before {
    width: 430px;
    height: 430px;
    right: -100px;
    top: -220px;
}

#oppBlogs .ob-hero::after {
    width: 300px;
    height: 300px;
    right: -40px;
    top: -155px;
}

#oppBlogs .ob-hero-inner {
    position: relative;
    z-index: 1;
    max-width: 850px;
    margin: 0 auto;
    text-align: center;
}

#oppBlogs .ob-eyebrow {
    display: inline-flex;
    align-items: center;
    gap: 9px;
    color: #ff9298;
    font-size: 11px;
    font-weight: 850;
    letter-spacing: 2.2px;
    text-transform: uppercase;
}

#oppBlogs .ob-eyebrow::before {
    content: "";
    width: 23px;
    height: 2px;
    background: currentColor;
}

#oppBlogs .ob-hero h1 {
    margin: 18px 0;
    color: #fff;
    font-size: clamp(38px, 5.5vw, 65px);
    font-weight: 900;
    line-height: 1.05;
    letter-spacing: -2.3px;
}

#oppBlogs .ob-hero h1 span {
    color: #f06d73;
}

#oppBlogs .ob-hero p {
    max-width: 690px;
    margin: 0 auto;
    color: #cad7e5;
    font-size: 15px;
    line-height: 1.9;
}

#oppBlogs .ob-search-wrap {
    max-width: 650px;
    margin: 32px auto 0;
}

#oppBlogs .ob-search {
    display: flex;
    gap: 10px;
    padding: 7px;
    background: #fff;
    border: 1px solid rgba(255,255,255,.2);
    border-radius: 13px;
    box-shadow: 0 15px 40px rgba(0,0,0,.13);
}

#oppBlogs .ob-search input {
    flex: 1;
    min-width: 0;
    height: 48px;
    padding: 0 14px;
    color: #24384d;
    background: transparent;
    border: 0;
    outline: none;
    font-family: inherit;
    font-size: 14px;
}

#oppBlogs .ob-search button {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    min-width: 120px;
    padding: 12px 18px;
    color: #fff;
    background: var(--ob-red);
    border: 0;
    border-radius: 9px;
    font-family: inherit;
    font-size: 13px;
    font-weight: 800;
    cursor: pointer;
    transition: background .2s;
}

#oppBlogs .ob-search button:hover {
    background: #a81e26;
}

/* FILTER BAR */
#oppBlogs .ob-filter-section {
    padding: 25px 0;
    background: #fff;
    border-bottom: 1px solid var(--ob-line);
}

#oppBlogs .ob-filter-inner {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
}

#oppBlogs .ob-filter-label {
    flex-shrink: 0;
    color: var(--ob-navy);
    font-size: 13px;
    font-weight: 850;
}

#oppBlogs .ob-category-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
    gap: 8px;
}

#oppBlogs .ob-category-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 10px 14px;
    color: #64758a;
    background: #f5f7fa;
    border: 1px solid #e9eef4;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 750;
    transition: color .2s, background .2s, border-color .2s;
}

#oppBlogs .ob-category-link:hover,
#oppBlogs .ob-category-link.is-active {
    color: #fff;
    background: var(--ob-navy);
    border-color: var(--ob-navy);
}

/* BLOG SECTION */
#oppBlogs .ob-blog-section {
    padding: 70px 0 85px;
    background: var(--ob-bg);
}

#oppBlogs .ob-section-head {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    gap: 20px;
    margin-bottom: 32px;
}

#oppBlogs .ob-section-head h2 {
    margin: 10px 0 0;
    color: var(--ob-navy);
    font-size: clamp(29px, 3.5vw, 42px);
    font-weight: 900;
    letter-spacing: -1.4px;
}

#oppBlogs .ob-section-head p {
    max-width: 470px;
    margin: 0;
    color: var(--ob-muted);
    font-size: 13px;
    line-height: 1.8;
}

#oppBlogs .ob-featured {
    display: grid;
    grid-template-columns: 1.04fr .96fr;
    overflow: hidden;
    margin-bottom: 35px;
    background: #fff;
    border: 1px solid var(--ob-line);
    border-radius: 20px;
    box-shadow: 0 12px 35px rgba(17, 43, 69, .05);
}

#oppBlogs .ob-featured-image {
    min-height: 335px;
    position: relative;
    overflow: hidden;
    background: #e7edf4;
}

#oppBlogs .ob-featured-image img {
    width: 100%;
    height: 100%;
    min-height: 335px;
    display: block;
    object-fit: cover;
    transition: transform .55s;
}

#oppBlogs .ob-featured:hover .ob-featured-image img {
    transform: scale(1.04);
}

#oppBlogs .ob-featured-placeholder,
#oppBlogs .ob-card-placeholder {
    display: grid;
    place-items: center;
    width: 100%;
    height: 100%;
    min-height: 280px;
    color: #fff;
    background:
        radial-gradient(circle at 80% 20%, rgba(255,255,255,.15), transparent 35%),
        linear-gradient(140deg, #143958, #276b99);
}

#oppBlogs .ob-featured-placeholder span,
#oppBlogs .ob-card-placeholder span {
    font-size: 64px;
    font-weight: 900;
    opacity: .8;
}

#oppBlogs .ob-featured-copy {
    padding: 35px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
}

#oppBlogs .ob-tag {
    display: inline-flex;
    padding: 7px 11px;
    color: #a9222a;
    background: #fff0f0;
    border-radius: 30px;
    font-size: 10px;
    font-weight: 850;
    letter-spacing: 1px;
    text-transform: uppercase;
}

#oppBlogs .ob-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 13px;
    margin: 17px 0 12px;
    color: #8190a2;
    font-size: 11px;
    font-weight: 650;
}

#oppBlogs .ob-featured-copy h3 {
    margin: 0 0 14px;
    color: var(--ob-navy);
    font-size: clamp(23px, 2.6vw, 32px);
    font-weight: 850;
    line-height: 1.3;
    letter-spacing: -.7px;
}

#oppBlogs .ob-featured-copy h3 a,
#oppBlogs .ob-card-title a {
    color: inherit;
}

#oppBlogs .ob-featured-copy h3 a:hover,
#oppBlogs .ob-card-title a:hover {
    color: var(--ob-red);
}

#oppBlogs .ob-featured-copy p {
    margin: 0 0 23px;
    color: var(--ob-muted);
    font-size: 13px;
    line-height: 1.9;
}

#oppBlogs .ob-read-link {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    color: var(--ob-blue);
    font-size: 12px;
    font-weight: 850;
}

#oppBlogs .ob-read-link span {
    display: inline-grid;
    place-items: center;
    width: 27px;
    height: 27px;
    color: #fff;
    background: var(--ob-blue);
    border-radius: 50%;
    transition: transform .2s, background .2s;
}

#oppBlogs .ob-read-link:hover {
    color: var(--ob-red);
}

#oppBlogs .ob-read-link:hover span {
    background: var(--ob-red);
    transform: translateX(4px);
}

/* CARDS */
#oppBlogs .ob-blog-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 24px;
}

#oppBlogs .ob-card {
    display: flex;
    flex-direction: column;
    min-width: 0;
    overflow: hidden;
    background: #fff;
    border: 1px solid #e6ebf2;
    border-radius: 16px;
    box-shadow: 0 5px 20px rgba(17, 43, 69, .035);
    transition: transform .25s, box-shadow .25s, border-color .25s;
}

#oppBlogs .ob-card:hover {
    transform: translateY(-6px);
    border-color: #d1dce8;
    box-shadow: 0 18px 40px rgba(17, 43, 69, .09);
}

#oppBlogs .ob-card-image {
    display: block;
    height: 220px;
    overflow: hidden;
    background: #e8eef5;
}

#oppBlogs .ob-card-image img {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: cover;
    transition: transform .5s;
}

#oppBlogs .ob-card:hover .ob-card-image img {
    transform: scale(1.055);
}

#oppBlogs .ob-card-placeholder {
    min-height: 220px;
    height: 220px;
}

#oppBlogs .ob-card-placeholder span {
    font-size: 45px;
}

#oppBlogs .ob-card-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 23px;
}

#oppBlogs .ob-card-title {
    margin: 0 0 12px;
    color: var(--ob-navy);
    font-size: 19px;
    font-weight: 850;
    line-height: 1.42;
    letter-spacing: -.35px;
}

#oppBlogs .ob-card-excerpt {
    flex: 1;
    margin: 0 0 20px;
    color: var(--ob-muted);
    font-size: 12px;
    line-height: 1.9;
}

#oppBlogs .ob-card-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    width: 100%;
    padding-top: 15px;
    border-top: 1px solid #edf1f5;
}

#oppBlogs .ob-card-date {
    color: #8290a0;
    font-size: 10px;
    font-weight: 700;
}

/* EMPTY STATE */
#oppBlogs .ob-empty {
    grid-column: 1 / -1;
    padding: 60px 25px;
    text-align: center;
    background: #fff;
    border: 1px dashed #cad5e2;
    border-radius: 17px;
}

#oppBlogs .ob-empty-symbol {
    display: grid;
    place-items: center;
    width: 60px;
    height: 60px;
    margin: 0 auto 18px;
    color: var(--ob-blue);
    background: #eaf2fa;
    border-radius: 50%;
    font-size: 25px;
    font-weight: 900;
}

#oppBlogs .ob-empty h3 {
    margin: 0 0 10px;
    color: var(--ob-navy);
    font-size: 23px;
    font-weight: 850;
}

#oppBlogs .ob-empty p {
    margin: 0 0 20px;
    color: var(--ob-muted);
    font-size: 13px;
    line-height: 1.8;
}

#oppBlogs .ob-reset {
    display: inline-flex;
    padding: 11px 17px;
    color: #fff;
    background: var(--ob-navy);
    border-radius: 8px;
    font-size: 12px;
    font-weight: 800;
}

/* PAGINATION */
#oppBlogs .ob-pagination {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    gap: 8px;
    margin-top: 42px;
}

#oppBlogs .ob-page-link {
    display: inline-grid;
    place-items: center;
    min-width: 42px;
    height: 42px;
    padding: 0 13px;
    color: #52667b;
    background: #fff;
    border: 1px solid #dfe7ef;
    border-radius: 9px;
    font-size: 12px;
    font-weight: 800;
    transition: color .2s, background .2s;
}

#oppBlogs .ob-page-link:hover,
#oppBlogs .ob-page-link.is-current {
    color: #fff;
    background: var(--ob-navy);
    border-color: var(--ob-navy);
}

/* CTA */
#oppBlogs .ob-cta {
    padding: 55px 0;
    background: linear-gradient(115deg, #102b46, #174d79);
}

#oppBlogs .ob-cta-inner {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 25px;
}

#oppBlogs .ob-cta h2 {
    margin: 0 0 9px;
    color: #fff;
    font-size: clamp(23px, 3vw, 34px);
    font-weight: 850;
    letter-spacing: -.6px;
}

#oppBlogs .ob-cta p {
    margin: 0;
    color: #cbd9e7;
    font-size: 13px;
    line-height: 1.8;
}

#oppBlogs .ob-cta-button {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 9px;
    flex-shrink: 0;
    padding: 14px 20px;
    color: #fff;
    background: var(--ob-red);
    border-radius: 9px;
    font-size: 12px;
    font-weight: 850;
    transition: background .2s, transform .2s;
}

#oppBlogs .ob-cta-button:hover {
    color: #fff;
    background: #a81e26;
    transform: translateY(-2px);
}

#oppBlogs a:focus-visible,
#oppBlogs button:focus-visible,
#oppBlogs input:focus-visible {
    outline: 3px solid #75b7f3;
    outline-offset: 3px;
}

/* RESPONSIVE */
@media (max-width: 950px) {
    #oppBlogs .ob-blog-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    #oppBlogs .ob-featured {
        grid-template-columns: 1fr 1fr;
    }

    #oppBlogs .ob-featured-copy {
        padding: 25px;
    }

    #oppBlogs .ob-filter-inner {
        align-items: flex-start;
        flex-direction: column;
    }

    #oppBlogs .ob-category-list {
        justify-content: flex-start;
    }
}

@media (max-width: 650px) {
    #oppBlogs .ob-container {
        width: min(100% - 30px, 520px);
    }

    #oppBlogs .ob-hero {
        padding: 55px 0;
    }

    #oppBlogs .ob-hero h1 {
        letter-spacing: -1.4px;
    }

    #oppBlogs .ob-search {
        flex-direction: column;
    }

    #oppBlogs .ob-search button {
        width: 100%;
    }

    #oppBlogs .ob-blog-section {
        padding: 48px 0 60px;
    }

    #oppBlogs .ob-section-head {
        align-items: flex-start;
        flex-direction: column;
    }

    #oppBlogs .ob-featured {
        grid-template-columns: 1fr;
    }

    #oppBlogs .ob-featured-image,
    #oppBlogs .ob-featured-image img {
        min-height: 240px;
        height: 240px;
    }

    #oppBlogs .ob-featured-copy {
        padding: 25px 22px;
    }

    #oppBlogs .ob-blog-grid {
        grid-template-columns: 1fr;
        gap: 19px;
    }

    #oppBlogs .ob-card-image {
        height: 235px;
    }

    #oppBlogs .ob-cta-inner {
        align-items: flex-start;
        flex-direction: column;
    }
}

@media (prefers-reduced-motion: reduce) {
    #oppBlogs *,
    #oppBlogs *::before,
    #oppBlogs *::after {
        transition-duration: .01ms !important;
        animation-duration: .01ms !important;
    }
}
</style>

<main id="oppBlogs">

    <!-- HERO -->
    <section class="ob-hero">
        <div class="ob-container">
            <div class="ob-hero-inner">

                <span class="ob-eyebrow">Knowledge • Innovation • Industry</span>

                <h1>
                    Our Blogs &<br>
                    <span>Industry Insights</span>
                </h1>

                <p>
                    Discover chemical industry insights, product knowledge,
                    applications, innovations and useful information for
                    businesses working across diverse industrial sectors.
                </p>

                <div class="ob-search-wrap">
                    <form class="ob-search" method="get" action="blogs.php">
                        <?php if ($selectedCategory !== ''): ?>
                            <input
                                type="hidden"
                                name="category"
                                value="<?= opp_blog_escape($selectedCategory) ?>"
                            >
                        <?php endif; ?>

                        <input
                            type="search"
                            name="q"
                            value="<?= opp_blog_escape($search) ?>"
                            placeholder="Search articles, chemicals, industries..."
                            aria-label="Search blog articles"
                        >

                        <button type="submit">
                            Search <span aria-hidden="true">?</span>
                        </button>
                    </form>
                </div>

            </div>
        </div>
    </section>

    <!-- CATEGORY FILTER -->
    <section class="ob-filter-section">
        <div class="ob-container">
            <div class="ob-filter-inner">

                <div class="ob-filter-label">Explore Topics</div>

                <nav class="ob-category-list" aria-label="Blog categories">

                    <a
                        class="ob-category-link <?= $selectedCategory === '' ? 'is-active' : '' ?>"
                        href="<?= opp_blog_escape($blogUrl(['category' => '', 'page' => 1])) ?>"
                    >
                        All Articles
                    </a>

                    <?php foreach ($blogCategories as $category): ?>
                        <?php
                        $categoryValue = !empty($category['slug'])
                            ? (string)$category['slug']
                            : (string)$category['id'];
                        ?>
                        <a
                            class="ob-category-link <?= $selectedCategory === $categoryValue ? 'is-active' : '' ?>"
                            href="<?= opp_blog_escape($blogUrl([
                                'category' => $categoryValue,
                                'page' => 1
                            ])) ?>"
                        >
                            <?= opp_blog_escape($category['name'] ?? 'Category') ?>
                        </a>
                    <?php endforeach; ?>

                </nav>
            </div>
        </div>
    </section>

    <!-- BLOG CONTENT -->
    <section class="ob-blog-section">
        <div class="ob-container">

            <div class="ob-section-head">
                <div>
                    <span class="ob-eyebrow">Latest Knowledge</span>
                    <h2>
                        <?= $search !== '' ? 'Search Results' : 'Latest Articles' ?>
                    </h2>
                </div>

                <p>
                    Read our latest articles to explore product applications,
                    industry developments and practical chemical knowledge.
                </p>
            </div>

            <?php
            /*
             * Featured article is shown separately on the first page
             * only when a featured post exists.
             */
            $displayPosts = $blogPosts;

            if ($page === 1 && $featuredBlog) {
                $displayPosts = array_values(array_filter(
                    $blogPosts,
                    function ($post) use ($featuredBlog) {
                        return (int)($post['id'] ?? 0) !== (int)($featuredBlog['id'] ?? 0);
                    }
                ));
            }
            ?>

            <?php if ($page === 1 && $featuredBlog): ?>
                <?php
                $featuredImage = opp_blog_image($featuredBlog['image'] ?? '');
                $featuredTitle = (string)($featuredBlog['title'] ?? 'Featured Article');
                $featuredExcerpt = opp_blog_excerpt(
                    $featuredBlog['excerpt'] ?? $featuredBlog['content'] ?? '',
                    230
                );
                ?>
                <article class="ob-featured">

                    <a
                        class="ob-featured-image"
                        href="<?= opp_blog_escape($blogDetailUrl($featuredBlog)) ?>"
                        aria-label="Read <?= opp_blog_escape($featuredTitle) ?>"
                    >
                        <?php if ($featuredImage !== ''): ?>
                            <img
                                src="<?= opp_blog_escape($featuredImage) ?>"
                                alt="<?= opp_blog_escape($featuredTitle) ?>"
                                loading="eager"
                                onerror="this.style.display='none';"
                            >
                        <?php else: ?>
                            <div class="ob-featured-placeholder">
                                <span>OP</span>
                            </div>
                        <?php endif; ?>
                    </a>

                    <div class="ob-featured-copy">
                        <span class="ob-tag">
                            <?= opp_blog_escape($featuredBlog['category_name'] ?: 'Featured Article') ?>
                        </span>

                        <div class="ob-meta">
                            <?php if (!empty($featuredBlog['published_at'])): ?>
                                <span>
                                    <?= opp_blog_escape(date(
                                        'd M Y',
                                        strtotime((string)$featuredBlog['published_at']) ?: time()
                                    )) ?>
                                </span>
                            <?php endif; ?>

                            <?php if (!empty($featuredBlog['author_name'])): ?>
                                <span>By <?= opp_blog_escape($featuredBlog['author_name']) ?></span>
                            <?php endif; ?>
                        </div>

                        <h3>
                            <a href="<?= opp_blog_escape($blogDetailUrl($featuredBlog)) ?>">
                                <?= opp_blog_escape($featuredTitle) ?>
                            </a>
                        </h3>

                        <p>
                            <?= opp_blog_escape(
                                $featuredExcerpt !== ''
                                    ? $featuredExcerpt
                                    : 'Explore this article for useful information, product knowledge and industry insights.'
                            ) ?>
                        </p>

                        <a
                            class="ob-read-link"
                            href="<?= opp_blog_escape($blogDetailUrl($featuredBlog)) ?>"
                        >
                            Read Featured Article <span aria-hidden="true">?</span>
                        </a>
                    </div>
                </article>
            <?php endif; ?>

            <div class="ob-blog-grid">

                <?php if (!$blogPosts): ?>

                    <div class="ob-empty">
                        <div class="ob-empty-symbol" aria-hidden="true">i</div>

                        <h3>
                            <?= $blogError ? 'Articles Are Not Available Yet' : 'No Articles Found' ?>
                        </h3>

                        <p>
                            <?php if ($blogError): ?>
                                Blog data could not be loaded. Please check the
                                database connection, table columns and published
                                article status in your admin panel.
                            <?php else: ?>
                                We couldn't find any articles matching your search.
                                Try a different keyword or view all articles.
                            <?php endif; ?>
                        </p>

                        <?php if ($search !== '' || $selectedCategory !== ''): ?>
                            <a class="ob-reset" href="blogs.php">View All Articles</a>
                        <?php endif; ?>
                    </div>

                <?php else: ?>

                    <?php foreach ($displayPosts as $post): ?>
                        <?php
                        $postTitle = (string)($post['title'] ?? 'Chemical Industry Article');
                        $postImage = opp_blog_image($post['image'] ?? '');
                        $postExcerpt = opp_blog_excerpt(
                            $post['excerpt'] ?? $post['content'] ?? '',
                            145
                        );
                        $postDate = '';

                        if (!empty($post['published_at'])) {
                            $timestamp = strtotime((string)$post['published_at']);

                            if ($timestamp !== false) {
                                $postDate = date('d M Y', $timestamp);
                            }
                        }
                        ?>

                        <article class="ob-card">

                            <a
                                class="ob-card-image"
                                href="<?= opp_blog_escape($blogDetailUrl($post)) ?>"
                                aria-label="Read <?= opp_blog_escape($postTitle) ?>"
                            >
                                <?php if ($postImage !== ''): ?>
                                    <img
                                        src="<?= opp_blog_escape($postImage) ?>"
                                        alt="<?= opp_blog_escape($postTitle) ?>"
                                        loading="lazy"
                                        onerror="this.style.display='none';"
                                    >
                                <?php else: ?>
                                    <div class="ob-card-placeholder">
                                        <span>OP</span>
                                    </div>
                                <?php endif; ?>
                            </a>

                            <div class="ob-card-body">

                                <span class="ob-tag">
                                    <?= opp_blog_escape(
                                        $post['category_name'] ?: 'Industry Insights'
                                    ) ?>
                                </span>

                                <div class="ob-meta">
                                    <?php if ($postDate !== ''): ?>
                                        <span><?= opp_blog_escape($postDate) ?></span>
                                    <?php endif; ?>

                                    <?php if (!empty($post['author_name'])): ?>
                                        <span>By <?= opp_blog_escape($post['author_name']) ?></span>
                                    <?php endif; ?>
                                </div>

                                <h3 class="ob-card-title">
                                    <a href="<?= opp_blog_escape($blogDetailUrl($post)) ?>">
                                        <?= opp_blog_escape($postTitle) ?>
                                    </a>
                                </h3>

                                <p class="ob-card-excerpt">
                                    <?= opp_blog_escape(
                                        $postExcerpt !== ''
                                            ? $postExcerpt
                                            : 'Read this article to learn more about chemical products, applications and industry knowledge.'
                                    ) ?>
                                </p>

                                <div class="ob-card-footer">
                                    <span class="ob-card-date">
                                        <?= $postDate !== '' ? opp_blog_escape($postDate) : 'Industry Article' ?>
                                    </span>

                                    <a
                                        class="ob-read-link"
                                        href="<?= opp_blog_escape($blogDetailUrl($post)) ?>"
                                        aria-label="Read <?= opp_blog_escape($postTitle) ?>"
                                    >
                                        Read More <span aria-hidden="true">?</span>
                                    </a>
                                </div>

                            </div>
                        </article>

                    <?php endforeach; ?>

                <?php endif; ?>

            </div>

            <!-- PAGINATION -->
            <?php if (!$blogError && $totalPages > 1): ?>
                <nav class="ob-pagination" aria-label="Blog pagination">

                    <?php if ($page > 1): ?>
                        <a
                            class="ob-page-link"
                            href="<?= opp_blog_escape($blogUrl(['page' => $page - 1])) ?>"
                            aria-label="Previous page"
                        >
                            ? Previous
                        </a>
                    <?php endif; ?>

                    <?php
                    $startPage = max(1, $page - 2);
                    $endPage = min($totalPages, $page + 2);

                    for ($pageNumber = $startPage; $pageNumber <= $endPage; $pageNumber++):
                    ?>
                        <a
                            class="ob-page-link <?= $pageNumber === $page ? 'is-current' : '' ?>"
                            href="<?= opp_blog_escape($blogUrl(['page' => $pageNumber])) ?>"
                            <?= $pageNumber === $page ? 'aria-current="page"' : '' ?>
                        >
                            <?= $pageNumber ?>
                        </a>
                    <?php endfor; ?>

                    <?php if ($page < $totalPages): ?>
                        <a
                            class="ob-page-link"
                            href="<?= opp_blog_escape($blogUrl(['page' => $page + 1])) ?>"
                            aria-label="Next page"
                        >
                            Next ?
                        </a>
                    <?php endif; ?>

                </nav>
            <?php endif; ?>

        </div>
    </section>

    <!-- CONTACT CTA -->
    <section class="ob-cta">
        <div class="ob-container">
            <div class="ob-cta-inner">
                <div>
                    <h2>Looking for Chemical Supply Solutions?</h2>
                    <p>
                        Contact our team to discuss your product requirements
                        and request further information.
                    </p>
                </div>

                <a class="ob-cta-button" href="contact.php">
                    Contact Our Team <span aria-hidden="true">?</span>
                </a>
            </div>
        </div>
    </section>

</main>

<?php require_once __DIR__ . '/footer.php'; ?>
