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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

// Get search parameters
$search = $_GET['search'] ?? '';
$page = (int)($_GET['page'] ?? 1);
$limit = 10;
$offset = ($page - 1) * $limit;

// Initialize response
$response = [
    'results' => [],
    'pagination' => [
        'more' => false
    ]
];

if (strlen($search) >= 2) {
    try {
        // Clean and prepare search term
        $search_term = trim($search);
        $search_param = "%$search_term%";
        
        // Search patients by name, phone, or patient number
        $query = "SELECT patient_id, patient_number, first_name, last_name, phone_primary, 
                         date_of_birth, email
                  FROM patients 
                  WHERE is_active = 1 
                    AND (first_name LIKE ? 
                         OR last_name LIKE ? 
                         OR CONCAT(first_name, ' ', last_name) LIKE ?
                         OR patient_number LIKE ? 
                         OR phone_primary LIKE ?)
                  ORDER BY 
                    CASE 
                        WHEN patient_number LIKE CONCAT(?, '%') THEN 1
                        WHEN first_name LIKE CONCAT(?, '%') THEN 2
                        WHEN last_name LIKE CONCAT(?, '%') THEN 3
                        ELSE 4
                    END,
                    first_name ASC, last_name ASC
                  LIMIT ? OFFSET ?";
        
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $stmt->bind_param("ssssssssii", 
            $search_param, $search_param, $search_param, $search_param, $search_param,
            $search_term, $search_term, $search_term,
            $limit, $offset
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Execute failed: " . $stmt->error);
        }
        
        $result = $stmt->get_result();
        
        while ($patient = $result->fetch_assoc()) {
            // Calculate age if date of birth is available
            $age = '';
            if ($patient['date_of_birth']) {
                try {
                    $dob = new DateTime($patient['date_of_birth']);
                    $now = new DateTime();
                    $age_years = $dob->diff($now)->y;
                    $age = $age_years . ' years';
                } catch (Exception $e) {
                    $age = '';
                }
            }
            
            // Format patient display text
            $display_text = htmlspecialchars($patient['first_name'] . ' ' . $patient['last_name']);
            $display_text .= ' (' . htmlspecialchars($patient['patient_number']) . ')';
            
            if ($patient['phone_primary']) {
                $display_text .= ' - ' . htmlspecialchars($patient['phone_primary']);
            }
            
            if ($age) {
                $display_text .= ' - ' . $age;
            }
            
            $response['results'][] = [
                'id' => (int)$patient['patient_id'],
                'text' => $display_text,
                'patient_number' => htmlspecialchars($patient['patient_number']),
                'first_name' => htmlspecialchars($patient['first_name']),
                'last_name' => htmlspecialchars($patient['last_name']),
                'phone' => htmlspecialchars($patient['phone_primary'] ?? ''),
                'email' => htmlspecialchars($patient['email'] ?? ''),
                'age' => $age
            ];
        }
        
        // Check if there are more results
        $count_query = "SELECT COUNT(*) as total 
                       FROM patients 
                       WHERE is_active = 1 
                         AND (first_name LIKE ? 
                              OR last_name LIKE ? 
                              OR CONCAT(first_name, ' ', last_name) LIKE ?
                              OR patient_number LIKE ? 
                              OR phone_primary LIKE ?)";
        
        $count_stmt = $conn->prepare($count_query);
        if (!$count_stmt) {
            throw new Exception("Count prepare failed: " . $conn->error);
        }
        
        $count_stmt->bind_param("sssss", 
            $search_param, $search_param, $search_param, $search_param, $search_param
        );
        
        if (!$count_stmt->execute()) {
            throw new Exception("Count execute failed: " . $count_stmt->error);
        }
        
        $count_result = $count_stmt->get_result();
        $total_count = $count_result->fetch_assoc()['total'];
        
        $response['pagination']['more'] = ($offset + $limit) < $total_count;
        
    } catch (Exception $e) {
        error_log("Patient search error: " . $e->getMessage());
        $response = [
            'results' => [],
            'pagination' => ['more' => false],
            'error' => 'Search failed: ' . $e->getMessage()
        ];
    }
}

header('Content-Type: application/json');
echo json_encode($response);

if (isset($conn)) {
    $conn->close();
}
?>