<?php
/**
 * PURE CHEMICAL — PREMIUM SEARCH PAGE
 * File: /search.php
 *
 * Features:
 * - Database-driven search
 * - PDO / MySQLi connection support
 * - Dynamic table and column detection
 * - Prepared statements
 * - Responsive premium UI
 * - A-Z / Chemist / Application filters
 * - Pagination
 * - No-results suggestions
 *
 * Existing project:
 * /admin/includes/db.php
 * /header.php
 * /footer.php
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/admin/includes/db.php';

/* ---------------------------------------------------------
   DATABASE CONNECTION DETECTION
--------------------------------------------------------- */

$db = null;
$dbType = '';

foreach (['pdo', 'conn', 'con', 'mysqli', 'db'] as $candidate) {
    if (isset($$candidate)) {
        if ($$candidate instanceof PDO) {
            $db = $$candidate;
            $dbType = 'pdo';
            break;
        }

        if ($$candidate instanceof mysqli) {
            $db = $$candidate;
            $dbType = 'mysqli';
            break;
        }
    }
}

/* ---------------------------------------------------------
   HELPERS
--------------------------------------------------------- */

if (!function_exists('pc_search_escape')) {
    function pc_search_escape($value): string
    {
        return htmlspecialchars(
            (string) $value,
            ENT_QUOTES | ENT_SUBSTITUTE,
            'UTF-8'
        );
    }
}

if (!function_exists('pc_search_identifier')) {
    function pc_search_identifier(string $name): string
    {
        return '`' . str_replace('`', '``', $name) . '`';
    }
}

if (!function_exists('pc_search_slug')) {
    function pc_search_slug(string $value): string
    {
        return strtolower(trim($value));
    }
}

if (!function_exists('pc_search_normalize')) {
    function pc_search_normalize(string $value): string
    {
        return trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
    }
}

/* ---------------------------------------------------------
   REQUEST
--------------------------------------------------------- */

$searchQuery = pc_search_normalize(
    (string) ($_POST['search_query'] ?? $_GET['search_query'] ?? $_GET['q'] ?? '')
);

$searchType = (string) ($_POST['search_type'] ?? $_GET['search_type'] ?? 'az');

$allowedTypes = ['az', 'chemist', 'application'];

if (!in_array($searchType, $allowedTypes, true)) {
    $searchType = 'az';
}

$searchQuery = mb_substr($searchQuery, 0, 100, 'UTF-8');

$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 12;
$offset = ($page - 1) * $perPage;

$results = [];
$totalResults = 0;
$searchError = false;
$searchSubmitted = ($searchQuery !== '');

/* ---------------------------------------------------------
   TABLE CONFIGURATION

   Only these known tables are searched.
   The code checks whether each table and column exists.
--------------------------------------------------------- */

$searchTables = [
    'products' => [
        'label' => 'Product',
        'title' => ['name', 'title', 'product_name', 'product_title'],
        'description' => ['description', 'short_description', 'details', 'summary'],
        'slug' => ['slug', 'url_slug'],
        'url' => 'product-details.php',
        'types' => ['az', 'chemist', 'application'],
    ],

    'product_categories' => [
        'label' => 'Product Category',
        'title' => ['name', 'title', 'category_name'],
        'description' => ['description', 'short_description'],
        'slug' => ['slug'],
        'url' => 'performance-chemicals.php',
        'types' => ['az', 'application'],
    ],

    'categories' => [
        'label' => 'Category',
        'title' => ['name', 'title', 'category_name'],
        'description' => ['description', 'short_description'],
        'slug' => ['slug'],
        'url' => 'performance-chemicals.php',
        'types' => ['az', 'application'],
    ],

    'industries' => [
        'label' => 'Industry',
        'title' => ['name', 'title', 'industry_name'],
        'description' => ['description', 'short_description'],
        'slug' => ['slug'],
        'url' => 'industries.php',
        'types' => ['az', 'application'],
    ],

    'services' => [
        'label' => 'Service',
        'title' => ['name', 'title', 'service_name'],
        'description' => ['description', 'short_description'],
        'slug' => ['slug'],
        'url' => 'services.php',
        'types' => ['az', 'application'],
    ],

    'brands' => [
        'label' => 'Brand',
        'title' => ['name', 'title', 'brand_name'],
        'description' => ['description', 'short_description'],
        'slug' => ['slug'],
        'url' => 'brands.php',
        'types' => ['az', 'chemist'],
    ],

    'pages' => [
        'label' => 'Page',
        'title' => ['title', 'name', 'page_title'],
        'description' => ['description', 'content', 'meta_description'],
        'slug' => ['slug'],
        'url' => 'page.php',
        'types' => ['az'],
    ],

    'blog_posts' => [
        'label' => 'Article',
        'title' => ['title', 'name', 'post_title'],
        'description' => ['excerpt', 'short_description', 'description', 'content'],
        'slug' => ['slug'],
        'url' => 'blog-details.php',
        'types' => ['az'],
    ],
];

/* ---------------------------------------------------------
   DATABASE INSPECTION HELPERS
--------------------------------------------------------- */

