<?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();
}

$test_type_id = intval($_POST['test_type_id']);
$user_id = $_SESSION['user_id'];

mysqli_begin_transaction($conn);

try {
    // Get test type details
    $test_query = "SELECT test_name, test_code FROM ent_test_types WHERE test_type_id = ?";
    $stmt = $conn->prepare($test_query);
    $stmt->bind_param('i', $test_type_id);
    $stmt->execute();
    $test = $stmt->get_result()->fetch_assoc();

    if (!$test) {
        throw new Exception("Test type not found");
    }

    // Check if test type has pending or in-progress orders
    $check_sql = "SELECT COUNT(*) as active_count 
                  FROM lab_order_tests 
                  WHERE test_type_id = ? 
                  AND status IN ('PENDING', 'IN_PROGRESS', 'SCHEDULED')";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param('i', $test_type_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();

    if ($result['active_count'] > 0) {
        throw new Exception("Cannot deactivate test type with active orders. Please complete or cancel pending orders first.");
    }

    // Deactivate test type
    $update_sql = "UPDATE ent_test_types SET is_active = 0, updated_at = NOW() WHERE test_type_id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param('i', $test_type_id);

    if (!$stmt->execute()) {
        throw new Exception("Failed to deactivate test type");
    }

    // Log activity
    $log_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, created_at)
                VALUES (?, 'DELETE', 'TEST_TYPE', ?, ?, ?, NOW())";
    $stmt = $conn->prepare($log_sql);
    $description = "Deactivated test type: " . $test['test_name'] . " (" . $test['test_code'] . ")";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt->bind_param('iiss', $user_id, $test_type_id, $description, $ip_address);
    $stmt->execute();

    mysqli_commit($conn);

    echo json_encode([
        'success' => true,
        'message' => 'Test type deactivated successfully'
    ]);

} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

mysqli_close($conn);
?>