<?php
/**
 * Get Test Details AJAX Endpoint
 * Retrieves detailed information about a specific test
 */

header('Content-Type: application/json');

require_once '../layouts/session.php';
require_once '../layouts/dbconn.php';

$response = ['success' => false, 'message' => '', 'data' => null];

// Check authentication
if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] != 'AUDIOLOGIST') {
    $response['message'] = 'Unauthorized access.';
    echo json_encode($response);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'POST') {
    $response['message'] = 'Invalid request method.';
    echo json_encode($response);
    exit();
}

// Get test ID
$order_test_id = isset($_GET['order_test_id']) ? intval($_GET['order_test_id']) : 
                (isset($_POST['order_test_id']) ? intval($_POST['order_test_id']) : 0);

if ($order_test_id <= 0) {
    $response['message'] = 'Invalid test ID.';
    echo json_encode($response);
    exit();
}

try {
    // Get comprehensive test details
    $test_sql = "SELECT 
                    lot.order_test_id,
                    lot.order_id,
                    lot.test_type_id,
                    lot.status,
                    lot.scheduled_at,
                    lot.started_at,
                    lot.completed_at,
                    lot.test_cost,
                    lot.result_value,
                    lot.result_unit,
                    lot.reference_range,
                    lot.interpretation,
                    lot.abnormal_flag,
                    lot.result_files,
                    lot.tested_by,
                    lot.verified_by,
                    lo.order_number,
                    lo.order_date,
                    lo.patient_id,
                    lo.ordered_by,
                    lo.priority,
                    lo.clinical_notes,
                    lo.clinical_indication,
                    ett.test_name,
                    ett.test_code,
                    ett.category,
                    ett.description as test_description,
                    ett.normal_range,
                    ett.preparation_instructions,
                    p.patient_number,
                    pu.full_name as patient_name,
                    pu.date_of_birth,
                    pu.gender,
                    pu.phone,
                    pu.email,
                    d.doctor_id,
                    du.full_name as doctor_name,
                    tu.full_name as tested_by_name,
                    vu.full_name as verified_by_name
                FROM lab_order_tests lot
                INNER JOIN lab_orders lo ON lot.order_id = lo.order_id
                INNER JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
                INNER JOIN patients p ON lo.patient_id = p.patient_id
                INNER JOIN users pu ON p.user_id = pu.user_id
                LEFT JOIN doctors d ON lo.ordered_by = d.doctor_id
                LEFT JOIN users du ON d.user_id = du.user_id
                LEFT JOIN users tu ON lot.tested_by = tu.user_id
                LEFT JOIN users vu ON lot.verified_by = vu.user_id
                WHERE lot.order_test_id = ?
                AND ett.category IN ('AUDIOMETRY')";
    
    $stmt = $conn->prepare($test_sql);
    $stmt->bind_param("i", $order_test_id);
    $stmt->execute();
    $test = $stmt->get_result()->fetch_assoc();
    
    if (!$test) {
        throw new Exception('Test not found or access denied.');
    }
    
    // Calculate patient age if DOB available
    if ($test['date_of_birth']) {
        $dob = new DateTime($test['date_of_birth']);
        $now = new DateTime();
        $test['age'] = $now->diff($dob)->y;
    } else {
        $test['age'] = null;
    }
    
    // Parse result files JSON
    if ($test['result_files']) {
        $test['result_files_parsed'] = json_decode($test['result_files'], true);
    } else {
        $test['result_files_parsed'] = [];
    }
    
    // Get previous test results for this patient and test type (for comparison)
    $history_sql = "SELECT 
                        lot.order_test_id,
                        lot.completed_at,
                        lot.result_value,
                        lot.abnormal_flag,
                        lo.order_number
                    FROM lab_order_tests lot
                    INNER JOIN lab_orders lo ON lot.order_id = lo.order_id
                    WHERE lo.patient_id = ?
                    AND lot.test_type_id = ?
                    AND lot.status = 'COMPLETED'
                    AND lot.order_test_id != ?
                    ORDER BY lot.completed_at DESC
                    LIMIT 5";
    
    $stmt = $conn->prepare($history_sql);
    $stmt->bind_param("iii", $test['patient_id'], $test['test_type_id'], $order_test_id);
    $stmt->execute();
    $history_result = $stmt->get_result();
    
    $test_history = [];
    while ($history = $history_result->fetch_assoc()) {
        $test_history[] = $history;
    }
    $test['previous_results'] = $test_history;
    
    // Format dates for display
    $test['scheduled_at_formatted'] = $test['scheduled_at'] ? date('M j, Y g:i A', strtotime($test['scheduled_at'])) : null;
    $test['started_at_formatted'] = $test['started_at'] ? date('M j, Y g:i A', strtotime($test['started_at'])) : null;
    $test['completed_at_formatted'] = $test['completed_at'] ? date('M j, Y g:i A', strtotime($test['completed_at'])) : null;
    $test['order_date_formatted'] = $test['order_date'] ? date('M j, Y', strtotime($test['order_date'])) : null;
    
    // Calculate test duration if started and completed
    if ($test['started_at'] && $test['completed_at']) {
        $start = new DateTime($test['started_at']);
        $end = new DateTime($test['completed_at']);
        $interval = $start->diff($end);
        $test['duration_minutes'] = ($interval->h * 60) + $interval->i;
    } else {
        $test['duration_minutes'] = null;
    }
    
    $response['success'] = true;
    $response['message'] = 'Test details retrieved successfully.';
    $response['data'] = $test;
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
    error_log("Error getting test details: " . $e->getMessage());
}

$conn->close();
echo json_encode($response);
exit();
?>