if (!function_exists('pc_search_table_exists')) {
    function pc_search_table_exists($db, string $dbType, string $table): bool
    {
        try {
            if ($dbType === 'pdo') {
                $stmt = $db->prepare(
                    'SHOW TABLES LIKE :table_name'
                );
                $stmt->execute([':table_name' => $table]);
                return (bool) $stmt->fetchColumn();
            }

            if ($dbType === 'mysqli') {
                $safeTable = $db->real_escape_string($table);
                $query = "SHOW TABLES LIKE '{$safeTable}'";
                $result = $db->query($query);

                if (!$result) {
                    return false;
                }

                $exists = $result->num_rows > 0;
                $result->free();

                return $exists;
            }
        } catch (Throwable $e) {
            return false;
        }

        return false;
    }
}

if (!function_exists('pc_search_columns')) {
    function pc_search_columns($db, string $dbType, string $table): array
    {
        $columns = [];

        try {
            $sql = 'SHOW COLUMNS FROM ' . pc_search_identifier($table);

            if ($dbType === 'pdo') {
                $stmt = $db->query($sql);
                $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

                foreach ($rows as $row) {
                    if (!empty($row['Field'])) {
                        $columns[] = (string) $row['Field'];
                    }
                }
            } elseif ($dbType === 'mysqli') {
                $result = $db->query($sql);

                if ($result) {
                    while ($row = $result->fetch_assoc()) {
                        if (!empty($row['Field'])) {
                            $columns[] = (string) $row['Field'];
                        }
                    }

                    $result->free();
                }
            }
        } catch (Throwable $e) {
            return [];
        }

        return $columns;
    }
}

if (!function_exists('pc_search_pick_column')) {
    function pc_search_pick_column(array $columns, array $candidates): ?string
    {
        foreach ($candidates as $candidate) {
            if (in_array($candidate, $columns, true)) {
                return $candidate;
            }
        }

        return null;
    }
}

/* ---------------------------------------------------------
   BUILD AND EXECUTE SEARCH
--------------------------------------------------------- */

if ($searchSubmitted) {
    if (mb_strlen($searchQuery, 'UTF-8') < 2) {
        $searchError = 'Please enter at least 2 characters to search.';
    } elseif (!$db || !$dbType) {
        $searchError = 'Database connection was not detected. Please check admin/includes/db.php.';
    } else {
        try {
            $queryRows = [];

            /*
             * Search each configured table only when it exists.
             * Every SQL identifier comes from this fixed allowlist
             * and the actual database column list.
             */
            foreach ($searchTables as $table => $config) {
                if (!in_array($searchType, $config['types'], true)) {
                    continue;
                }

                if (!pc_search_table_exists($db, $dbType, $table)) {
                    continue;
                }

                $columns = pc_search_columns($db, $dbType, $table);

                if (!$columns) {
                    continue;
                }

                $titleColumn = pc_search_pick_column(
                    $columns,
                    $config['title']
                );

                if (!$titleColumn) {
                    continue;
                }

                $descriptionColumn = pc_search_pick_column(
                    $columns,
                    $config['description']
                );

                $slugColumn = pc_search_pick_column(
                    $columns,
                    $config['slug']
                );

                $statusColumn = pc_search_pick_column(
                    $columns,
                    ['status', 'is_active', 'active', 'published']
                );

                $conditions = [];
                $params = [];

                $conditions[] =
                    pc_search_identifier($titleColumn) . ' LIKE ?';

                $params[] = '%' . $searchQuery . '%';

                if ($descriptionColumn) {
                    $conditions[] =
                        pc_search_identifier($descriptionColumn) . ' LIKE ?';

                    $params[] = '%' . $searchQuery . '%';
                }

                /*
                 * If a status field exists, try to show active/public
                 * records only. Unknown status formats are handled
                 * without requiring a particular schema.
                 */
                $where = '(' . implode(' OR ', $conditions) . ')';

                if ($statusColumn) {
                    $where .= ' AND (
                        ' . pc_search_identifier($statusColumn) . ' = 1
                        OR LOWER(CAST(' . pc_search_identifier($statusColumn) . ' AS CHAR))
                           IN ("active", "published", "enabled", "1")
                    )';
                }

                $selectColumns = [
                    pc_search_identifier($titleColumn) . ' AS result_title'
                ];

                if ($descriptionColumn) {
                    $selectColumns[] =
                        pc_search_identifier($descriptionColumn) . ' AS result_description';
                } else {
                    $selectColumns[] = '"" AS result_description';
                }

                if ($slugColumn) {
                    $selectColumns[] =
                        pc_search_identifier($slugColumn) . ' AS result_slug';
                } else {
                    $selectColumns[] = '"" AS result_slug';
                }

                $sql = 'SELECT ' . implode(', ', $selectColumns) .
                    ' FROM ' . pc_search_identifier($table) .
                    ' WHERE ' . $where .
                    ' LIMIT 100';

                if ($dbType === 'pdo') {
                    $stmt = $db->prepare($sql);
                    $stmt->execute($params);
                    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
                } else {
                    $stmt = $db->prepare($sql);

                    if (!$stmt) {
                        continue;
                    }

                    $types = str_repeat('s', count($params));
                    $stmt->bind_param($types, ...$params);
                    $stmt->execute();

                    $result = $stmt->get_result();
                    $rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

                    if ($result) {
                        $result->free();
                    }

                    $stmt->close();
                }

                foreach ($rows as $row) {
                    $title = trim((string) ($row['result_title'] ?? ''));

                    if ($title === '') {
                        continue;
                    }

                    $description = trim(
                        strip_tags((string) ($row['result_description'] ?? ''))
                    );

                    $slug = trim((string) ($row['result_slug'] ?? ''));

                    /*
                     * Avoid duplicate cards when a keyword matches
                     * more than one configured source.
                     */
                    $queryRows[] = [
                        'title' => $title,
                        'description' => $description,
                        'type' => $config['label'],
                        'table' => $table,
                        'slug' => $slug,
                        'url' => $config['url'],
                    ];
                }
            }

            /* Remove duplicate title/type pairs. */
            $unique = [];

            foreach ($queryRows as $item) {
                $key = mb_strtolower(
                    $item['type'] . '|' . $item['title'],
                    'UTF-8'
                );

                if (!isset($unique[$key])) {
                    $unique[$key] = $item;
                }
            }

            $queryRows = array_values($unique);

            /*
             * Sort exact title matches first, then alphabetical.
             */
            usort($queryRows, function ($a, $b) use ($searchQuery) {
                $aExact = mb_strtolower($a['title'], 'UTF-8') ===
                    mb_strtolower($searchQuery, 'UTF-8');

                $bExact = mb_strtolower($b['title'], 'UTF-8') ===
                    mb_strtolower($searchQuery, 'UTF-8');

                if ($aExact !== $bExact) {
                    return $aExact ? -1 : 1;
                }

                return strcasecmp($a['title'], $b['title']);
            });

            $totalResults = count($queryRows);
            $results = array_slice($queryRows, $offset, $perPage);

        } catch (Throwable $e) {
            /*
             * Do not expose SQL errors or credentials to visitors.
             * Check the PHP error log for technical details.
             */
            error_log('Pure Chemical search error: ' . $e->getMessage());
            $searchError = 'We could not complete your search right now. Please try again.';
        }
    }
}

