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

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

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

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

$test_type_id = isset($_POST['test_type_id']) ? (int) $_POST['test_type_id'] : 0;
if (!$test_type_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid test type ID']);
    exit();
}

// Get form data
$test_name = mysqli_real_escape_string($conn, $_POST['test_name']);
$category = mysqli_real_escape_string($conn, $_POST['category']);
$subcategory = mysqli_real_escape_string($conn, $_POST['subcategory']);
$description = mysqli_real_escape_string($conn, $_POST['description']);
$sample_type = mysqli_real_escape_string($conn, $_POST['sample_type']);
$normal_range = mysqli_real_escape_string($conn, $_POST['normal_range']);
$preparation_instructions = mysqli_real_escape_string($conn, $_POST['preparation_instructions']);
$cost = floatval($_POST['cost']);
$turnaround_time_hours = intval($_POST['turnaround_time_hours']);

$requires_fasting = isset($_POST['requires_fasting']) ? 1 : 0;
$requires_appointment = isset($_POST['requires_appointment']) ? 1 : 0;
$technician_required = isset($_POST['technician_required']) ? 1 : 0;
$external_lab = isset($_POST['external_lab']) ? 1 : 0;
$is_active = isset($_POST['is_active']) ? 1 : 0;

$equipment_required = mysqli_real_escape_string($conn, $_POST['equipment_required']);
$room_type_required = mysqli_real_escape_string($conn, $_POST['room_type_required']);
$external_lab_name = isset($_POST['external_lab_name']) ? mysqli_real_escape_string($conn, $_POST['external_lab_name']) : '';

if (empty($test_name) || empty($category) || $cost < 0) {
    echo json_encode(['success' => false, 'message' => 'Please fill all required fields correctly']);
    exit();
}

try {
    mysqli_begin_transaction($conn);

    $sql = "UPDATE ent_test_types SET 
            test_name = ?, 
            category = ?, 
            subcategory = ?,
            description = ?, 
            sample_type = ?,
            normal_range = ?,
            preparation_instructions = ?,
            cost = ?, 
            turnaround_time_hours = ?, 
            requires_fasting = ?, 
            requires_appointment = ?, 
            technician_required = ?, 
            external_lab = ?, 
            equipment_required = ?,
            room_type_required = ?,
            external_lab_name = ?,
            is_active = ?,
            updated_at = NOW()
            WHERE test_type_id = ?";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        'sssssssdiiiissssi',
        $test_name,
        $category,
        $subcategory,
        $description,
        $sample_type,
        $normal_range,
        $preparation_instructions,
        $cost,
        $turnaround_time_hours,
        $requires_fasting,
        $requires_appointment,
        $technician_required,
        $external_lab,
        $equipment_required,
        $room_type_required,
        $external_lab_name,
        $is_active,
        $test_type_id
    );

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

        mysqli_commit($conn);
        echo json_encode(['success' => true, 'message' => 'Test type updated successfully', 'test_type_id' => $test_type_id]);
    } else {
        throw new Exception("Failed to update test type");
    }

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

$conn->close();
?>