<?php
/**
 * api/search.php — Sitewide AJAX search endpoint for SaniBook
 * Returns JSON results grouped by: submissions, users, categories, content, pages, counties
 * Searches BOTH submitted (pending) and approved data
 * Version: 1.1.0
 *
 * Changelog:
 * 1.1.0 - Expanded search to cover all site data: submissions (all statuses),
 *          users/organisations, categories, approved content, static pages, counties.
 *          Returns grouped results for rich navbar suggestions.
 * 1.0.0 - Initial release, only searched verified submissions + orgs + counties.
 */
header('Content-Type: application/json');
session_start();
include __DIR__ . '/../config.php';

$q = trim($_GET['q'] ?? '');
if (mb_strlen($q) < 2) {
    echo json_encode(['results' => []]);
    exit;
}

$like = '%' . $q . '%';
$results = [];

// ── 1. Submissions (approved/verified only) — max 6 ──
$stmt = $conn->prepare(
    "SELECT id, title, org_name, county, contact_person,
            service_chains, enabling_pillars, thematic_categories,
            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 6"
);
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()) {
        $results[] = [
            'type'    => 'submission',
            'id'      => (int) $row['id'],
            'title'   => htmlspecialchars($row['title'] ?: $row['org_name'] ?: 'Untitled'),
            'sub'     => trim(htmlspecialchars(($row['county'] ?? '') . ($row['org_name'] ? ' · ' . $row['org_name'] : ''))),
            'icon'    => 'fa-file-lines',
            'color'   => 'text-teal-600',
            'url'     => '/view_submission.php?id=' . $row['id'],
        ];
    }
    $stmt->close();
}

// ── 2. Users / Organisations — max 4 ──
$stmt = $conn->prepare(
    "SELECT id, org_name, county, slug, bio
     FROM users
     WHERE role != 'admin'
       AND (org_name LIKE ? OR county LIKE ? OR bio LIKE ? OR email LIKE ?)
     ORDER BY org_name
     LIMIT 4"
);
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'];
        $results[] = [
            'type'  => 'user',
            'id'    => (int) $row['id'],
            'title' => htmlspecialchars($row['org_name'] ?: 'User'),
            'sub'   => htmlspecialchars($row['county'] ?? ''),
            'icon'  => 'fa-building',
            'color' => 'text-blue-600',
            'url'   => $link,
        ];
    }
    $stmt->close();
}

// ── 3. Categories — max 4 ──
$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 4"
);
if ($stmt) {
    $stmt->bind_param("sss", $like, $like, $like);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $results[] = [
            'type'  => 'category',
            'id'    => (int) $row['id'],
            'title' => htmlspecialchars($row['title']),
            'sub'   => htmlspecialchars($row['short_desc'] ?? ''),
            'icon'  => $row['icon'] ?? 'fa-folder',
            'color' => 'text-purple-600',
            'url'   => '/sanitation-reality.php#cat-' . $row['id'],
        ];
    }
    $stmt->close();
}

// ── 4. Approved Content — max 4 ──
$stmt = $conn->prepare(
    "SELECT c.id, c.title, cat.title AS cat_title
     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 4"
);
if ($stmt) {
    $stmt->bind_param("ss", $like, $like);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $results[] = [
            'type'  => 'content',
            'id'    => (int) $row['id'],
            'title' => htmlspecialchars($row['title']),
            'sub'   => htmlspecialchars($row['cat_title'] ?? 'Content'),
            'icon'  => 'fa-bookmark',
            'color' => 'text-indigo-600',
            'url'   => '/view_content.php?id=' . $row['id'],
        ];
    }
    $stmt->close();
}

// ── 5. Static Pages — always available, filtered client-style ──
$pages = [
    ['title' => 'Service Chain',          'url' => '/service-chain.php',          'icon' => 'fa-link',          'keywords' => 'service chain sanitation containment emptying treatment reuse'],
    ['title' => 'Enabling Pillars',       'url' => '/enabling-pillars.php',       'icon' => 'fa-columns',       'keywords' => 'enabling pillars policy financing governance regulation'],
    ['title' => 'Submitted Works',        'url' => '/submitted.php',              'icon' => 'fa-file-lines',    'keywords' => 'submitted works data submissions dashboard'],
    ['title' => 'Sanitation Reality',     'url' => '/sanitation-reality.php',     'icon' => 'fa-chart-bar',     'keywords' => 'sanitation reality status barriers challenges'],
    ['title' => 'Barriers',              'url' => '/thematic-repositories.php',  'icon' => 'fa-shield',        'keywords' => 'barriers thematic repositories challenges obstacles'],
    ['title' => 'Public Directory',       'url' => '/explore.php',                'icon' => 'fa-users',         'keywords' => 'public directory explore organisations organisations profiles'],
    ['title' => 'Why SaniBook',           'url' => '/why-sanibook.php',           'icon' => 'fa-circle-info',   'keywords' => 'why sanibook about mission vision'],
    ['title' => 'Grand Unveiling',        'url' => '/grand-unveiling.php',        'icon' => 'fa-calendar-star', 'keywords' => 'grand unveiling launch event ceremony'],
    ['title' => 'Pricing',               'url' => '/pricing.php',                'icon' => 'fa-tag',           'keywords' => 'pricing plans packages tokens subscription cost'],
    ['title' => 'Submit Data',            'url' => '/submit-data.php',            'icon' => 'fa-pen',           'keywords' => 'submit data contribute add story entry'],
];

foreach ($pages as $page) {
    if (stripos($page['title'], $q) !== false || stripos($page['keywords'], $q) !== false) {
        $results[] = [
            'type'  => 'page',
            'id'    => 0,
            'title' => $page['title'],
            'sub'   => 'Page',
            'icon'  => $page['icon'],
            'color' => 'text-slate-600',
            'url'   => $page['url'],
        ];
    }
}

// ── 6. Counties — match against known 47 Kenyan counties, show count ──
$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"];
$county_matches = 0;
foreach ($all_counties as $county) {
    if ($county_matches >= 3) break;
    if (stripos($county, $q) !== false) {
        $results[] = [
            'type'  => 'county',
            'id'    => 0,
            'title' => $county,
            'sub'   => 'County',
            'icon'  => 'fa-location-dot',
            'color' => 'text-green-600',
            'url'   => '/submitted.php?county=' . urlencode($county),
        ];
        $county_matches++;
    }
}

// ── 7. Service chain nodes ──
$chain_nodes = [
    ['title' => 'Containment',        'keywords' => 'containment toilet latrine pit septic'],
    ['title' => 'Emptying & Transport','keywords' => 'emptying transport exhauster vacuum truck desludging'],
    ['title' => 'Treatment',           'keywords' => 'treatment plant processing wastewater sewage'],
    ['title' => 'Reuse & Disposal',    'keywords' => 'reuse disposal compost biogas fertilizer briquettes'],
];
foreach ($chain_nodes as $node) {
    if (stripos($node['title'], $q) !== false || stripos($node['keywords'], $q) !== false) {
        $results[] = [
            'type'  => 'page',
            'id'    => 0,
            'title' => $node['title'] . ' (Service Chain)',
            'sub'   => 'Service Chain Node',
            'icon'  => 'fa-link',
            'color' => 'text-teal-600',
            'url'   => '/service-chain.php',
        ];
    }
}

echo json_encode(['results' => $results]);
