<?php
/**
 * Start Audio Test AJAX Endpoint
 * Updates test status to IN_PROGRESS and logs the action
 */

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

// Include required files
require_once '../layouts/session.php';
require_once '../layouts/dbconn.php';

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

// Check if user is logged in and is an audiologist
if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] != 'AUDIOLOGIST') {
    $response['message'] = 'Unauthorized access. Audiologist login required.';
    echo json_encode($response);
    exit();
}

// Check if request method is POST
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;

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

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

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

try {
    // First, verify the test exists and get its current status
    $verify_sql = "SELECT lot.order_test_id, lot.order_id, lot.status, lot.test_type_id, lot.tested_by,
                          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 ett.category IN ('AUDIOMETRY')";
    
    $stmt = $conn->prepare($verify_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 not authorized for audiologist.');
    }
    
    // Check if test is already in progress or completed
    if ($test['status'] == 'IN_PROGRESS') {
        throw new Exception('Test is already in progress.');
    }
    
    if ($test['status'] == 'COMPLETED') {
        throw new Exception('Test has already been completed.');
    }
    
    if ($test['status'] == 'CANCELLED') {
        throw new Exception('Test has been cancelled and cannot be started.');
    }
    
    // Update test status to IN_PROGRESS
    $update_sql = "UPDATE lab_order_tests 
                   SET status = 'IN_PROGRESS',
                       tested_by = ?,
                       started_at = NOW(),
                       updated_at = NOW()
                   WHERE order_test_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("ii", $user_id, $order_test_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update test status: ' . $stmt->error);
    }
    
    // Check if the overall lab order needs status update
    // If this is the first test being started, update order status
    $check_order_sql = "SELECT COUNT(*) as in_progress_count
                        FROM lab_order_tests
                        WHERE order_id = ?
                        AND status = 'IN_PROGRESS'";
    
    $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['in_progress_count'] == 1) {
        // This is the first test being started, update order status
        $update_order_sql = "UPDATE lab_orders 
                            SET status = 'IN_PROGRESS',
                                updated_at = NOW()
                            WHERE order_id = ?
                            AND status IN ('PENDING', 'SCHEDULED')";
        
        $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 (?, 'START_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'],
        'status' => 'IN_PROGRESS',
        'started_by' => $user_name,
        'started_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);
    
    if (!$stmt->execute()) {
        // Log activity failure shouldn't stop the main operation
        error_log("Failed to log activity for test start: " . $stmt->error);
    }
    
    // Create notification for the ordering doctor (optional)
    if ($test['ordered_by']) {
        $notify_sql = "INSERT INTO notifications 
                      (user_id, title, message, type, reference_type, reference_id, created_at)
                      VALUES (?, ?, ?, 'INFO', '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 Started: " . $test['test_name'];
            $notify_message = "Audiologist " . $user_name . " has started " . $test['test_name'] . 
                            " for patient " . $test['patient_name'] . " (Order: " . $test['order_number'] . ")";
            
            $stmt = $conn->prepare($notify_sql);
            $stmt->bind_param("issi", $doctor_result['user_id'], $notify_title, $notify_message, $order_test_id);
            $stmt->execute();
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    // Success response
    $response['success'] = true;
    $response['message'] = 'Test started successfully. You can now proceed with testing.';
    $response['data'] = [
        'order_test_id' => $order_test_id,
        'order_number' => $test['order_number'],
        'test_name' => $test['test_name'],
        'patient_name' => $test['patient_name'],
        'status' => 'IN_PROGRESS',
        'started_at' => date('Y-m-d H:i:s')
    ];
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    $response['success'] = false;
    $response['message'] = $e->getMessage();
    
    // Log error
    error_log("Error starting audio test: " . $e->getMessage() . " | User ID: " . $user_id . " | Test ID: " . $order_test_id);
}

// Close database connection
$conn->close();

// Return JSON response
echo json_encode($response);
exit();
?>