<?php
require './config.php';
require './functions.php';

$connect = connect($database);

header('Content-Type: application/json');

$query = isset($_GET['q']) ? trim($_GET['q']) : '';

if (empty($query) || strlen($query) < 2) {
    echo json_encode(['stores' => [], 'categories' => []]);
    exit;
}

$searchTerm = '%' . $query . '%';

// Search stores with coupon count
$storeQuery = $connect->prepare("
    SELECT s.store_id, s.store_title, s.store_slug, s.store_image, 
           COUNT(c.coupon_id) as coupon_count
    FROM stores s
    LEFT JOIN coupons c ON s.store_id = c.coupon_store AND c.coupon_status = 1
    WHERE s.store_status = 1 
    AND s.store_title LIKE :query
    GROUP BY s.store_id
    ORDER BY s.store_title ASC
    LIMIT 5
");
$storeQuery->execute([':query' => $searchTerm]);
$stores = $storeQuery->fetchAll(PDO::FETCH_ASSOC);

// Search categories with store count
$categoryQuery = $connect->prepare("
    SELECT cat.category_id, cat.category_title, cat.category_slug,
           COUNT(DISTINCT s.store_id) as store_count
    FROM categories cat
    LEFT JOIN stores s ON cat.category_id = s.store_category AND s.store_status = 1
    WHERE cat.category_status = 1 
    AND cat.category_title LIKE :query
    GROUP BY cat.category_id
    ORDER BY cat.category_title ASC
    LIMIT 5
");
$categoryQuery->execute([':query' => $searchTerm]);
$categories = $categoryQuery->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'stores' => $stores,
    'categories' => $categories
]);
?>
