<?php
/**
 * Complete Audio Test AJAX Endpoint
 * Updates test status to COMPLETED with results
 */

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

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

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

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

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

// Get and validate input
$order_test_id = isset($_POST['order_test_id']) ? intval($_POST['order_test_id']) : 0;
$result_value = isset($_POST['result_value']) ? trim($_POST['result_value']) : '';
$result_unit = isset($_POST['result_unit']) ? trim($_POST['result_unit']) : null;
$reference_range = isset($_POST['reference_range']) ? trim($_POST['reference_range']) : null;
$interpretation = isset($_POST['interpretation']) ? trim($_POST['interpretation']) : null;
$abnormal_flag = isset($_POST['abnormal_flag']) ? $_POST['abnormal_flag'] : 'NORMAL';
$result_files = isset($_POST['result_files']) ? $_POST['result_files'] : null;

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

// Validate abnormal_flag
$valid_flags = ['NORMAL', 'HIGH', 'LOW', 'CRITICAL', 'ABNORMAL'];
if (!in_array($abnormal_flag, $valid_flags)) {
    $abnormal_flag = 'NORMAL';
}

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['full_name'] ?? 'Audiologist';

// Start transaction
$conn->begin_transaction();

try {
    // Verify the test exists and is in progress by this audiologist
    $verify_sql = "SELECT lot.order_test_id, lot.order_id, lot.status, lot.tested_by, lot.test_type_id,
                          lo.order_number, lo.patient_id, lo.ordered_by,
                          ett.test_name, ett.test_code, ett.category,
                          p.patient_number, u.full_name as patient_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 u ON p.user_id = u.user_id
                   WHERE lot.order_test_id = ?
                   AND lot.tested_by = ?
                   AND ett.category IN ('AUDIOMETRY')";
    
    $stmt = $conn->prepare($verify_sql);
    $stmt->bind_param("ii", $order_test_id, $user_id);
    $stmt->execute();
    $test = $stmt->get_result()->fetch_assoc();
    
    if (!$test) {
        throw new Exception('Test not found or you are not authorized to complete this test.');
    }
    
    if ($test['status'] == 'COMPLETED') {
        throw new Exception('Test has already been completed.');
    }
    
    if ($test['status'] != 'IN_PROGRESS') {
        throw new Exception('Test must be in progress before it can be completed.');
    }
    
    // Prepare result files JSON if provided
    $result_files_json = null;
    if ($result_files && is_array($result_files)) {
        $result_files_json = json_encode($result_files);
    } elseif ($result_files && is_string($result_files)) {
        // Validate JSON
        $test_json = json_decode($result_files);
        if (json_last_error() === JSON_ERROR_NONE) {
            $result_files_json = $result_files;
        }
    }
    
    // Update test status to COMPLETED with results
    $update_sql = "UPDATE lab_order_tests 
                   SET status = 'COMPLETED',
                       result_value = ?,
                       result_unit = ?,
                       reference_range = ?,
                       interpretation = ?,
                       abnormal_flag = ?,
                       result_files = ?,
                       completed_at = NOW(),
                       updated_at = NOW()
                   WHERE order_test_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("ssssssi", 
        $result_value, 
        $result_unit, 
        $reference_range, 
        $interpretation, 
        $abnormal_flag, 
        $result_files_json,
        $order_test_id
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update test results: ' . $stmt->error);
    }
    
    // Check if all tests in the order are completed
    $check_order_sql = "SELECT 
                            COUNT(*) as total_tests,
                            COUNT(CASE WHEN status = 'COMPLETED' THEN 1 END) as completed_tests
                        FROM lab_order_tests
                        WHERE order_id = ?";
    
    $stmt = $conn->prepare($check_order_sql);
    $stmt->bind_param("i", $test['order_id']);
    $stmt->execute();
    $order_check = $stmt->get_result()->fetch_assoc();
    
    if ($order_check['total_tests'] == $order_check['completed_tests']) {
        // All tests completed, update order status
        $update_order_sql = "UPDATE lab_orders 
                            SET status = 'COMPLETED',
                                completed_at = NOW(),
                                updated_at = NOW()
                            WHERE order_id = ?";
        
        $stmt = $conn->prepare($update_order_sql);
        $stmt->bind_param("i", $test['order_id']);
        $stmt->execute();
    }
    
    // Log the activity
    $activity_sql = "INSERT INTO activity_log 
                    (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent, logged_at)
                    VALUES (?, 'COMPLETE_TEST', 'AUDIOLOGY', ?, 'LAB_ORDER_TEST', ?, ?, ?, NOW())";
    
    $new_values = json_encode([
        'order_test_id' => $order_test_id,
        'order_number' => $test['order_number'],
        'test_name' => $test['test_name'],
        'test_code' => $test['test_code'],
        'patient_name' => $test['patient_name'],
        'patient_number' => $test['patient_number'],
        'result_value' => $result_value,
        'abnormal_flag' => $abnormal_flag,
        'status' => 'COMPLETED',
        'completed_by' => $user_name,
        'completed_at' => date('Y-m-d H:i:s')
    ]);
    
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    
    $stmt = $conn->prepare($activity_sql);
    $stmt->bind_param("iisss", $user_id, $order_test_id, $new_values, $ip_address, $user_agent);
    $stmt->execute();
    
    // Create notification for the ordering doctor
    if ($test['ordered_by']) {
        $notify_sql = "INSERT INTO notifications 
                      (user_id, title, message, type, reference_type, reference_id, created_at)
                      VALUES (?, ?, ?, ?, 'LAB_TEST', ?, NOW())";
        
        // Get doctor's user_id
        $doctor_user_sql = "SELECT user_id FROM doctors WHERE doctor_id = ?";
        $stmt = $conn->prepare($doctor_user_sql);
        $stmt->bind_param("i", $test['ordered_by']);
        $stmt->execute();
        $doctor_result = $stmt->get_result()->fetch_assoc();
        
        if ($doctor_result) {
            $notify_title = "Test Completed: " . $test['test_name'];
            $notify_message = $test['test_name'] . " for patient " . $test['patient_name'] . 
                            " has been completed. Result: " . $abnormal_flag . 
                            " (Order: " . $test['order_number'] . ")";
            
            $notify_type = ($abnormal_flag == 'CRITICAL') ? 'URGENT' : 
                          (($abnormal_flag == 'NORMAL') ? 'INFO' : 'WARNING');
            
            $stmt = $conn->prepare($notify_sql);
            $stmt->bind_param("isssi", 
                $doctor_result['user_id'], 
                $notify_title, 
                $notify_message, 
                $notify_type,
                $order_test_id
            );
            $stmt->execute();
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    // Success response
    $response['success'] = true;
    $response['message'] = 'Test completed successfully. Results have been recorded.';
    $response['data'] = [
        'order_test_id' => $order_test_id,
        'order_number' => $test['order_number'],
        'test_name' => $test['test_name'],
        'patient_name' => $test['patient_name'],
        'abnormal_flag' => $abnormal_flag,
        'status' => 'COMPLETED',
        'completed_at' => date('Y-m-d H:i:s')
    ];
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    $response['success'] = false;
    $response['message'] = $e->getMessage();
    
    error_log("Error completing audio test: " . $e->getMessage() . " | User ID: " . $user_id . " | Test ID: " . $order_test_id);
}

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