/* ---------------------------------------------------------
   RESULT URL
--------------------------------------------------------- */

if (!function_exists('pc_search_result_url')) {
    function pc_search_result_url(array $item): string
    {
        $base = (string) ($item['url'] ?? 'performance-chemicals.php');
        $slug = trim((string) ($item['slug'] ?? ''));

        if ($slug === '') {
            return $base;
        }

        $param = 'slug';

        if (in_array($item['table'] ?? '', ['categories', 'product_categories'], true)) {
            $param = 'category';
        }

        return $base . '?' . rawurlencode($param) . '=' . rawurlencode($slug);
    }
}

/* ---------------------------------------------------------
   HEADER
--------------------------------------------------------- */

$pageTitle = 'Search Performance Chemicals | Pure Chemical';
$pageDescription = 'Search chemical products, applications, industries, brands and services.';

require_once __DIR__ . '/header.php';
?>

<style>
/* =========================================================
   PURE CHEMICAL — PREMIUM SEARCH PAGE
========================================================= */

.pc-search-page,
.pc-search-page * {
    box-sizing: border-box;
}

.pc-search-page {
    --pc-navy: #061b30;
    --pc-navy-light: #0b3151;
    --pc-blue: #087fe7;
    --pc-cyan: #00c9f2;
    --pc-text: #20364b;
    --pc-muted: #718197;
    --pc-line: #e3ebf3;
    --pc-surface: #f4f8fc;

    font-family: "Manrope", "Segoe UI", Arial, sans-serif;
    color: var(--pc-text);
    background: #fff;
    overflow: hidden;
}

.pc-search-container {
    width: min(1180px, calc(100% - 40px));
    margin-inline: auto;
}

