<?php
session_start();
include 'config.php';

$is_logged_in = isset($_SESSION['user_id']);
$raw_q = isset($_GET['q']) ? trim($_GET['q']) : '';
$query = htmlspecialchars(strip_tags($raw_q), ENT_QUOTES, 'UTF-8');

// ── Group buckets ──
$groups = [
    'submission' => ['label' => 'Submissions',    'icon' => 'fa-file-lines',  'bg' => '#ccfbf1', 'fg' => '#0f766e', 'ibg' => '#f0fdf4', 'items' => []],
    'user'       => ['label' => 'Organizations',  'icon' => 'fa-building',    'bg' => '#dbeafe', 'fg' => '#1d4ed8', 'ibg' => '#eff6ff', 'items' => []],
    'category'   => ['label' => 'Categories',     'icon' => 'fa-folder',      'bg' => '#ede9fe', 'fg' => '#7c3aed', 'ibg' => '#f5f3ff', 'items' => []],
    'content'    => ['label' => 'Articles',       'icon' => 'fa-bookmark',    'bg' => '#e0e7ff', 'fg' => '#3730a3', 'ibg' => '#eef2ff', 'items' => []],
    'page'       => ['label' => 'Pages',          'icon' => 'fa-file',        'bg' => '#f1f5f9', 'fg' => '#475569', 'ibg' => '#f8fafc', 'items' => []],
    'county'     => ['label' => 'Counties',       'icon' => 'fa-location-dot','bg' => '#dcfce7', 'fg' => '#15803d', 'ibg' => '#f0fdf4', 'items' => []],
];

$total = 0;

