<?php
include "core/autoload.php";
include "core/app/model/PatientData.php";

if(isset($_GET['term'])) {
    try {
        $term = $_GET['term'];
        
        $sql = "SELECT id, ci, name, lastname FROM pacient WHERE ci LIKE \"%" . $term . "%\" LIMIT 5";
        $query = Executor::doit($sql);
        $patients = array();
        
        if($query && isset($query[0])) {
            $data = Model::many($query[0], new PatientData());
            
            foreach($data as $patient) {
                $patients[] = array(
                    'id' => $patient->id,
                    'label' => $patient->ci . ' - ' . $patient->name . ' ' . $patient->lastname,
                    'value' => $patient->ci,
                    'name' => $patient->name,
                    'lastname' => $patient->lastname
                );
            }
        }
        
        header('Content-Type: application/json');
        echo json_encode($patients);
    } catch (Exception $e) {
        header('Content-Type: application/json');
        echo json_encode(['error' => $e->getMessage()]);
    }
}