<?php
/**
 * AJAX Endpoint: Get Doctor's Patients
 * Returns list of patients associated with the logged-in doctor
 * Used for patient selection in lab orders, consultations, etc.
 */

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 {
    $doctor_id = $_SESSION['user_id'];
    
    // 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;

    // Base SQL - get patients associated with this doctor
    $sql = "SELECT DISTINCT
                p.patient_id,
                p.patient_number,
                p.registration_type,
                p.insurance_provider_id,
                p.insurance_number,
                u.full_name,
                u.phone_primary,
                u.phone_secondary,
                u.email,
                u.gender,
                u.date_of_birth,
                p.blood_group,
                p.allergies,
                ip.provider_name as insurance_provider,
                (SELECT MAX(pv.registration_date) 
                 FROM patient_visits pv 
                 WHERE pv.patient_id = p.patient_id) as last_visit_date,
                (SELECT COUNT(*) 
                 FROM consultations c 
                 WHERE c.patient_id = p.patient_id AND c.doctor_id = ?) as consultation_count
            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 p.is_active = 1
            AND (
                -- Patients who have had consultations with this doctor
                EXISTS (
                    SELECT 1 FROM consultations c 
                    WHERE c.patient_id = p.patient_id AND c.doctor_id = ?
                )
                OR
                -- Patients who have had appointments with this doctor
                EXISTS (
                    SELECT 1 FROM appointments a 
                    WHERE a.patient_id = p.patient_id AND a.doctor_id = ?
                )
                OR
                -- Patients who have had prescriptions from this doctor
                EXISTS (
                    SELECT 1 FROM prescriptions pr
                    WHERE pr.patient_id = p.patient_id AND pr.doctor_id = ?
                )
                OR
                -- Patients with recent visits (last 30 days) - accessible by all doctors
                EXISTS (
                    SELECT 1 FROM patient_visits pv 
                    WHERE pv.patient_id = p.patient_id 
                    AND pv.registration_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                )
            )";
    
    // Add search filter if provided (minimum 2 characters)
    $has_search = !empty($search) && strlen($search) >= 2;
    if ($has_search) {
        $sql .= " AND (
            u.full_name LIKE ?
            OR p.patient_number LIKE ?
            OR u.phone_primary LIKE ?
            OR u.phone_secondary LIKE ?
            OR u.email LIKE ?
        )";
    }
    
    // Add ordering
    if ($has_search) {
        $sql .= " 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";
    } else {
        $sql .= " ORDER BY u.full_name ASC";
    }
    
    $sql .= " LIMIT 100";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    
    // Bind parameters based on search
    if ($has_search) {
        $search_param = "%{$search}%";
        $search_start = "{$search}%";
        
        // 4 doctor_id params + 5 search params (WHERE) + 3 search params (ORDER BY) = 12 params
        $stmt->bind_param(
            "iiiisssssssss",
            $doctor_id,      // 1: consultation_count subquery
            $doctor_id,      // 2: consultations EXISTS
            $doctor_id,      // 3: appointments EXISTS
            $doctor_id,      // 4: prescriptions EXISTS
            $search_param,   // 5: full_name LIKE (WHERE)
            $search_param,   // 6: patient_number LIKE (WHERE)
            $search_param,   // 7: phone_primary LIKE (WHERE)
            $search_param,   // 8: phone_secondary LIKE (WHERE)
            $search_param,   // 9: email LIKE (WHERE)
            $search_start,   // 10: patient_number LIKE (ORDER BY)
            $search_start,   // 11: full_name LIKE (ORDER BY)
            $search_start    // 12: phone_primary LIKE (ORDER BY)
        );
    } else {
        // Only 4 doctor_id params
        $stmt->bind_param("iiii", $doctor_id, $doctor_id, $doctor_id, $doctor_id);
    }
    
    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
        $age = '';
        if (!empty($row['date_of_birth'])) {
            try {
                $dob = new DateTime($row['date_of_birth']);
                $now = new DateTime();
                $age = $dob->diff($now)->y;
            } catch (Exception $e) {
                $age = '';
            }
        }
        
        // Format last visit
        $last_visit_display = '';
        if (!empty($row['last_visit_date'])) {
            $last_visit_display = date('d M Y', strtotime($row['last_visit_date']));
        }
        
        // Parse allergies if stored as comma-separated
        $allergies_array = [];
        if (!empty($row['allergies'])) {
            $allergies_array = array_map('trim', explode(',', $row['allergies']));
        }
        
        $response['results'][] = [
            'id' => (int)$row['patient_id'],
            'patient_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'],
            'date_of_birth' => $row['date_of_birth'],
            'blood_group' => $row['blood_group'],
            'allergies' => $row['allergies'],
            'allergies_array' => $allergies_array,
            'registration_type' => $row['registration_type'],
            'insurance_provider_id' => $row['insurance_provider_id'],
            'insurance_provider' => $row['insurance_provider'],
            'insurance_number' => $row['insurance_number'],
            'last_visit_date' => $row['last_visit_date'],
            'last_visit_display' => $last_visit_display,
            'consultation_count' => (int)$row['consultation_count']
        ];
    }
    
    $stmt->close();
    
    if (defined('DEBUG_MODE') && DEBUG_MODE) {
        $response['debug'] = [
            'doctor_id' => $doctor_id,
            'search_term' => $search,
            'results_count' => count($response['results']),
            'has_search' => $has_search
        ];
    }
    
} catch (Exception $e) {
    $response['success'] = false;
    $response['error'] = $e->getMessage();
    $response['results'] = [];
    error_log("Get doctor patients 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();
?>