<?php
// ajax/get_consultations.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(['error' => 'Unauthorized']);
    exit();
}

// Check if visit_id is provided
if (!isset($_GET['visit_id']) || empty($_GET['visit_id'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Visit ID is required']);
    exit();
}

$visit_id = $_GET['visit_id'];

try {
    // Get consultations for the specified visit
    $query = "SELECT c.consultation_id, c.consultation_number, u.full_name as doctor_name, c.status
              FROM consultations c
              INNER JOIN users u ON c.doctor_id = u.user_id
              WHERE c.visit_id = ?
              ORDER BY c.created_at DESC";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $visit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $consultations = [];
    while ($row = $result->fetch_assoc()) {
        $consultations[] = [
            'consultation_id' => $row['consultation_id'],
            'consultation_number' => $row['consultation_number'],
            'doctor_name' => $row['full_name'],
            'status' => $row['status']
        ];
    }
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode($consultations);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}

$conn->close();
?>