<?php
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');

$action = $_GET['action'] ?? '';
$pdo = db();

try {
    switch ($action) {
        case 'search':
            $q = $_GET['q'] ?? '';
            
            if (empty($q)) {
                echo json_encode(['results' => []]);
                exit;
            }
            
            // Search by name, phone or id (patient number)
            $sql = "SELECT id, name, phone, civil_id FROM patients WHERE name LIKE ? OR phone LIKE ? OR civil_id LIKE ? OR id = ? LIMIT 20";
            $stmt = $pdo->prepare($sql);
            $term = "%$q%";
            $id_term = intval($q); // for exact match on patient number
            $stmt->execute([$term, $term, $term, $id_term]);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Format results for select2
            $formatted_results = array_map(function($p) {
                $patient_number = sprintf('%06d', $p['id']);
                $display_text = $patient_number . ' - ' . $p['name'];
                if (!empty($p['phone'])) {
                    $display_text .= ' - ' . $p['phone'];
                }
                return [
                    'id' => $p['id'],
                    'text' => $display_text,
                    'name' => $p['name'],
                    'phone' => $p['phone']
                ];
            }, $results);
            
            echo json_encode(['results' => $formatted_results]);
            break;

        default:
            http_response_code(400);
            echo json_encode(['error' => 'Invalid action']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
