<?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' => [],
    'total' => 0,
    'query' => '',
    'debug' => []
];

try {
    // Get search term - support both GET and POST, and both 'search' and 'query' parameters
    $search = '';
    if (isset($_POST['query'])) {
        $search = trim($_POST['query']);
    } elseif (isset($_POST['search'])) {
        $search = trim($_POST['search']);
    } elseif (isset($_GET['query'])) {
        $search = trim($_GET['query']);
    } elseif (isset($_GET['search'])) {
        $search = trim($_GET['search']);
    }
    $response['query'] = $search;

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

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

    // Updated SQL to join users and patients
    $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);
    }

    // FIXED: Exactly 8 parameters (5 for WHERE, 3 for ORDER BY)
    $stmt->bind_param(
        "ssssssss",  // 8 's' for strings
        $search_param,  // 1: full_name LIKE (WHERE)
        $search_param,  // 2: patient_number LIKE (WHERE)
        $search_param,  // 3: phone_primary LIKE (WHERE)
        $search_param,  // 4: phone_secondary LIKE (WHERE)
        $search_param,  // 5: email LIKE (WHERE)
        $search_start,  // 6: patient_number LIKE (ORDER BY)
        $search_start,  // 7: full_name LIKE (ORDER BY)
        $search_start   // 8: phone_primary LIKE (ORDER BY)
    );

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

    $result = $stmt->get_result();
    $response['total'] = $result->num_rows;

    while ($row = $result->fetch_assoc()) {
        // Calculate age - return just the number for Select2 compatibility
        $age = '';
        if (!empty($row['date_of_birth'])) {
            try {
                $dob = new DateTime($row['date_of_birth']);
                $now = new DateTime();
                $age = $dob->diff($now)->y; // Just the number, not "X years"
            } catch (Exception $e) {
                $age = '';
            }
        }

        $response['results'][] = [
            'id' => (int)$row['patient_id'],
            'patient_number' => $row['patient_number'],
            'full_name' => $row['full_name'],
            'phone' => $row['phone_primary'] ?: $row['phone_secondary'],
            'phone_primary' => $row['phone_primary'],
            'phone_secondary' => $row['phone_secondary'],
            'email' => $row['email'],
            'age' => $age,
            'gender' => $row['gender'],
            'blood_group' => $row['blood_group'],
            'registration_type' => $row['registration_type'],
            'date_of_birth' => $row['date_of_birth'],
            'created_at' => $row['created_at']
        ];
    }

    $stmt->close();

    if (defined('DEBUG_MODE') && DEBUG_MODE) {
        $response['debug'] = [
            'search_term' => $search,
            'results_count' => count($response['results']),
            'sql' => $sql
        ];
    }

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

    if (defined('DEBUG_MODE') && DEBUG_MODE) {
        $response['debug'] = [
            'error_message' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ];
    }
}

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

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