<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

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

// Check if user is ENT doctor
if ($_SESSION['role_code'] !== 'ENT_DOCTOR') {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

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

// Get form data
$patient_id = intval($_POST['patient_id']);
$consultation_id = isset($_POST['consultation_id']) ? intval($_POST['consultation_id']) : null;
$test_type_id = intval($_POST['test_type_id']);
$priority = mysqli_real_escape_string($conn, $_POST['priority']);
$special_instructions = mysqli_real_escape_string($conn, $_POST['special_instructions']);
$clinical_notes = mysqli_real_escape_string($conn, $_POST['clinical_notes']);

mysqli_begin_transaction($conn);

try {
    // Generate order number
    $order_number = 'LAB-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    
    // Insert lab order
    $insert_query = "INSERT INTO lab_orders 
        (patient_id, consultation_id, test_type_id, order_number, order_date, 
         ordered_by, priority, special_instructions, clinical_notes, status)
    VALUES (?, ?, ?, ?, NOW(), ?, ?, ?, ?, 'ORDERED')";
    
    $stmt = $conn->prepare($insert_query);
    $stmt->bind_param("iiisisss", 
        $patient_id, 
        $consultation_id, 
        $test_type_id, 
        $order_number,
        $_SESSION['user_id'],
        $priority,
        $special_instructions,
        $clinical_notes
    );
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to create lab order: " . $stmt->error);
    }
    
    $order_id = $conn->insert_id;
    
    // Log activity
    $log_query = "INSERT INTO activity_log 
        (user_id, action, module, record_id, record_type, ip_address, logged_at)
    VALUES (?, 'CREATE', 'LAB_ORDERS', ?, 'LAB_ORDER', ?, NOW())";
    
    $log_stmt = $conn->prepare($log_query);
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $log_stmt->bind_param("iis", $_SESSION['user_id'], $order_id, $ip_address);
    $log_stmt->execute();
    
    mysqli_commit($conn);
    
    echo json_encode([
        'success' => true,
        'message' => 'Lab order created successfully',
        'order_id' => $order_id,
        'order_number' => $order_number
    ]);
    
} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>