if ($raw_q !== '') {
    $like = '%' . $conn->real_escape_string($raw_q) . '%';

    // ── 1. Submissions (verified) ──
    $stmt = $conn->prepare(
        "SELECT id, title, org_name, county, contact_person, story, service_chains, created_at
         FROM submissions
         WHERE is_verified = 1
           AND (title LIKE ? OR org_name LIKE ? OR contact_person LIKE ?
                OR county LIKE ? OR story LIKE ?
                OR service_chains LIKE ? OR enabling_pillars LIKE ?
                OR thematic_categories LIKE ?)
         ORDER BY created_at DESC
         LIMIT 30"
    );
    if ($stmt) {
        $stmt->bind_param("ssssssss", $like, $like, $like, $like, $like, $like, $like, $like);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $meta_parts = [];
            if (!empty($row['org_name'])) $meta_parts[] = htmlspecialchars($row['org_name']);
            if (!empty($row['county']))   $meta_parts[] = htmlspecialchars($row['county']);
            if (!empty($row['contact_person'])) $meta_parts[] = htmlspecialchars($row['contact_person']);
            $groups['submission']['items'][] = [
                'title'   => htmlspecialchars($row['title'] ?: $row['org_name'] ?: 'Untitled'),
                'meta'    => implode(' · ', $meta_parts),
                'snippet' => mb_substr(strip_tags($row['story'] ?? ''), 0, 140),
                'url'     => 'view_submission.php?id=' . $row['id'],
                'date'    => date('M j, Y', strtotime($row['created_at'] ?? 'now')),
            ];
        }
        $stmt->close();
    }

    // ── 2. Users / Organisations (verified, public) ──
    $stmt = $conn->prepare(
        "SELECT id, org_name, county, slug, bio
         FROM users
         WHERE role != 'admin'
           AND (IFNULL(is_public,1) = 1)
           AND (org_name LIKE ? OR bio LIKE ? OR county LIKE ? OR email LIKE ?)
         ORDER BY org_name
         LIMIT 20"
    );
    if ($stmt) {
        $stmt->bind_param("ssss", $like, $like, $like, $like);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $link = !empty($row['slug'])
                ? 'profile.php?slug=' . urlencode($row['slug'])
                : 'profile.php?id=' . $row['id'];
            $groups['user']['items'][] = [
                'title'   => htmlspecialchars($row['org_name'] ?: 'Organization'),
                'meta'    => htmlspecialchars($row['county'] ?? ''),
                'snippet' => mb_substr(strip_tags($row['bio'] ?? ''), 0, 140),
                'url'     => $link,
                'date'    => '',
            ];
        }
        $stmt->close();
    }

    // ── 3. Categories ──
    $stmt = $conn->prepare(
        "SELECT id, title, short_desc, icon
         FROM categories
         WHERE title LIKE ? OR short_desc LIKE ? OR full_desc LIKE ?
         ORDER BY title
         LIMIT 15"
    );
    if ($stmt) {
        $stmt->bind_param("sss", $like, $like, $like);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $groups['category']['items'][] = [
                'title'   => htmlspecialchars($row['title']),
                'meta'    => '',
                'snippet' => htmlspecialchars($row['short_desc'] ?? ''),
                'url'     => 'sanitation-reality.php#cat-' . $row['id'],
                'date'    => '',
            ];
        }
        $stmt->close();
    }

    // ── 4. Approved Content ──
    $stmt = $conn->prepare(
        "SELECT c.id, c.title, c.body, cat.title AS cat_title, c.created_at
         FROM content c
         LEFT JOIN categories cat ON c.category_id = cat.id
         WHERE c.status = 'approved'
           AND (c.title LIKE ? OR c.body LIKE ?)
         ORDER BY c.created_at DESC
         LIMIT 20"
    );
    if ($stmt) {
        $stmt->bind_param("ss", $like, $like);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $groups['content']['items'][] = [
                'title'   => htmlspecialchars($row['title']),
                'meta'    => htmlspecialchars($row['cat_title'] ?? ''),
                'snippet' => mb_substr(strip_tags($row['body'] ?? ''), 0, 140),
                'url'     => 'view_content.php?id=' . $row['id'],
                'date'    => date('M j, Y', strtotime($row['created_at'] ?? 'now')),
            ];
        }
        $stmt->close();
    }

    // ── 5. Static Pages ──
    $pages = [
        ['title' => 'Service Chain',      'url' => '/service-chain.php',         'keywords' => 'service chain sanitation containment emptying treatment reuse'],
        ['title' => 'Enabling Pillars',   'url' => '/enabling-pillars.php',       'keywords' => 'enabling pillars policy financing governance regulation'],
        ['title' => 'Submitted Works',    'url' => '/submitted.php',              'keywords' => 'submitted works data submissions dashboard'],
        ['title' => 'Sanitation Reality', 'url' => '/sanitation-reality.php',     'keywords' => 'sanitation reality status barriers challenges'],
        ['title' => 'Barriers',           'url' => '/thematic-repositories.php',  'keywords' => 'barriers thematic repositories challenges obstacles'],
        ['title' => 'Public Directory',   'url' => '/explore.php',                'keywords' => 'public directory explore organisations profiles'],
        ['title' => 'Why SaniBook?',      'url' => '/why-sanibook.php',           'keywords' => 'why sanibook about mission vision purpose'],
        ['title' => 'Grand Unveiling',    'url' => '/grand-unveiling.php',        'keywords' => 'grand unveiling launch event ceremony'],
        ['title' => 'Pricing',            'url' => '/pricing.php',                'keywords' => 'pricing plans packages tokens subscription cost'],
        ['title' => 'Submit Data',        'url' => '/submit-data.php',            'keywords' => 'submit data contribute add story entry'],
        ['title' => 'How to Use SaniBook','url' => '/#how-to-use',               'keywords' => 'how to use guide steps navigate sanibook getting started'],
    ];
    foreach ($pages as $page) {
        if (stripos($page['title'], $raw_q) !== false || stripos($page['keywords'], $raw_q) !== false) {
            $groups['page']['items'][] = [
                'title'   => $page['title'],
                'meta'    => 'Site Page',
                'snippet' => '',
                'url'     => $page['url'],
                'date'    => '',
            ];
        }
    }

    // ── 6. Counties ──
    $all_counties = ["Mombasa","Kwale","Kilifi","Tana River","Lamu","Taita Taveta","Garissa","Wajir","Mandera","Marsabit","Isiolo","Meru","Tharaka-Nithi","Embu","Kitui","Machakos","Makueni","Nyandarua","Nyeri","Kirinyaga","Murang'a","Kiambu","Turkana","West Pokot","Samburu","Trans-Nzoia","Uasin Gishu","Elgeyo-Marakwet","Nandi","Baringo","Laikipia","Nakuru","Narok","Kajiado","Kericho","Bomet","Kakamega","Vihiga","Bungoma","Busia","Siaya","Kisumu","Homa Bay","Migori","Kisii","Nyamira","Nairobi"];
    foreach ($all_counties as $county) {
        if (stripos($county, $raw_q) !== false) {
            $groups['county']['items'][] = [
                'title'   => $county . ' County',
                'meta'    => 'Kenya',
                'snippet' => 'View all verified submissions from ' . $county . ' County.',
                'url'     => 'submitted.php?county=' . urlencode($county),
                'date'    => '',
            ];
        }
    }

    foreach ($groups as $g) $total += count($g['items']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search<?php echo $query ? ' results for "' . $query . '"' : ''; ?> | SaniBook Kenya</title>
    <meta name="description" content="Search SaniBook's database of sanitation knowledge.">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700;900&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
    <link rel="icon" href="images/saniBook logo.png" type="image/png">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .font-heading { font-family: 'Montserrat', sans-serif; }
        .result-card {
            background: #fff;
            border-radius: 14px;
            border: 1px solid #e2e8f0;
            box-shadow: 0 1px 4px rgba(15,23,42,0.06);
            display: flex;
            flex-direction: column;
            transition: box-shadow 0.2s, transform 0.2s;
            overflow: hidden;
        }
        .result-card:hover {
            box-shadow: 0 8px 28px rgba(15,23,42,0.11);
            transform: translateY(-2px);
        }
        .rc-icon-wrap {
            width: 34px; height: 34px;
            border-radius: 9px;
            display: flex; align-items: center; justify-content: center;
            font-size: 0.8rem;
            flex-shrink: 0;
        }
        .rc-badge {
            display: inline-flex; align-items: center;
            font-size: 0.6rem; font-weight: 800;
            padding: 2px 7px; border-radius: 999px;
            letter-spacing: 0.05em;
            text-transform: uppercase;
        }
        /* Sticky section nav */
        .section-pill {
            display: inline-flex; align-items: center; gap: 6px;
            padding: 5px 14px; border-radius: 999px;
            font-size: 0.75rem; font-weight: 700;
            cursor: pointer; transition: background 0.15s, color 0.15s;
            white-space: nowrap;
        }
    </style>
</head>
<body class="bg-slate-50 text-slate-900">

    <?php include 'navbar.php'; ?>

    <!-- Search Hero -->
    <section class="bg-gradient-to-br from-blue-900 via-blue-800 to-blue-700 py-14">
        <div class="max-w-4xl mx-auto px-4 text-center">
            <h1 class="text-3xl md:text-4xl font-heading font-bold text-white mb-6">
                <i class="fa-solid fa-magnifying-glass mr-2"></i>Search SaniBook
            </h1>
            <form action="search.php" method="GET" class="max-w-2xl mx-auto">
                <div class="relative">
                    <input type="text" name="q" value="<?php echo $query; ?>"
                        placeholder="Search organizations, counties, content, submissions..."
                        class="w-full pl-12 pr-28 py-4 text-base bg-white/95 rounded-2xl shadow-xl border-0 focus:outline-none focus:ring-4 focus:ring-blue-300 transition-all"
                        autofocus>
                    <i class="fa-solid fa-search absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 text-base"></i>
                    <button type="submit"
                        class="absolute right-2 top-1/2 -translate-y-1/2 px-6 py-2.5 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 transition-colors text-sm">
                        Search
                    </button>
                </div>
            </form>
        </div>
    </section>

    <!-- Results -->
    <div class="max-w-7xl mx-auto px-4 py-10">

        <?php if ($raw_q === ''): ?>
            <!-- Empty state -->
            <div class="text-center py-24">
                <i class="fa-solid fa-magnifying-glass text-6xl text-slate-200 mb-5 block"></i>
                <p class="text-xl text-slate-400 font-medium">Search across submissions, organizations, categories, counties and more.</p>
            </div>

        <?php elseif ($total === 0): ?>
            <!-- No results -->
            <div class="text-center py-24">
                <i class="fa-solid fa-circle-exclamation text-6xl text-slate-200 mb-5 block"></i>
                <p class="text-xl text-slate-500 mb-2">No results for "<strong><?php echo $query; ?></strong>"</p>
                <p class="text-sm text-slate-400">Try different keywords or check your spelling.</p>
            </div>

        <?php else: ?>

            <!-- Summary + filter pills -->
            <div class="mb-8">
                <p class="text-sm text-slate-500 mb-4">
                    <strong><?php echo $total; ?></strong> results for "<strong><?php echo $query; ?></strong>"
                    — grouped by type
                </p>
                <!-- Quick-jump pills -->
                <div class="flex flex-wrap gap-2">
                    <?php foreach ($groups as $key => $g):
                        if (empty($g['items'])) continue;
                        $count = count($g['items']);
                    ?>
                    <a href="#group-<?php echo $key; ?>"
                        class="section-pill border border-slate-200 bg-white text-slate-600 hover:bg-slate-100">
                        <i class="fa-solid <?php echo $g['icon']; ?>" style="color:<?php echo $g['fg']; ?>"></i>
                        <?php echo $g['label']; ?>
                        <span class="ml-1 px-1.5 py-0 rounded-full text-white text-[10px] font-bold" style="background:<?php echo $g['fg']; ?>"><?php echo $count; ?></span>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Grouped sections -->
            <?php foreach ($groups as $key => $g):
                if (empty($g['items'])) continue;
            ?>
            <section id="group-<?php echo $key; ?>" class="mb-12 scroll-mt-20">

                <!-- Section header -->
                <div class="flex items-center gap-3 mb-5">
                    <span class="rc-icon-wrap" style="background:<?php echo $g['ibg']; ?>">
                        <i class="fa-solid <?php echo $g['icon']; ?>" style="color:<?php echo $g['fg']; ?>; font-size:0.9rem;"></i>
                    </span>
                    <h2 class="font-heading font-bold text-lg text-slate-800"><?php echo $g['label']; ?></h2>
                    <span class="rc-badge" style="background:<?php echo $g['bg']; ?>;color:<?php echo $g['fg']; ?>">
                        <?php echo count($g['items']); ?> found
                    </span>
                    <div class="flex-1 h-px bg-slate-100"></div>
                </div>

                <!-- Cards grid -->
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
                    <?php foreach ($g['items'] as $item): ?>
                    <div class="result-card">
                        <div class="p-5 flex flex-col flex-1">
                            <!-- Badge row -->
                            <div class="flex items-center justify-between gap-2 mb-3">
                                <div class="flex items-center gap-2">
                                    <span class="rc-icon-wrap" style="background:<?php echo $g['ibg']; ?>">
                                        <i class="fa-solid <?php echo $g['icon']; ?>" style="color:<?php echo $g['fg']; ?>"></i>
                                    </span>
                                    <?php if (!empty($item['meta'])): ?>
                                    <span class="text-xs text-slate-400 truncate max-w-[160px]"><?php echo $item['meta']; ?></span>
                                    <?php endif; ?>
                                </div>
                                <?php if (!empty($item['date'])): ?>
                                <span class="text-xs text-slate-300 flex-shrink-0"><?php echo $item['date']; ?></span>
                                <?php endif; ?>
                            </div>

                            <!-- Title -->
                            <h3 class="font-bold text-slate-900 text-base mb-2 leading-snug line-clamp-2">
                                <?php echo $item['title']; ?>
                            </h3>

                            <!-- Snippet -->
                            <?php if (!empty($item['snippet'])): ?>
                            <p class="text-sm text-slate-500 line-clamp-3 flex-1 mb-4">
                                <?php echo htmlspecialchars($item['snippet']); ?>…
                            </p>
                            <?php else: ?>
                            <div class="flex-1"></div>
                            <?php endif; ?>

                            <!-- CTA -->
                            <div class="pt-3 border-t border-slate-100">
                                <a href="<?php echo $item['url']; ?>"
                                    class="inline-flex items-center gap-1.5 text-sm font-semibold hover:underline"
                                    style="color:<?php echo $g['fg']; ?>">
                                    View <i class="fa-solid fa-arrow-right text-xs"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

            </section>
            <?php endforeach; ?>

        <?php endif; ?>

    </div>

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

</body>
</html>