<?php
/**
 * AJAX Endpoint: Get Patient Details
 * Retrieves comprehensive details for a single patient
 * Used for populating patient information in forms
 */

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',
        'patient' => null
    ]);
    exit();
}

// Initialize response
$response = [
    'success' => true,
    'patient' => null,
    'recent_visits' => [],
    'debug' => []
];

try {
    // Get patient_id - support both GET and POST
    $patient_id = 0;
    if (isset($_POST['patient_id'])) {
        $patient_id = (int)$_POST['patient_id'];
    } elseif (isset($_GET['patient_id'])) {
        $patient_id = (int)$_GET['patient_id'];
    } elseif (isset($_POST['id'])) {
        $patient_id = (int)$_POST['id'];
    } elseif (isset($_GET['id'])) {
        $patient_id = (int)$_GET['id'];
    }
    
    if ($patient_id <= 0) {
        throw new Exception("Invalid patient ID");
    }
    
    // Get comprehensive patient details
    $sql = "SELECT 
                p.*,
                u.full_name,
                u.phone_primary,
                u.phone_secondary,
                u.email,
                u.gender,
                u.date_of_birth,
                u.national_id,
                u.address,
                u.emergency_contact_name,
                u.emergency_contact_phone,
                u.profile_picture,
                u.is_active,
                ip.provider_name as insurance_provider,
                ip.phone as insurance_phone,
                ip.email as insurance_email,
                (SELECT MAX(pv.registration_date) 
                 FROM patient_visits pv 
                 WHERE pv.patient_id = p.patient_id) as last_visit_date,
                (SELECT COUNT(*) 
                 FROM patient_visits pv 
                 WHERE pv.patient_id = p.patient_id) as total_visits,
                (SELECT COUNT(*) 
                 FROM consultations c 
                 WHERE c.patient_id = p.patient_id) as total_consultations,
                (SELECT COUNT(*) 
                 FROM lab_orders lo 
                 WHERE lo.patient_id = p.patient_id) as total_lab_orders,
                (SELECT COUNT(*) 
                 FROM prescriptions pr 
                 WHERE pr.patient_id = p.patient_id) as total_prescriptions
            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.patient_id = ?";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    
    $stmt->bind_param("i", $patient_id);
    
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }
    
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception("Patient not found");
    }
    
    $patient = $result->fetch_assoc();
    $stmt->close();
    
    // Calculate age
    $age = '';
    if (!empty($patient['date_of_birth'])) {
        try {
            $dob = new DateTime($patient['date_of_birth']);
            $now = new DateTime();
            $age = $dob->diff($now)->y;
        } catch (Exception $e) {
            $age = '';
        }
    }
    
    // Format last visit
    $last_visit_display = '';
    if (!empty($patient['last_visit_date'])) {
        $last_visit_display = date('d M Y', strtotime($patient['last_visit_date']));
    }
    
    // Parse allergies
    $allergies_array = [];
    if (!empty($patient['allergies'])) {
        $allergies_array = array_map('trim', explode(',', $patient['allergies']));
    }
    
    // Parse chronic conditions
    $conditions_array = [];
    if (!empty($patient['chronic_conditions'])) {
        $conditions_array = array_map('trim', explode(',', $patient['chronic_conditions']));
    }
    
    // Build patient data response
    $response['patient'] = [
        'patient_id' => (int)$patient['patient_id'],
        'patient_number' => $patient['patient_number'],
        'user_id' => (int)$patient['user_id'],
        'full_name' => $patient['full_name'],
        'phone_primary' => $patient['phone_primary'],
        'phone_secondary' => $patient['phone_secondary'],
        'email' => $patient['email'],
        'gender' => $patient['gender'],
        'date_of_birth' => $patient['date_of_birth'],
        'age' => $age,
        'national_id' => $patient['national_id'],
        'address' => $patient['address'],
        'emergency_contact_name' => $patient['emergency_contact_name'],
        'emergency_contact_phone' => $patient['emergency_contact_phone'],
        'profile_picture' => $patient['profile_picture'],
        'is_active' => (int)$patient['is_active'],
        
        // Registration details
        'registration_type' => $patient['registration_type'],
        'registration_date' => $patient['registration_date'],
        
        // Insurance details
        'insurance_provider_id' => $patient['insurance_provider_id'],
        'insurance_provider' => $patient['insurance_provider'],
        'insurance_phone' => $patient['insurance_phone'],
        'insurance_email' => $patient['insurance_email'],
        'insurance_number' => $patient['insurance_number'],
        'policy_number' => $patient['policy_number'],
        
        // Employment details
        'employer' => $patient['employer'],
        'occupation' => $patient['occupation'],
        'marital_status' => $patient['marital_status'],
        
        // Medical details
        'blood_group' => $patient['blood_group'],
        'allergies' => $patient['allergies'],
        'allergies_array' => $allergies_array,
        'chronic_conditions' => $patient['chronic_conditions'],
        'chronic_conditions_array' => $conditions_array,
        'current_medications' => $patient['current_medications'],
        'family_medical_history' => $patient['family_medical_history'],
        'ent_history' => $patient['ent_history'],
        'preferred_language' => $patient['preferred_language'],
        
        // Statistics
        'last_visit_date' => $patient['last_visit_date'],
        'last_visit_display' => $last_visit_display,
        'total_visits' => (int)$patient['total_visits'],
        'total_consultations' => (int)$patient['total_consultations'],
        'total_lab_orders' => (int)$patient['total_lab_orders'],
        'total_prescriptions' => (int)$patient['total_prescriptions']
    ];
    
    // Get recent visits
    $visits_sql = "SELECT 
                      visit_id,
                      visit_number,
                      visit_type,
                      visit_source,
                      registration_type,
                      registration_date,
                      status,
                      chief_complaint,
                      total_amount,
                      balance
                   FROM patient_visits
                   WHERE patient_id = ?
                   ORDER BY registration_date DESC
                   LIMIT 5";
    
    $visits_stmt = $conn->prepare($visits_sql);
    if ($visits_stmt) {
        $visits_stmt->bind_param("i", $patient_id);
        
        if ($visits_stmt->execute()) {
            $visits_result = $visits_stmt->get_result();
            
            while ($visit = $visits_result->fetch_assoc()) {
                $response['recent_visits'][] = [
                    'visit_id' => (int)$visit['visit_id'],
                    'visit_number' => $visit['visit_number'],
                    'visit_type' => $visit['visit_type'],
                    'visit_source' => $visit['visit_source'],
                    'registration_type' => $visit['registration_type'],
                    'registration_date' => $visit['registration_date'],
                    'registration_date_formatted' => date('d M Y', strtotime($visit['registration_date'])),
                    'status' => $visit['status'],
                    'chief_complaint' => $visit['chief_complaint'],
                    'total_amount' => $visit['total_amount'],
                    'balance' => $visit['balance']
                ];
            }
        }
        $visits_stmt->close();
    }
    
    if (defined('DEBUG_MODE') && DEBUG_MODE) {
        $response['debug'] = [
            'patient_id' => $patient_id,
            'visits_count' => count($response['recent_visits'])
        ];
    }
    
} catch (Exception $e) {
    $response['success'] = false;
    $response['error'] = $e->getMessage();
    $response['patient'] = null;
    error_log("Get patient details 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();
?>