<?php
header('Content-Type: application/json');
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['patients' => [], 'has_more' => false]);
    exit();
}

$search = $_GET['search'] ?? '';
$page = $_GET['page'] ?? 1;
$limit = 20;
$offset = ($page - 1) * $limit;

$patients = [];
$has_more = false;

if (strlen($search) >= 2) {
    $search_term = "%{$search}%";
    
    $sql = "SELECT 
        p.patient_id,
        p.patient_number,
        u.full_name,
        u.phone_number,
        u.email,
        u.date_of_birth,
        TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age,
        u.gender,
        p.registration_type,
        p.insurance_provider_id,
        ins.provider_name as insurance_name
    FROM patients p
    INNER JOIN users u ON p.user_id = u.user_id
    LEFT JOIN insurance_providers ins ON p.insurance_provider_id = ins.provider_id
    WHERE (u.full_name LIKE ? OR p.patient_number LIKE ? OR u.phone_number LIKE ?)
    AND p.is_active = 1
    ORDER BY u.full_name
    LIMIT ? OFFSET ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssii", $search_term, $search_term, $search_term, $limit, $offset);
    $stmt->execute();
    $result = $stmt->get_result();
    
    while ($row = $result->fetch_assoc()) {
        $patients[] = $row;
    }
    
    // Check if there are more results
    $count_sql = "SELECT COUNT(*) as total
                 FROM patients p
                 INNER JOIN users u ON p.user_id = u.user_id
                 WHERE (u.full_name LIKE ? OR p.patient_number LIKE ? OR u.phone_number LIKE ?)
                 AND p.is_active = 1";
    
    $count_stmt = $conn->prepare($count_sql);
    $count_stmt->bind_param("sss", $search_term, $search_term, $search_term);
    $count_stmt->execute();
    $count_result = $count_stmt->get_result()->fetch_assoc();
    
    $has_more = ($offset + $limit) < $count_result['total'];
}

echo json_encode([
    'patients' => $patients,
    'has_more' => $has_more
]);

$conn->close();
?>