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

// Ensure user is authenticated
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'error' => 'Unauthorized access',
        'results' => []
    ]);
    exit();
}

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

try {
    // Get search term - support multiple parameter names for flexibility
    $search = '';
    if (isset($_POST['q'])) {
        $search = trim($_POST['q']);
    } elseif (isset($_GET['q'])) {
        $search = trim($_GET['q']);
    } elseif (isset($_POST['query'])) {
        $search = trim($_POST['query']);
    } elseif (isset($_GET['query'])) {
        $search = trim($_GET['query']);
    } elseif (isset($_POST['search'])) {
        $search = trim($_POST['search']);
    } elseif (isset($_GET['search'])) {
        $search = trim($_GET['search']);
    }

    // Require at least 2 characters for search
    if (strlen($search) < 2) {
        echo json_encode($response);
        exit();
    }

    $search_param = "%{$search}%";
    $search_start = "{$search}%";

    // Search patients with user information
    $sql = "SELECT 
                p.patient_id,
                p.patient_number,
                u.full_name,
                u.email,
                u.phone_primary,
                u.phone_secondary,
                u.date_of_birth,
                u.gender,
                p.blood_group,
                p.registration_type,
                p.created_at
            FROM patients p
            INNER JOIN users u ON p.user_id = u.user_id
            WHERE p.is_active = 1
              AND (
                    u.full_name LIKE ?
                 OR p.patient_number LIKE ?
                 OR u.phone_primary LIKE ?
                 OR u.phone_secondary LIKE ?
                 OR u.email LIKE ?
                )
            ORDER BY 
                CASE 
                    WHEN p.patient_number LIKE ? THEN 1
                    WHEN u.full_name LIKE ? THEN 2
                    WHEN u.phone_primary LIKE ? THEN 3
                    ELSE 4
                END,
                u.full_name ASC
            LIMIT 20";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }

    // Bind 8 parameters (5 for WHERE clause, 3 for ORDER BY)
    $stmt->bind_param(
        "ssssssss",
        $search_param,  // full_name LIKE
        $search_param,  // patient_number LIKE
        $search_param,  // phone_primary LIKE
        $search_param,  // phone_secondary LIKE
        $search_param,  // email LIKE
        $search_start,  // ORDER BY patient_number
        $search_start,  // ORDER BY full_name
        $search_start   // ORDER BY phone_primary
    );

    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        // Calculate age
        $age = '';
        $age_display = '';
        if (!empty($row['date_of_birth'])) {
            try {
                $dob = new DateTime($row['date_of_birth']);
                $now = new DateTime();
                $age_years = $dob->diff($now)->y;
                $age = $age_years;
                $age_display = $age_years . ' yrs';
            } catch (Exception $e) {
                $age_display = 'N/A';
            }
        } else {
            $age_display = 'N/A';
        }

        // Format display text for Select2
        $display_text = $row['patient_number'] . ' - ' . $row['full_name'];
        $display_text .= ' (' . $age_display . ', ' . ($row['gender'] ?: 'N/A') . ')';
        
        if ($row['phone_primary']) {
            $display_text .= ' - ' . $row['phone_primary'];
        }

        // Add to results array in Select2 format
        $response['results'][] = [
            'id' => (int)$row['patient_id'],
            'text' => $display_text,
            'patient_id' => (int)$row['patient_id'],
            'patient_number' => $row['patient_number'],
            'full_name' => $row['full_name'],
            'phone_primary' => $row['phone_primary'],
            'phone_secondary' => $row['phone_secondary'],
            'email' => $row['email'],
            'age' => $age,
            'age_display' => $age_display,
            'gender' => $row['gender'],
            'blood_group' => $row['blood_group'],
            'registration_type' => $row['registration_type'],
            'date_of_birth' => $row['date_of_birth']
        ];
    }

    $stmt->close();

} catch (Exception $e) {
    $response['success'] = false;
    $response['error'] = $e->getMessage();
    $response['results'] = [];
    error_log("Patient search error: " . $e->getMessage());
}

// Close connection
if (isset($conn)) {
    $conn->close();
}

// Output JSON
echo json_encode($response);
exit();
?>