.pc-search-hero {
    position: relative;
    isolation: isolate;
    padding: 76px 0 82px;
    background:
        radial-gradient(circle at 85% 15%, rgba(0, 201, 242, .20), transparent 28%),
        radial-gradient(circle at 12% 100%, rgba(8, 127, 231, .22), transparent 30%),
        linear-gradient(125deg, #041626 0%, #082a49 54%, #064b78 100%);
    color: #fff;
}

.pc-search-hero::before,
.pc-search-hero::after {
    content: "";
    position: absolute;
    z-index: -1;
    pointer-events: none;
    border: 1px solid rgba(255,255,255,.10);
    border-radius: 50%;
}

.pc-search-hero::before {
    width: 460px;
    height: 460px;
    right: -150px;
    top: -230px;
}

.pc-search-hero::after {
    width: 320px;
    height: 320px;
    right: -80px;
    top: -160px;
}

.pc-search-eyebrow {
    display: inline-flex;
    align-items: center;
    gap: 9px;
    padding: 9px 14px;
    border: 1px solid rgba(255,255,255,.20);
    border-radius: 999px;
    background: rgba(255,255,255,.07);
    color: #bdefff;
    font-size: 12px;
    font-weight: 800;
    letter-spacing: 1.7px;
    text-transform: uppercase;
}

.pc-search-eyebrow span {
    width: 7px;
    height: 7px;
    border-radius: 50%;
    background: var(--pc-cyan);
    box-shadow: 0 0 0 5px rgba(0,201,242,.13);
}

.pc-search-hero h1 {
    max-width: 850px;
    margin: 22px 0 15px;
    color: #fff;
    font-size: clamp(35px, 5.4vw, 64px);
    line-height: 1.08;
    font-weight: 850;
    letter-spacing: -2px;
}

.pc-search-hero h1 span {
    color: #62ddff;
}

.pc-search-hero p {
    max-width: 690px;
    margin: 0;
    color: #c1d4e4;
    font-size: 16px;
    line-height: 1.9;
}

.pc-search-breadcrumb {
    display: flex;
    align-items: center;
    gap: 9px;
    margin-top: 26px;
    color: #b5cada;
    font-size: 13px;
}

.pc-search-breadcrumb a {
    color: #fff;
    text-decoration: none;
}

.pc-search-breadcrumb a:hover {
    color: #62ddff;
}

.pc-search-main {
    padding: 0 0 80px;
    background:
        linear-gradient(180deg, #f4f8fc 0, #fff 300px);
}

.pc-search-panel {
    position: relative;
    margin-top: -36px;
    padding: 30px;
    border: 1px solid rgba(224,234,244,.9);
    border-radius: 22px;
    background: #fff;
    box-shadow: 0 20px 60px rgba(5,35,62,.10);
}

.pc-search-panel-heading {
    margin: 0 0 8px;
    color: var(--pc-navy);
    font-size: 22px;
    font-weight: 850;
    letter-spacing: -.5px;
}

.pc-search-panel-subtitle {
    margin: 0 0 22px;
    color: var(--pc-muted);
    font-size: 14px;
    line-height: 1.7;
}

.pc-search-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 9px;
    margin-bottom: 18px;
}

.pc-search-tab {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    min-height: 42px;
    padding: 10px 16px;
    border: 1px solid var(--pc-line);
    border-radius: 11px;
    background: #fff;
    color: #52667b;
    font: inherit;
    font-size: 13px;
    font-weight: 800;
    cursor: pointer;
    transition: .2s ease;
}

.pc-search-tab:hover {
    border-color: #9bdcff;
    color: var(--pc-blue);
}

.pc-search-tab.is-active {
    border-color: var(--pc-blue);
    background: #eaf5ff;
    color: #075db0;
}

.pc-search-tab .pc-tab-letter {
    display: grid;
    width: 22px;
    height: 22px;
    place-items: center;
    border-radius: 6px;
    background: rgba(8,127,231,.10);
    font-size: 11px;
}

.pc-search-form {
    display: flex;
    align-items: stretch;
    gap: 12px;
}

.pc-search-input-wrap {
    position: relative;
    flex: 1;
    min-width: 0;
}

.pc-search-input-wrap svg {
    position: absolute;
    left: 18px;
    top: 50%;
    width: 21px;
    height: 21px;
    transform: translateY(-50%);
    color: #8293a5;
    pointer-events: none;
}

.pc-search-input {
    display: block;
    width: 100%;
    min-height: 60px;
    padding: 16px 18px 16px 52px;
    border: 1px solid #dce6f0;
    border-radius: 13px;
    outline: none;
    background: #f9fbfd;
    color: var(--pc-navy);
    font: inherit;
    font-size: 15px;
    transition: .2s ease;
}

.pc-search-input:focus {
    border-color: var(--pc-blue);
    background: #fff;
    box-shadow: 0 0 0 4px rgba(8,127,231,.10);
}

.pc-search-input::placeholder {
    color: #91a0b0;
}

.pc-search-submit {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    min-width: 160px;
    padding: 15px 22px;
    border: 0;
    border-radius: 13px;
    background: linear-gradient(135deg, #087fe7, #075bb4);
    color: #fff;
    font: inherit;
    font-size: 14px;
    font-weight: 850;
    cursor: pointer;
    box-shadow: 0 9px 22px rgba(8,127,231,.20);
    transition: transform .2s ease, box-shadow .2s ease;
}

.pc-search-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 13px 28px rgba(8,127,231,.28);
}

.pc-search-submit svg {
    width: 18px;
    height: 18px;
}

.pc-search-help {
    margin-top: 13px;
    color: #8291a1;
    font-size: 12px;
    line-height: 1.7;
}

.pc-search-content {
    padding-top: 42px;
}

.pc-search-results-head {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    gap: 20px;
    margin-bottom: 24px;
}

.pc-search-results-head h2 {
    margin: 0 0 7px;
    color: var(--pc-navy);
    font-size: clamp(23px, 3vw, 32px);
    font-weight: 850;
    letter-spacing: -1px;
}

.pc-search-results-head p {
    margin: 0;
    color: var(--pc-muted);
    font-size: 14px;
    line-height: 1.7;
}

.pc-search-count {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    flex-shrink: 0;
    padding: 10px 14px;
    border: 1px solid #d9eaff;
    border-radius: 999px;
    background: #eff7ff;
    color: #075db0;
    font-size: 12px;
    font-weight: 850;
}

.pc-search-results-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 18px;
}

