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

// Check authentication
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Get patient and visit info if provided
$patient_id = isset($_GET['patient_id']) ? intval($_GET['patient_id']) : 0;
$visit_id = isset($_GET['visit_id']) ? intval($_GET['visit_id']) : 0;
$consultation_id = isset($_GET['consultation_id']) ? intval($_GET['consultation_id']) : 0;

$patient = null;
$visit = null;
$smart_session = null;
$smart_benefits = [];

if ($patient_id > 0) {
    $patient_sql = "SELECT * FROM patients WHERE patient_id = ?";
    $stmt = $conn->prepare($patient_sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $patient = $stmt->get_result()->fetch_assoc();
}

if ($visit_id > 0) {
    $visit_sql = "SELECT * FROM patient_visits WHERE visit_id = ?";
    $stmt = $conn->prepare($visit_sql);
    $stmt->bind_param("i", $visit_id);
    $stmt->execute();
    $visit = $stmt->get_result()->fetch_assoc();
    
    // Check for SMART session
    if ($visit && $visit['smart_session_id']) {
        $smart_sql = "SELECT * FROM smart_sessions WHERE id = ?";
        $stmt = $conn->prepare($smart_sql);
        $stmt->bind_param("i", $visit['smart_session_id']);
        $stmt->execute();
        $smart_session = $stmt->get_result()->fetch_assoc();
        
        // Get SMART benefits
        if ($smart_session) {
            $benefits_sql = "SELECT * FROM smart_benefits WHERE session_id = ? AND claimable = 1";
            $stmt = $conn->prepare($benefits_sql);
            $stmt->bind_param("i", $smart_session['id']);
            $stmt->execute();
            $smart_benefits = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        }
    }
}

// Get test types
$tests_sql = "SELECT * FROM service_pricing WHERE is_active = 1 ORDER BY service_type, service_name";
$test_types = $conn->query($tests_sql);

// Group tests by category
$tests_by_category = [];
$test_types->data_seek(0);
while ($test = $test_types->fetch_assoc()) {
    $tests_by_category[$test['service_type']][] = $test;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $conn->begin_transaction();
    
    try {
        $patient_id = intval($_POST['patient_id']);
        $visit_id = intval($_POST['visit_id']);
        $consultation_id = isset($_POST['consultation_id']) ? intval($_POST['consultation_id']) : null;
        $priority = $_POST['priority'];
        $clinical_notes = $_POST['clinical_notes'];
        $clinical_indication = $_POST['clinical_indication'];
        $selected_tests = json_decode($_POST['selected_tests'], true);
        
        // Generate order number
        $order_number = 'LAB' . date('Ymd') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
        
        // Calculate totals
        $total_cost = 0;
        foreach ($selected_tests as $test) {
            $total_cost += floatval($test['cost']);
        }
        
        // Calculate commissions (10% lab, 5% doctor)
        $lab_commission = $total_cost * 0.10;
        $doctor_commission = $total_cost * 0.05;
        
        // Insert lab order
        $order_sql = "INSERT INTO lab_orders (
            order_number, visit_id, patient_id, consultation_id, ordered_by,
            priority, clinical_notes, clinical_indication, total_cost,
            lab_commission, ordering_doctor_commission, status, ordered_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', NOW())";
        
        $stmt = $conn->prepare($order_sql);
        $stmt->bind_param(
            "siiiisssdd d",
            $order_number, $visit_id, $patient_id, $consultation_id, $user_id,
            $priority, $clinical_notes, $clinical_indication, $total_cost,
            $lab_commission, $doctor_commission
        );
        $stmt->execute();
        $order_id = $conn->insert_id;
        
        // Insert individual tests
        $test_sql = "INSERT INTO lab_order_tests (
            order_id, test_type_id, test_cost, status
        ) VALUES (?, ?, ?, 'PENDING')";
        
        $stmt = $conn->prepare($test_sql);
        foreach ($selected_tests as $test) {
            $stmt->bind_param("iid", $order_id, $test['test_id'], $test['cost']);
            $stmt->execute();
        }
        
        // Check if SMART preauth is needed
        $needs_preauth = false;
        if (isset($_POST['smart_session_id']) && intval($_POST['smart_session_id']) > 0) {
            $smart_session_id = intval($_POST['smart_session_id']);
            $preauth_type = $_POST['preauth_type'] ?? 'ZERO';
            
            if ($preauth_type != 'ZERO') {
                $needs_preauth = true;
                
                // Create SMART preauth request
                $preauth_code = 'PREAUTH' . date('YmdHis') . rand(100, 999);
                
                $preauth_sql = "INSERT INTO smart_preauth (
                    visit_id, smart_session_id, preauth_request_code,
                    preauth_type, requested_amount, preauth_status,
                    requested_by, requested_at
                ) VALUES (?, ?, ?, ?, ?, 'PENDING', ?, NOW())";
                
                $stmt = $conn->prepare($preauth_sql);
                $stmt->bind_param(
                    "iissdi",
                    $visit_id, $smart_session_id, $preauth_code,
                    $preauth_type, $total_cost, $user_id
                );
                $stmt->execute();
            }
        }
        
        // Log activity
        $activity_sql = "INSERT INTO activity_logs (
            user_id, action, entity_type, entity_id, description
        ) VALUES (?, 'CREATE', 'LAB_ORDER', ?, ?)";
        
        $description = "Created lab order $order_number for patient ID $patient_id";
        $stmt = $conn->prepare($activity_sql);
        $stmt->bind_param("iis", $user_id, $order_id, $description);
        $stmt->execute();
        
        $conn->commit();
        
        $response = [
            'success' => true,
            'message' => 'Lab order created successfully',
            'order_id' => $order_id,
            'order_number' => $order_number,
            'needs_preauth' => $needs_preauth
        ];
        
        if (isset($_POST['ajax'])) {
            echo json_encode($response);
            exit();
        } else {
            $_SESSION['success_message'] = 'Lab order created successfully!';
            header('Location: list_lab_orders.php');
            exit();
        }
        
    } catch (Exception $e) {
        $conn->rollback();
        
        if (isset($_POST['ajax'])) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
            exit();
        } else {
            $_SESSION['error_message'] = 'Error creating lab order: ' . $e->getMessage();
        }
    }
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Lab Order')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="assets/libs/select2/select2.min.css" rel="stylesheet">
    
    <style>
        .test-category-card {
            border: 2px solid #e9ecef;
            border-radius: 8px;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .test-category-card:hover {
            border-color: #667eea;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
        }
        
        .test-checkbox {
            transform: scale(1.2);
            margin-right: 0.5rem;
        }
        
        .selected-tests-summary {
            position: sticky;
            top: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
        }
        
        .smart-badge {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: 600;
        }
        
        .preauth-alert {
            border-left: 4px solid #ff9800;
            background: #fff3e0;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">
                                    <i class="ri-test-tube-line me-2"></i>Create Lab Order
                                </h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_lab_orders.php">Lab Orders</a></li>
                                        <li class="breadcrumb-item active">Create Order</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <form id="labOrderForm" method="POST">
                        <div class="row">
                            <!-- Left Column: Order Details -->
                            <div class="col-lg-8">
                                <!-- Patient Information -->
                                <div class="card">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0">
                                            <i class="ri-user-line me-2"></i>Patient Information
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <?php if ($patient): ?>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <p><strong>Patient Name:</strong> <?php echo htmlspecialchars($patient['full_name']); ?></p>
                                                    <p><strong>Patient Number:</strong> <?php echo $patient['patient_number']; ?></p>
                                                    <p><strong>Age/Gender:</strong> 
                                                        <?php 
                                                        $dob = new DateTime($patient['date_of_birth']);
                                                        $age = $dob->diff(new DateTime())->y;
                                                        echo "$age years / " . $patient['gender'];
                                                        ?>
                                                    </p>
                                                </div>
                                                <div class="col-md-6">
                                                    <p><strong>Phone:</strong> <?php echo $patient['phone_primary']; ?></p>
                                                    <?php if ($visit && $visit['registration_type'] == 'INSURANCE'): ?>
                                                        <p><strong>Registration:</strong> 
                                                            <span class="badge bg-info">INSURANCE</span>
                                                            <?php if ($smart_session): ?>
                                                                <span class="smart-badge ms-2">
                                                                    <i class="ri-shield-check-line me-1"></i>SMART
                                                                </span>
                                                            <?php endif; ?>
                                                        </p>
                                                        <?php if ($smart_session): ?>
                                                            <p><strong>Member Number:</strong> <?php echo $smart_session['smart_member_number']; ?></p>
                                                        <?php endif; ?>
                                                    <?php else: ?>
                                                        <p><strong>Registration:</strong> <span class="badge bg-secondary">CASH</span></p>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            
                                            <input type="hidden" name="patient_id" value="<?php echo $patient_id; ?>">
                                            <input type="hidden" name="visit_id" value="<?php echo $visit_id; ?>">
                                            <input type="hidden" name="consultation_id" value="<?php echo $consultation_id; ?>">
                                            <?php if ($smart_session): ?>
                                                <input type="hidden" name="smart_session_id" value="<?php echo $smart_session['id']; ?>">
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <div class="mb-3">
                                                <label class="form-label">Search Patient *</label>
                                                <select class="form-select select2-patient" name="patient_id" required>
                                                    <option value="">Select Patient</option>
                                                </select>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <!-- SMART Preauthorization Alert -->
                                <?php if ($smart_session && !empty($smart_benefits)): ?>
                                <div class="preauth-alert">
                                    <h6><i class="ri-alert-line me-2"></i>SMART Pre-authorization Required</h6>
                                    <p class="mb-2">This patient is under SMART insurance. Please select preauthorization type:</p>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="preauth_type" 
                                               id="preauth_zero" value="ZERO" checked>
                                        <label class="form-check-label" for="preauth_zero">
                                            Type 0 (No preauth needed)
                                        </label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="preauth_type" 
                                               id="preauth_one" value="ONE">
                                        <label class="form-check-label" for="preauth_one">
                                            Type 1 (24hr preauth)
                                        </label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="preauth_type" 
                                               id="preauth_two" value="TWO">
                                        <label class="form-check-label" for="preauth_two">
                                            Type 2 (48hr preauth)
                                        </label>
                                    </div>
                                    
                                    <div class="mt-3">
                                        <strong>Available Benefits:</strong>
                                        <ul class="mb-0">
                                            <?php foreach ($smart_benefits as $benefit): ?>
                                                <li>
                                                    <?php echo $benefit['pool_description']; ?>: 
                                                    KES <?php echo number_format($benefit['amount'], 2); ?>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <!-- Order Details -->
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="ri-file-list-3-line me-2"></i>Order Details
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row g-3">
                                            <div class="col-md-4">
                                                <label class="form-label">Priority *</label>
                                                <select class="form-select" name="priority" required>
                                                    <option value="ROUTINE">Routine</option>
                                                    <option value="URGENT">Urgent</option>
                                                    <option value="STAT">STAT</option>
                                                </select>
                                            </div>
                                            <div class="col-12">
                                                <label class="form-label">Clinical Notes *</label>
                                                <textarea class="form-control" name="clinical_notes" 
                                                          rows="3" required 
                                                          placeholder="Enter clinical notes or reason for tests"></textarea>
                                            </div>
                                            <div class="col-12">
                                                <label class="form-label">Clinical Indication</label>
                                                <textarea class="form-control" name="clinical_indication" 
                                                          rows="2" 
                                                          placeholder="Enter clinical indication or symptoms"></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Test Selection -->
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="ri-checkbox-multiple-line me-2"></i>Select Tests
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <?php foreach ($tests_by_category as $category => $tests): ?>
                                            <div class="test-category-card">
                                                <div class="card-header bg-light">
                                                    <h6 class="mb-0">
                                                        <?php 
                                                        $category_icons = [
                                                            'AUDIOMETRY' => 'ri-ear-line',
                                                            'VESTIBULAR' => 'ri-compass-3-line',
                                                            'IMAGING' => 'ri-image-line',
                                                            'ENDOSCOPY' => 'ri-camera-line',
                                                            'ALLERGY' => 'ri-medicine-bottle-line',
                                                            'SLEEP_STUDY' => 'ri-moon-line',
                                                            'PATHOLOGY' => 'ri-microscope-line',
                                                            'MICROBIOLOGY' => 'ri-virus-line'
                                                        ];
                                                        $icon = $category_icons[$category] ?? 'ri-test-tube-line';
                                                        ?>
                                                        <i class="<?php echo $icon; ?> me-2"></i>
                                                        <?php echo str_replace('_', ' ', $category); ?>
                                                    </h6>
                                                </div>
                                                <div class="card-body">
                                                    <div class="row">
                                                        <?php foreach ($tests as $test): ?>
                                                            <div class="col-md-6 mb-2">
                                                                <div class="form-check">
                                                                    <input class="form-check-input test-checkbox" 
                                                                           type="checkbox" 
                                                                           name="tests[]" 
                                                                           value="<?php echo $test['pricing_id']; ?>"
                                                                           data-test-id="<?php echo $test['pricing_id']; ?>"
                                                                           data-test-name="<?php echo htmlspecialchars($test['service_name']); ?>"
                                                                           data-test-code="<?php echo $test['service_type']; ?>"
                                                                           data-test-cost="<?php echo $test['base_price']; ?>"
                                                                           id="test_<?php echo $test['pricing_id']; ?>">
                                                                    <label class="form-check-label" 
                                                                           for="test_<?php echo $test['pricing_id']; ?>">
                                                                        <strong><?php echo $test['service_name']; ?></strong>
                                                                        <span class="text-muted">(<?php echo $test['pricing_id']; ?>)</span>
                                                                        <br>
                                                                        <small class="text-primary">
                                                                            KES <?php echo number_format($test['base_price'], 2); ?>
                                                                        </small>
                                                                        <?php if ($test['requires_appointment']): ?>
                                                                            <span class="badge bg-warning-subtle text-warning ms-2">
                                                                                Requires Appointment
                                                                            </span>
                                                                        <?php endif; ?>
                                                                    </label>
                                                                </div>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Right Column: Summary -->
                            <div class="col-lg-4">
                                <div class="selected-tests-summary">
                                    <h5 class="mb-3">
                                        <i class="ri-shopping-cart-line me-2"></i>Selected Tests
                                    </h5>
                                    
                                    <div id="selectedTestsList">
                                        <p class="text-center opacity-75">No tests selected</p>
                                    </div>
                                    
                                    <hr class="border-white opacity-25">
                                    
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Total Tests:</span>
                                        <strong id="totalTests">0</strong>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between mb-3">
                                        <span>Total Cost:</span>
                                        <strong id="totalCost">KES 0.00</strong>
                                    </div>
                                    
                                    <input type="hidden" name="selected_tests" id="selectedTestsData" value="[]">
                                    
                                    <button type="submit" class="btn btn-light w-100 mb-2" id="submitBtn" disabled>
                                        <i class="ri-add-line me-1"></i>Create Lab Order
                                    </button>
                                    
                                    <button type="button" class="btn btn-outline-light w-100" onclick="clearSelection()">
                                        <i class="ri-delete-bin-line me-1"></i>Clear Selection
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/libs/select2/select2.min.js"></script>

    <script>
        let selectedTests = [];

        $(document).ready(function() {
            // Initialize Select2 for patient search (if not pre-selected)
            <?php if (!$patient): ?>
            $('.select2-patient').select2({
                ajax: {
                    url: 'ajax/search_patients.php',
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return { q: params.term };
                    },
                    processResults: function(data) {
                        return {
                            results: data.map(item => ({
                                id: item.patient_id,
                                text: item.patient_number + ' - ' + item.full_name
                            }))
                        };
                    }
                },
                minimumInputLength: 2,
                placeholder: 'Search by name or patient number'
            });
            <?php endif; ?>

            // Test checkbox change handler
            $('.test-checkbox').change(function() {
                updateSelectedTests();
            });

            // Form submission
            $('#labOrderForm').submit(function(e) {
                e.preventDefault();
                
                if (selectedTests.length === 0) {
                    Swal.fire('Error', 'Please select at least one test', 'error');
                    return;
                }
                
                const formData = new FormData(this);
                formData.append('ajax', '1');
                
                Swal.fire({
                    title: 'Creating Lab Order',
                    text: 'Please wait...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                $.ajax({
                    url: 'create_lab_order.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        try {
                            const data = typeof response === 'string' ? JSON.parse(response) : response;
                            
                            if (data.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Success!',
                                    text: data.message,
                                    timer: 2000
                                }).then(() => {
                                    if (data.needs_preauth) {
                                        window.location.href = 'manage_preauth.php?order=' + data.order_id;
                                    } else {
                                        window.location.href = 'list_lab_orders.php';
                                    }
                                });
                            } else {
                                Swal.fire('Error', data.message, 'error');
                            }
                        } catch (e) {
                            Swal.fire('Error', 'Invalid server response', 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error', 'Failed to create lab order', 'error');
                    }
                });
            });
        });

        function updateSelectedTests() {
            selectedTests = [];
            let totalCost = 0;
            
            $('.test-checkbox:checked').each(function() {
                const test = {
                    test_id: $(this).data('test-id'),
                    test_name: $(this).data('test-name'),
                    test_code: $(this).data('test-code'),
                    cost: parseFloat($(this).data('test-cost'))
                };
                
                selectedTests.push(test);
                totalCost += test.cost;
            });
            
            // Update UI
            if (selectedTests.length > 0) {
                let html = '<div class="list-group list-group-flush">';
                selectedTests.forEach(test => {
                    html += `
                        <div class="list-group-item bg-transparent border-white border-opacity-25 text-white p-2">
                            <div class="d-flex justify-content-between">
                                <small>${test.test_name}</small>
                                <small>KES ${test.cost.toFixed(2)}</small>
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                $('#selectedTestsList').html(html);
                $('#submitBtn').prop('disabled', false);
            } else {
                $('#selectedTestsList').html('<p class="text-center opacity-75">No tests selected</p>');
                $('#submitBtn').prop('disabled', true);
            }
            
            $('#totalTests').text(selectedTests.length);
            $('#totalCost').text('KES ' + totalCost.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
            $('#selectedTestsData').val(JSON.stringify(selectedTests));
        }

        function clearSelection() {
            $('.test-checkbox').prop('checked', false);
            updateSelectedTests();
            
            Swal.fire({
                icon: 'info',
                title: 'Selection Cleared',
                text: 'All tests have been deselected',
                timer: 1500,
                showConfirmButton: false
            });
        }
    </script>
</body>
</html>