<?php
session_start();
include '../layouts/dbconn.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$order_test_id = intval($_POST['order_test_id']);
$new_status = mysqli_real_escape_string($conn, $_POST['status']);
$user_id = $_SESSION['user_id'];

// Validate status
$valid_statuses = ['PENDING', 'SCHEDULED', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED'];
if(!in_array($new_status, $valid_statuses)) {
    echo json_encode(['success' => false, 'message' => 'Invalid status']);
    exit();
}

mysqli_begin_transaction($conn);

try {
    // Get current test details
    $test_query = "SELECT lot.*, lo.order_number, lo.patient_id
                   FROM lab_order_tests lot
                   INNER JOIN lab_orders lo ON lot.order_id = lo.order_id
                   WHERE lot.order_test_id = ?";
    $stmt = $conn->prepare($test_query);
    $stmt->bind_param('i', $order_test_id);
    $stmt->execute();
    $test = $stmt->get_result()->fetch_assoc();
    
    if(!$test) {
        throw new Exception("Test not found");
    }
    
    // Update test status
    $update_sql = "UPDATE lab_order_tests SET status = ?, updated_at = NOW()";
    $params = [$new_status];
    $types = 's';
    
    // Set additional fields based on status
    if($new_status === 'IN_PROGRESS') {
        $update_sql .= ", started_at = NOW(), tested_by = ?";
        $params[] = $user_id;
        $types .= 'i';
    } elseif($new_status === 'COMPLETED') {
        $update_sql .= ", completed_at = NOW()";
    }
    
    $update_sql .= " WHERE order_test_id = ?";
    $params[] = $order_test_id;
    $types .= 'i';
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param($types, ...$params);
    
    if(!$stmt->execute()) {
        throw new Exception("Failed to update test status");
    }
    
    // Update parent order status if needed
    if($new_status === 'COMPLETED') {
        // Check if all tests in the order are completed
        $check_query = "SELECT COUNT(*) as total, 
                        SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completed
                        FROM lab_order_tests
                        WHERE order_id = ?";
        $stmt = $conn->prepare($check_query);
        $stmt->bind_param('i', $test['order_id']);
        $stmt->execute();
        $order_status = $stmt->get_result()->fetch_assoc();
        
        if($order_status['total'] == $order_status['completed']) {
            $update_order = "UPDATE lab_orders SET status = 'COMPLETED', completed_at = NOW() WHERE order_id = ?";
            $stmt = $conn->prepare($update_order);
            $stmt->bind_param('i', $test['order_id']);
            $stmt->execute();
        }
    }
    
    // Log activity
    $log_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, created_at)
                VALUES (?, 'UPDATE', 'LAB_TEST', ?, ?, ?, NOW())";
    $stmt = $conn->prepare($log_sql);
    $description = "Updated test status to " . $new_status . " for order " . $test['order_number'];
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt->bind_param('iiss', $user_id, $order_test_id, $description, $ip_address);
    $stmt->execute();
    
    mysqli_commit($conn);
    
    echo json_encode([
        'success' => true,
        'message' => 'Test status updated successfully',
        'new_status' => $new_status
    ]);
    
} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

mysqli_close($conn);
?>