<?php
/**
 * Search Cases AJAX
 * Real-time case search for autocomplete
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

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

if (!isLoggedIn()) {
    echo json_encode([]);
    exit;
}

$pdo = getDB();
$userId = $_SESSION['user_id'];
$query = $_GET['q'] ?? '';

if (strlen($query) < 2) {
    echo json_encode([]);
    exit;
}

$searchTerm = "%$query%";
$stmt = $pdo->prepare("SELECT id, patient_name, patient_mobile, status 
                      FROM cases 
                      WHERE user_id = ? AND (patient_name LIKE ? OR patient_mobile LIKE ?)
                      ORDER BY created_at DESC
                      LIMIT 20");
$stmt->execute([$userId, $searchTerm, $searchTerm]);
$cases = $stmt->fetchAll();

echo json_encode($cases);
?>