<?php
session_start();
require_once 'layouts/dbconn.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode([]);
    exit();
}

$search = $_GET['search'] ?? '';

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

$search_param = '%' . $conn->real_escape_string($search) . '%';

// Search patients by name, patient number, phone, or national ID
$sql = "SELECT 
    p.patient_id,
    p.patient_number,
    u.full_name,
    u.phone_primary,
    u.email,
    u.gender,
    u.date_of_birth,
    TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age,
    p.registration_type,
    p.insurance_number,
    p.policy_number,
    ip.provider_name as insurance_provider,
    p.employer,
    u.national_id,
    u.is_active
FROM patients p
INNER JOIN users u ON p.user_id = u.user_id
LEFT JOIN insurance_providers ip ON p.insurance_provider_id = ip.provider_id
WHERE u.is_active = 1
AND (
    u.full_name LIKE ? OR
    p.patient_number LIKE ? OR
    u.phone_primary LIKE ? OR
    u.national_id LIKE ? OR
    p.insurance_number LIKE ?
)
ORDER BY u.full_name
LIMIT 20";

$stmt = $conn->prepare($sql);
$stmt->bind_param('sssss', $search_param, $search_param, $search_param, $search_param, $search_param);
$stmt->execute();
$result = $stmt->get_result();

$patients = [];
while ($row = $result->fetch_assoc()) {
    $patients[] = [
        'patient_id' => $row['patient_id'],
        'patient_number' => $row['patient_number'],
        'full_name' => $row['full_name'],
        'phone_primary' => $row['phone_primary'],
        'email' => $row['email'],
        'gender' => $row['gender'],
        'age' => $row['age'],
        'registration_type' => $row['registration_type'],
        'insurance_number' => $row['insurance_number'],
        'policy_number' => $row['policy_number'],
        'insurance_provider' => $row['insurance_provider'],
        'employer' => $row['employer'],
        'national_id' => $row['national_id']
    ];
}

echo json_encode($patients);
$stmt->close();
$conn->close();
?>