.pc-search-result-card {
    position: relative;
    display: flex;
    flex-direction: column;
    min-height: 218px;
    padding: 23px;
    overflow: hidden;
    border: 1px solid #e2eaf2;
    border-radius: 17px;
    background: #fff;
    text-decoration: none;
    box-shadow: 0 5px 18px rgba(12,42,69,.035);
    transition: transform .25s ease, border-color .25s ease, box-shadow .25s ease;
}

.pc-search-result-card::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--pc-blue), var(--pc-cyan));
    transition: width .25s ease;
}

.pc-search-result-card:hover {
    transform: translateY(-5px);
    border-color: #b8dcf9;
    box-shadow: 0 16px 35px rgba(12,42,69,.09);
}

.pc-search-result-card:hover::before {
    width: 100%;
}

.pc-search-result-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    margin-bottom: 19px;
}

.pc-search-result-icon {
    display: grid;
    width: 44px;
    height: 44px;
    place-items: center;
    border-radius: 13px;
    background: linear-gradient(135deg, #e8f5ff, #e8fbff);
    color: #0874d0;
}

.pc-search-result-icon svg {
    width: 22px;
    height: 22px;
}

.pc-search-result-type {
    padding: 6px 9px;
    border-radius: 7px;
    background: #f1f6fb;
    color: #5b7085;
    font-size: 10px;
    font-weight: 850;
    letter-spacing: .5px;
    text-transform: uppercase;
}

.pc-search-result-card h3 {
    margin: 0 0 10px;
    color: var(--pc-navy);
    font-size: 17px;
    line-height: 1.5;
    font-weight: 850;
    overflow-wrap: anywhere;
}

.pc-search-result-card p {
    display: -webkit-box;
    margin: 0 0 20px;
    overflow: hidden;
    color: #718197;
    font-size: 13px;
    line-height: 1.8;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
}

.pc-search-result-link {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    margin-top: auto;
    color: #0874d0;
    font-size: 12px;
    font-weight: 850;
}

.pc-search-result-link svg {
    width: 15px;
    height: 15px;
    transition: transform .2s ease;
}

.pc-search-result-card:hover .pc-search-result-link svg {
    transform: translateX(4px);
}

.pc-search-message {
    padding: 24px;
    border: 1px solid #f2d8d8;
    border-radius: 14px;
    background: #fff8f8;
    color: #923d3d;
    font-size: 14px;
    line-height: 1.8;
}

.pc-search-empty {
    padding: 55px 24px;
    border: 1px dashed #d7e4ef;
    border-radius: 20px;
    background: #f9fbfd;
    text-align: center;
}

.pc-search-empty-icon {
    display: grid;
    width: 72px;
    height: 72px;
    margin: 0 auto 20px;
    place-items: center;
    border-radius: 22px;
    background: #eaf5ff;
    color: #0874d0;
}

.pc-search-empty-icon svg {
    width: 32px;
    height: 32px;
}

.pc-search-empty h3 {
    margin: 0 0 10px;
    color: var(--pc-navy);
    font-size: 23px;
    font-weight: 850;
}

.pc-search-empty p {
    max-width: 560px;
    margin: 0 auto 22px;
    color: var(--pc-muted);
    font-size: 14px;
    line-height: 1.9;
}

.pc-search-suggestions {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 9px;
}

.pc-search-suggestions a {
    display: inline-flex;
    padding: 10px 13px;
    border: 1px solid #dce8f3;
    border-radius: 999px;
    background: #fff;
    color: #36536e;
    text-decoration: none;
    font-size: 12px;
    font-weight: 800;
    transition: .2s ease;
}

.pc-search-suggestions a:hover {
    border-color: var(--pc-blue);
    color: var(--pc-blue);
}

.pc-search-pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 32px;
}

.pc-search-pagination a,
.pc-search-pagination span {
    display: grid;
    min-width: 42px;
    height: 42px;
    padding: 0 12px;
    place-items: center;
    border: 1px solid #dce6f0;
    border-radius: 10px;
    background: #fff;
    color: #52667b;
    text-decoration: none;
    font-size: 13px;
    font-weight: 850;
}

.pc-search-pagination .is-current {
    border-color: var(--pc-blue);
    background: var(--pc-blue);
    color: #fff;
}

