<?php
session_start();
header('Content-Type: application/json');
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 (support both GET and POST)
$patient_id = null;
if (isset($_GET['patient_id'])) {
    $patient_id = $_GET['patient_id'];
} elseif (isset($_POST['patient_id'])) {
    $patient_id = $_POST['patient_id'];
}

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 with patient details
    // Fixed query to join with users table (since patients table links to users table)
    $query = "SELECT 
                v.visit_id, 
                v.visit_number, 
                v.visit_type, 
                v.registration_date,
                v.status,
                v.visit_source,
                p.patient_number,
                u.full_name as patient_name
              FROM patient_visits v 
              INNER JOIN patients p ON v.patient_id = p.patient_id
              INNER JOIN users u ON p.user_id = u.user_id
              WHERE v.patient_id = ? 
                AND v.status IN ('REGISTERED', 'WAITING', 'IN_CONSULTATION')
              ORDER BY v.registration_date DESC 
              LIMIT 10";
    
    $stmt = $conn->prepare($query);
    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();
    
    $visits = [];
    while ($row = $result->fetch_assoc()) {
        // Format date nicely
        $reg_date = new DateTime($row['registration_date']);
        $formatted_date = $reg_date->format('M d, Y');
        
        $visits[] = [
            'visit_id' => (int)$row['visit_id'],
            'visit_number' => $row['visit_number'],
            'visit_type' => $row['visit_type'],
            'visit_source' => $row['visit_source'],
            'registration_date' => $row['registration_date'],
            'formatted_date' => $formatted_date,
            'status' => $row['status'],
            'patient_number' => $row['patient_number'],
            'patient_name' => $row['patient_name']
        ];
    }
    
    $stmt->close();
    
    echo json_encode([
        'success' => true,
        'visits' => $visits,
        'count' => count($visits)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching visits: ' . $e->getMessage()
    ]);
    error_log("Get patient visits error: " . $e->getMessage());
}

$conn->close();
?>