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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Get patient ID from request
$patient_id = $_GET['patient_id'] ?? null;

if (!$patient_id || !is_numeric($patient_id)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid patient ID']);
    exit();
}

try {
    // Get patient visits
    $query = "SELECT v.visit_id, v.visit_number, v.visit_type, v.registration_date, v.status,
                     p.patient_number, p.first_name, p.last_name
              FROM patient_visits v 
              INNER JOIN patients p ON v.patient_id = p.patient_id
              WHERE v.patient_id = ? AND v.status IN ('REGISTERED', 'IN_CONSULTATION')
              ORDER BY v.registration_date DESC 
              LIMIT 10";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $visits = [];
    while ($row = $result->fetch_assoc()) {
        $visits[] = [
            'visit_id' => $row['visit_id'],
            'visit_number' => $row['visit_number'],
            'visit_type' => $row['visit_type'],
            'registration_date' => $row['registration_date'],
            'status' => $row['status'],
            'patient_number' => $row['patient_number'],
            'patient_name' => $row['first_name'] . ' ' . $row['last_name']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'visits' => $visits
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching visits: ' . $e->getMessage()
    ]);
}

$conn->close();
?>