.pc-search-cta {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 28px;
    margin-top: 55px;
    padding: 30px 32px;
    border-radius: 20px;
    background:
        radial-gradient(circle at 100% 0%, rgba(0,201,242,.17), transparent 32%),
        linear-gradient(120deg, #061b30, #0a3658);
    color: #fff;
}

.pc-search-cta h3 {
    margin: 0 0 8px;
    color: #fff;
    font-size: 23px;
    font-weight: 850;
}

.pc-search-cta p {
    max-width: 650px;
    margin: 0;
    color: #c0d2e1;
    font-size: 13px;
    line-height: 1.8;
}

.pc-search-cta a {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    flex-shrink: 0;
    padding: 13px 18px;
    border-radius: 10px;
    background: #fff;
    color: #07355a;
    text-decoration: none;
    font-size: 13px;
    font-weight: 850;
    transition: .2s ease;
}

.pc-search-cta a:hover {
    transform: translateY(-2px);
    background: #c8f5ff;
}

@media (max-width: 900px) {
    .pc-search-results-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    .pc-search-hero {
        padding: 62px 0 70px;
    }

    .pc-search-panel {
        padding: 24px;
    }
}

@media (max-width: 600px) {
    .pc-search-container {
        width: min(100% - 28px, 1180px);
    }

    .pc-search-hero {
        padding: 48px 0 62px;
    }

    .pc-search-hero h1 {
        letter-spacing: -1px;
    }

    .pc-search-hero p {
        font-size: 14px;
    }

    .pc-search-panel {
        margin-top: -28px;
        padding: 19px;
        border-radius: 17px;
    }

    .pc-search-panel-heading {
        font-size: 20px;
    }

    .pc-search-form {
        flex-direction: column;
    }

    .pc-search-submit {
        width: 100%;
        min-height: 54px;
    }

    .pc-search-results-head {
        align-items: flex-start;
        flex-direction: column;
    }

    .pc-search-results-grid {
        grid-template-columns: 1fr;
        gap: 13px;
    }

    .pc-search-result-card {
        min-height: 195px;
        padding: 20px;
    }

    .pc-search-cta {
        align-items: flex-start;
        flex-direction: column;
        padding: 24px;
    }

    .pc-search-cta a {
        width: 100%;
    }
}

@media (prefers-reduced-motion: reduce) {
    .pc-search-page *,
    .pc-search-page *::before,
    .pc-search-page *::after {
        transition-duration: .01ms !important;
        animation-duration: .01ms !important;
    }
}
</style>

<main class="pc-search-page">

    <!-- HERO -->
    <section class="pc-search-hero">
        <div class="pc-search-container">

            <span class="pc-search-eyebrow">
                <span></span>
                Chemical Discovery Centre
            </span>

            <h1>
                Find the Right<br>
                <span>Chemical Solution.</span>
            </h1>

            <p>
                Explore chemical products, industry applications, specialist
                services and technical resources through one convenient search.
                Discover information relevant to your business requirements.
            </p>

            <nav class="pc-search-breadcrumb" aria-label="Breadcrumb">
                <a href="index.php">Home</a>
                <span aria-hidden="true">/</span>
                <span>Search</span>
            </nav>

        </div>
    </section>

    <!-- SEARCH -->
    <section class="pc-search-main">
        <div class="pc-search-container">

            <div class="pc-search-panel">

                <h2 class="pc-search-panel-heading">
                    What are you looking for?
                </h2>

                <p class="pc-search-panel-subtitle">
                    Search by product name, chemical category, industry,
                    application or keyword.
                </p>

                <div class="pc-search-tabs" role="group" aria-label="Search type">

                    <button
                        class="pc-search-tab <?= $searchType === 'az' ? 'is-active' : ''; ?>"
                        type="button"
                        data-search-type="az"
                        aria-pressed="<?= $searchType === 'az' ? 'true' : 'false'; ?>"
                    >
                        <span class="pc-tab-letter">A–Z</span>
                        All Results
                    </button>

                    <button
                        class="pc-search-tab <?= $searchType === 'chemist' ? 'is-active' : ''; ?>"
                        type="button"
                        data-search-type="chemist"
                        aria-pressed="<?= $searchType === 'chemist' ? 'true' : 'false'; ?>"
                    >
                        <span class="pc-tab-letter">C</span>
                        Products & Brands
                    </button>

                    <button
                        class="pc-search-tab <?= $searchType === 'application' ? 'is-active' : ''; ?>"
                        type="button"
                        data-search-type="application"
                        aria-pressed="<?= $searchType === 'application' ? 'true' : 'false'; ?>"
                    >
                        <span class="pc-tab-letter">A</span>
                        Applications
                    </button>

                </div>

                <form
                    class="pc-search-form"
                    action="search.php"
                    method="get"
                    role="search"
                >

                    <input
                        type="hidden"
                        name="search_type"
                        id="pcSearchType"
                        value="<?= pc_search_escape($searchType); ?>"
                    >

                    <div class="pc-search-input-wrap">

                        <svg viewBox="0 0 24 24" fill="none"
                             stroke="currentColor" stroke-width="2"
                             stroke-linecap="round" aria-hidden="true">
                            <circle cx="11" cy="11" r="7"></circle>
                            <path d="m20 20-4-4"></path>
                        </svg>

                        <label for="pcSearchInput" style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);">
                            Search chemical products and applications
                        </label>

                        <input
                            class="pc-search-input"
                            id="pcSearchInput"
                            type="search"
                            name="search_query"
                            value="<?= pc_search_escape($searchQuery); ?>"
                            placeholder="Enter a product, chemical or application..."
                            minlength="2"
                            maxlength="100"
                            autocomplete="off"
                            required
                        >

                    </div>

                    <button class="pc-search-submit" type="submit">
                        Search Now
                        <svg viewBox="0 0 24 24" fill="none"
                             stroke="currentColor" stroke-width="2"
                             stroke-linecap="round" stroke-linejoin="round"
                             aria-hidden="true">
                            <path d="M5 12h14"></path>
                            <path d="m12 5 7 7-7 7"></path>
                        </svg>
                    </button>

                </form>

                <div class="pc-search-help">
                    Tip: Try a specific chemical name, product category,
                    industry or application keyword.
                </div>

            </div>

            <!-- RESULTS -->
            <div class="pc-search-content">

                <?php if ($searchError !== ''): ?>

                    <div class="pc-search-message" role="alert">
                        <?= pc_search_escape($searchError); ?>
                    </div>

                <?php elseif ($searchSubmitted): ?>

                    <div class="pc-search-results-head">

                        <div>
                            <h2>Search Results</h2>

                            <p>
                                Results for
                                <strong>“<?= pc_search_escape($searchQuery); ?>”</strong>
                            </p>
                        </div>

                        <span class="pc-search-count">
                            <?= (int) $totalResults; ?>
                            <?= $totalResults === 1 ? 'Result' : 'Results'; ?>
                        </span>

                    </div>

                    <?php if (!empty($results)): ?>

                        <div class="pc-search-results-grid">

                            <?php foreach ($results as $item): ?>

                                <a
                                    class="pc-search-result-card"
                                    href="<?= pc_search_escape(pc_search_result_url($item)); ?>"
                                >

                                    <div class="pc-search-result-top">

                                        <span class="pc-search-result-icon">
                                            <svg viewBox="0 0 24 24" fill="none"
                                                 stroke="currentColor" stroke-width="1.8"
                                                 stroke-linecap="round" stroke-linejoin="round"
                                                 aria-hidden="true">
                                                <path d="M9 3h6"></path>
                                                <path d="M10 3v6.2l-5.2 8.3A2.3 2.3 0 0 0 6.7 21h10.6a2.3 2.3 0 0 0 1.9-3.5L14 9.2V3"></path>
                                                <path d="M8 15h8"></path>
                                            </svg>
                                        </span>

                                        <span class="pc-search-result-type">
                                            <?= pc_search_escape($item['type']); ?>
                                        </span>

                                    </div>

                                    <h3>
                                        <?= pc_search_escape($item['title']); ?>
                                    </h3>

                                    <?php if ($item['description'] !== ''): ?>
                                        <p>
                                            <?= pc_search_escape(
                                                mb_substr($item['description'], 0, 190, 'UTF-8')
                                            ); ?>
                                        </p>
                                    <?php else: ?>
                                        <p>
                                            Explore more information about this
                                            chemical product or related offering.
                                        </p>
                                    <?php endif; ?>

                                    <span class="pc-search-result-link">
                                        Explore Details

                                        <svg viewBox="0 0 24 24" fill="none"
                                             stroke="currentColor" stroke-width="2"
                                             stroke-linecap="round" stroke-linejoin="round"
                                             aria-hidden="true">
                                            <path d="M5 12h14"></path>
                                            <path d="m12 5 7 7-7 7"></path>
                                        </svg>
                                    </span>

                                </a>

                            <?php endforeach; ?>

                        </div>

                        <?php
                        $totalPages = (int) ceil($totalResults / $perPage);

                        if ($totalPages > 1):
                        ?>

                            <nav class="pc-search-pagination" aria-label="Search result pages">

                                <?php if ($page > 1): ?>
                                    <a href="?search_query=<?= rawurlencode($searchQuery); ?>&search_type=<?= rawurlencode($searchType); ?>&page=<?= $page - 1; ?>">
                                        &laquo; Previous
                                    </a>
                                <?php endif; ?>

                                <?php
                                $startPage = max(1, $page - 2);
                                $endPage = min($totalPages, $page + 2);

                                for ($p = $startPage; $p <= $endPage; $p++):
                                ?>
                                    <?php if ($p === $page): ?>
                                        <span class="is-current" aria-current="page">
                                            <?= $p; ?>
                                        </span>
                                    <?php else: ?>
                                        <a href="?search_query=<?= rawurlencode($searchQuery); ?>&search_type=<?= rawurlencode($searchType); ?>&page=<?= $p; ?>">
                                            <?= $p; ?>
                                        </a>
                                    <?php endif; ?>
                                <?php endfor; ?>

                                <?php if ($page < $totalPages): ?>
                                    <a href="?search_query=<?= rawurlencode($searchQuery); ?>&search_type=<?= rawurlencode($searchType); ?>&page=<?= $page + 1; ?>">
                                        Next &raquo;
                                    </a>
                                <?php endif; ?>

                            </nav>

                        <?php endif; ?>

                    <?php else: ?>

                        <div class="pc-search-empty">

                            <div class="pc-search-empty-icon">
                                <svg viewBox="0 0 24 24" fill="none"
                                     stroke="currentColor" stroke-width="1.7"
                                     stroke-linecap="round" stroke-linejoin="round"
                                     aria-hidden="true">
                                    <circle cx="11" cy="11" r="7"></circle>
                                    <path d="m20 20-4-4"></path>
                                    <path d="M8.5 8.5l5 5"></path>
                                    <path d="m13.5 8.5-5 5"></path>
                                </svg>
                            </div>

                            <h3>No matching results found</h3>

                            <p>
                                We couldn't find a match for
                                <strong>“<?= pc_search_escape($searchQuery); ?>”</strong>.
                                Try a different spelling, use a broader keyword,
                                or explore our chemical categories.
                            </p>

                            <div class="pc-search-suggestions">
                                <a href="performance-chemicals.php">Performance Chemicals</a>
                                <a href="index.php">Home</a>
                                <a href="contact.php">Contact Our Team</a>
                            </div>

                        </div>

                    <?php endif; ?>

                <?php else: ?>

                    <div class="pc-search-results-head">
                        <div>
                            <h2>Explore Our Chemical Portfolio</h2>
                            <p>
                                Start with a keyword or browse the main chemical
                                categories below.
                            </p>
                        </div>
                    </div>

                    <div class="pc-search-results-grid">

                        <?php
                        $quickLinks = [
                            [
                                'title' => 'Active Pharmaceutical Ingredients',
                                'description' => 'Explore pharmaceutical ingredient categories.',
                                'url' => 'performance-chemicals.php'
                            ],
                            [
                                'title' => 'Cosmetics & Personal Care',
                                'description' => 'Browse ingredients and solutions for personal care.',
                                'url' => 'performance-chemicals.php'
                            ],
                            [
                                'title' => 'Food Colours',
                                'description' => 'Explore colour-related chemical categories.',
                                'url' => 'performance-chemicals.php'
                            ],
                            [
                                'title' => 'Paints & Coatings',
                                'description' => 'Find chemical categories for coating applications.',
                                'url' => 'performance-chemicals.php'
                            ],
                            [
                                'title' => 'Textile Chemicals',
                                'description' => 'Explore chemicals for textile-related applications.',
                                'url' => 'performance-chemicals.php'
                            ],
                            [
                                'title' => 'Water Treatment Chemicals',
                                'description' => 'Browse water-treatment chemical categories.',
                                'url' => 'performance-chemicals.php'
                            ],
                        ];
                        ?>

                        <?php foreach ($quickLinks as $link): ?>

                            <a
                                class="pc-search-result-card"
                                href="<?= pc_search_escape($link['url']); ?>"
                            >

                                <div class="pc-search-result-top">
                                    <span class="pc-search-result-icon">
                                        <svg viewBox="0 0 24 24" fill="none"
                                             stroke="currentColor" stroke-width="1.8"
                                             stroke-linecap="round" stroke-linejoin="round"
                                             aria-hidden="true">
                                            <path d="M9 3h6"></path>
                                            <path d="M10 3v6.2l-5.2 8.3A2.3 2.3 0 0 0 6.7 21h10.6a2.3 2.3 0 0 0 1.9-3.5L14 9.2V3"></path>
                                        </svg>
                                    </span>
                                    <span class="pc-search-result-type">Explore</span>
                                </div>

                                <h3><?= pc_search_escape($link['title']); ?></h3>
                                <p><?= pc_search_escape($link['description']); ?></p>

                                <span class="pc-search-result-link">
                                    Explore Category
                                    <svg viewBox="0 0 24 24" fill="none"
                                         stroke="currentColor" stroke-width="2"
                                         stroke-linecap="round" stroke-linejoin="round"
                                         aria-hidden="true">
                                        <path d="M5 12h14"></path>
                                        <path d="m12 5 7 7-7 7"></path>
                                    </svg>
                                </span>

                            </a>

                        <?php endforeach; ?>

                    </div>

                <?php endif; ?>

                <!-- CONTACT CTA -->
                <div class="pc-search-cta">

                    <div>
                        <h3>Need help finding a chemical solution?</h3>
                        <p>
                            Share your product requirements or application details
                            with our team to help identify relevant information.
                        </p>
                    </div>

                    <a href="contact.php">
                        Contact Our Team
                        <span aria-hidden="true">&rarr;</span>
                    </a>

                </div>

            </div>

        </div>
    </section>

</main>

<script>
(function () {
    'use strict';

    const tabs = document.querySelectorAll('.pc-search-tab');
    const typeInput = document.getElementById('pcSearchType');
    const searchInput = document.getElementById('pcSearchInput');

    const placeholders = {
        az: 'Enter a product, chemical or application...',
        chemist: 'Search product names or brands...',
        application: 'Search an industry or application...'
    };

    tabs.forEach(function (tab) {
        tab.addEventListener('click', function () {
            const selectedType = tab.getAttribute('data-search-type');

            if (!selectedType || !typeInput) {
                return;
            }

            typeInput.value = selectedType;

            tabs.forEach(function (otherTab) {
                const isActive = otherTab === tab;

                otherTab.classList.toggle('is-active', isActive);
                otherTab.setAttribute(
                    'aria-pressed',
                    isActive ? 'true' : 'false'
                );
            });

            if (searchInput) {
                searchInput.placeholder =
                    placeholders[selectedType] || placeholders.az;
                searchInput.focus();
            }
        });
    });
})();
</script>

<?php
require_once __DIR__ . '/footer.php';
?>
