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

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

$doctor_id = $_SESSION['user_id'];
$patient_id = $_GET['patient_id'] ?? 0;

// Get patient details if provided
$patient = null;
if ($patient_id > 0) {
    $patient_query = "SELECT p.*, u.full_name, u.phone_primary
                     FROM patients p
                     INNER JOIN users u ON p.user_id = u.user_id
                     WHERE p.patient_id = ?";
    $stmt = $conn->prepare($patient_query);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $patient = $stmt->get_result()->fetch_assoc();
}

// Get test categories from ent_test_types
$categories_query = "SELECT DISTINCT category FROM ent_test_types WHERE is_active = 1 ORDER BY category";
$categories = $conn->query($categories_query);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $conn->begin_transaction();
    
    try {
        $patient_id = $_POST['patient_id'];
        $test_type_ids = $_POST['test_type_ids'] ?? [];
        $priority = $_POST['priority'] ?? 'ROUTINE';
        $clinical_notes = $_POST['clinical_notes'] ?? '';
        $order_type = $_POST['order_type'] ?? 'ROUTINE';
        
        // Validate input
        if (empty($test_type_ids)) {
            throw new Exception("Please select at least one test");
        }
        
        // Generate order number
        $year = date('Y');
        $sql_count = "SELECT COUNT(*) as count FROM lab_orders WHERE YEAR(order_date) = YEAR(CURDATE())";
        $count_result = $conn->query($sql_count);
        $count = $count_result->fetch_assoc()['count'] + 1;
        $order_number = 'LAB' . $year . str_pad($count, 5, '0', STR_PAD_LEFT);
        
        // Insert lab order
        $order_sql = "INSERT INTO lab_orders (
            order_number, patient_id, ordered_by, order_date, order_type, 
            priority, clinical_notes, status
        ) VALUES (?, ?, ?, CURDATE(), ?, ?, ?, 'PENDING')";
        
        $order_stmt = $conn->prepare($order_sql);
        $order_stmt->bind_param("siisss", 
            $order_number, $patient_id, $doctor_id, 
            $order_type, $priority, $clinical_notes
        );
        $order_stmt->execute();
        $order_id = $conn->insert_id;
        
        // Insert lab order tests
        foreach ($test_type_ids as $test_type_id) {
            // Get test cost
            $cost_query = "SELECT cost FROM ent_test_types WHERE test_type_id = ?";
            $cost_stmt = $conn->prepare($cost_query);
            $cost_stmt->bind_param("i", $test_type_id);
            $cost_stmt->execute();
            $test_cost = $cost_stmt->get_result()->fetch_assoc()['cost'];
            
            $item_sql = "INSERT INTO lab_order_tests (order_id, test_type_id, test_cost, status) 
                        VALUES (?, ?, ?, 'PENDING')";
            $item_stmt = $conn->prepare($item_sql);
            $item_stmt->bind_param("iid", $order_id, $test_type_id, $test_cost);
            $item_stmt->execute();
        }
        
        // Log activity
        $action = "CREATE";
        $module = "LAB_ORDERS";
        $ip_address = $_SERVER['REMOTE_ADDR'];
        
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, ip_address) 
                    VALUES (?, ?, ?, ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("issis", $_SESSION['user_id'], $action, $module, $order_id, $ip_address);
        $log_stmt->execute();
        
        $conn->commit();
        
        $_SESSION['success_message'] = "Lab tests ordered successfully! Order Number: " . $order_number;
        header('Location: my_lab_orders.php');
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = "Error ordering tests: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Order Lab Tests')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
</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">Order Lab Tests</h4>
                                <div class="page-title-right">
                                    <a href="my_lab_orders.php" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line"></i> Back to Lab Orders
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <form method="POST" id="orderTestsForm">
                        <div class="row">
                            <div class="col-lg-8">
                                <div class="card">
                                    <div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                                        <h5 class="card-title mb-0 text-white">
                                            <i class="ri-test-tube-line me-2"></i>Test Order Details
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label">Patient <span class="text-danger">*</span></label>
                                                <select class="form-select select2" name="patient_id" id="patientSelect" required <?php echo $patient ? 'disabled' : ''; ?>>
                                                    <option value="">Select Patient</option>
                                                    <?php if ($patient): ?>
                                                        <option value="<?php echo $patient['patient_id']; ?>" selected>
                                                            <?php echo htmlspecialchars($patient['full_name']); ?> (<?php echo $patient['patient_number']; ?>)
                                                        </option>
                                                    <?php endif; ?>
                                                </select>
                                                <?php if ($patient): ?>
                                                    <input type="hidden" name="patient_id" value="<?php echo $patient['patient_id']; ?>">
                                                <?php endif; ?>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Order Type <span class="text-danger">*</span></label>
                                                <select class="form-select" name="order_type" required>
                                                    <option value="ROUTINE">Routine</option>
                                                    <option value="URGENT">Urgent</option>
                                                    <option value="EMERGENCY">Emergency</option>
                                                </select>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Priority <span class="text-danger">*</span></label>
                                                <select class="form-select" name="priority" required>
                                                    <option value="ROUTINE">Routine</option>
                                                    <option value="URGENT">Urgent</option>
                                                    <option value="STAT">STAT (Immediate)</option>
                                                </select>
                                            </div>

                                            <div class="col-md-12 mb-3">
                                                <label class="form-label">Clinical Notes / Indication</label>
                                                <textarea class="form-control" name="clinical_notes" rows="3"
                                                          placeholder="Clinical indication for tests, relevant symptoms, provisional diagnosis..."></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Test Selection -->
                                <div class="card">
                                    <div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                                        <h5 class="card-title mb-0 text-white">
                                            <i class="ri-flask-line me-2"></i>Select Tests <span class="text-danger">*</span>
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <input type="text" class="form-control" id="searchTests" 
                                                   placeholder="Search tests by name or code...">
                                        </div>

                                        <div class="accordion" id="testCategories">
                                            <?php 
                                            $categories->data_seek(0);
                                            $index = 0;
                                            while($category = $categories->fetch_assoc()): 
                                                $category_name = $category['category'];
                                                
                                                // Get tests in this category
                                                $tests_query = "SELECT * FROM ent_test_types 
                                                               WHERE category = ? AND is_active = 1 
                                                               ORDER BY test_name";
                                                $tests_stmt = $conn->prepare($tests_query);
                                                $tests_stmt->bind_param("s", $category_name);
                                                $tests_stmt->execute();
                                                $tests = $tests_stmt->get_result();
                                            ?>
                                                <div class="accordion-item">
                                                    <h2 class="accordion-header" id="heading<?php echo $index; ?>">
                                                        <button class="accordion-button <?php echo $index > 0 ? 'collapsed' : ''; ?>" type="button" 
                                                                data-bs-toggle="collapse" data-bs-target="#collapse<?php echo $index; ?>">
                                                            <?php echo htmlspecialchars($category_name); ?>
                                                            <span class="badge bg-primary ms-2"><?php echo $tests->num_rows; ?> tests</span>
                                                        </button>
                                                    </h2>
                                                    <div id="collapse<?php echo $index; ?>" class="accordion-collapse collapse <?php echo $index === 0 ? 'show' : ''; ?>">
                                                        <div class="accordion-body">
                                                            <div class="row">
                                                                <?php while($test = $tests->fetch_assoc()): ?>
                                                                    <div class="col-md-6 mb-2">
                                                                        <div class="form-check">
                                                                            <input class="form-check-input test-checkbox" type="checkbox" 
                                                                                   name="test_type_ids[]" value="<?php echo $test['test_type_id']; ?>" 
                                                                                   id="test<?php echo $test['test_type_id']; ?>"
                                                                                   data-name="<?php echo strtolower($test['test_name']); ?>"
                                                                                   data-code="<?php echo strtolower($test['test_code']); ?>"
                                                                                   data-price="<?php echo $test['cost']; ?>">
                                                                            <label class="form-check-label" for="test<?php echo $test['test_type_id']; ?>">
                                                                                <strong><?php echo htmlspecialchars($test['test_name']); ?></strong><br>
                                                                                <small class="text-muted">Code: <?php echo $test['test_code']; ?> | KES <?php echo number_format($test['cost'], 2); ?></small>
                                                                            </label>
                                                                        </div>
                                                                    </div>
                                                                <?php endwhile; ?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php 
                                            $index++;
                                            endwhile; 
                                            ?>
                                        </div>

                                        <div class="alert alert-danger mt-3" id="noTestsAlert" style="display: none;">
                                            <i class="ri-error-warning-line me-2"></i>No tests selected. Please select at least one test.
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-4">
                                <!-- Selected Tests Summary -->
                                <div class="card">
                                    <div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                                        <h5 class="card-title mb-0 text-white">
                                            <i class="ri-file-list-line me-2"></i>Order Summary
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div id="selectedTestsSummary">
                                            <p class="text-muted"><i>No tests selected</i></p>
                                        </div>
                                        <hr>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong>Total Cost:</strong>
                                            <h4 class="mb-0 text-primary" id="totalCost">KES 0.00</h4>
                                        </div>
                                    </div>
                                </div>

                                <!-- Submit Button -->
                                <div class="card">
                                    <div class="card-body">
                                        <div class="d-grid gap-2">
                                            <button type="submit" class="btn btn-success btn-lg">
                                                <i class="ri-test-tube-line me-1"></i> Submit Lab Order
                                            </button>
                                            <a href="my_lab_orders.php" class="btn btn-secondary btn-lg">
                                                <i class="ri-close-line me-1"></i> Cancel
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/select2/js/select2.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            console.log('Order tests page loaded');
            
            $('.select2').select2({
                width: '100%'
            });

            // Load patients if not pre-selected
            <?php if (!$patient): ?>
            $.ajax({
                url: 'ajax/get_doctor_patients.php',
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.results) {
                        response.results.forEach(function(patient) {
                            $('#patientSelect').append(
                                '<option value="' + patient.patient_id + '">' + 
                                patient.full_name + ' (' + patient.patient_number + ')' +
                                '</option>'
                            );
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Failed to load patients:', error);
                }
            });
            <?php endif; ?>

            // Search tests
            $('#searchTests').on('keyup', function() {
                var searchTerm = $(this).val().toLowerCase();
                console.log('Searching for:', searchTerm);
                
                $('.test-checkbox').each(function() {
                    var testName = $(this).data('name') || '';
                    var testCode = $(this).data('code') || '';
                    var parentDiv = $(this).closest('.col-md-6');
                    
                    if (testName.includes(searchTerm) || testCode.includes(searchTerm)) {
                        parentDiv.show();
                    } else {
                        parentDiv.hide();
                    }
                });
            });

            // Update summary when tests are selected - Use event delegation for dynamically loaded content
            $(document).on('change', '.test-checkbox', function() {
                console.log('Checkbox changed:', $(this).attr('id'), 'Checked:', $(this).is(':checked'));
                updateSummary();
            });
            
            // Initialize summary on page load
            updateSummary();
            
            // Also trigger update when accordion is opened (in case tests load dynamically)
            $('.accordion-button').on('click', function() {
                setTimeout(updateSummary, 100);
            });

            function updateSummary() {
                var selectedTests = [];
                var totalCost = 0;
                
                $('.test-checkbox:checked').each(function() {
                    var checkbox = $(this);
                    var testId = checkbox.val();
                    var label = $('label[for="' + checkbox.attr('id') + '"]');
                    
                    // Get test name and price
                    var testName = label.find('strong').text() || label.text().split('Code:')[0].trim();
                    var price = parseFloat(checkbox.data('price')) || 0;
                    
                    selectedTests.push({
                        id: testId,
                        name: testName,
                        price: price
                    });
                    totalCost += price;
                });
                
                if (selectedTests.length > 0) {
                    var html = '<div class="list-group list-group-flush">';
                    selectedTests.forEach(function(test, index) {
                        html += '<div class="list-group-item px-0 py-2 border-0">';
                        html += '<div class="d-flex justify-content-between align-items-start">';
                        html += '<div class="flex-grow-1">';
                        html += '<i class="ri-checkbox-circle-line text-success me-2"></i>';
                        html += '<small>' + test.name + '</small>';
                        html += '</div>';
                        html += '<div class="text-end">';
                        html += '<small class="text-muted">KES ' + test.price.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + '</small>';
                        html += '</div>';
                        html += '</div>';
                        html += '</div>';
                    });
                    html += '</div>';
                    
                    $('#selectedTestsSummary').html(html);
                    $('#totalCost').text('KES ' + totalCost.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
                    $('#noTestsAlert').hide();
                } else {
                    $('#selectedTestsSummary').html('<p class="text-muted mb-0"><i>No tests selected</i></p>');
                    $('#totalCost').text('KES 0.00');
                }
                
                // Log for debugging
                console.log('Selected tests:', selectedTests);
                console.log('Total cost:', totalCost);
            }

            // Form validation
            $('#orderTestsForm').on('submit', function(e) {
                var selectedTests = $('.test-checkbox:checked').length;
                
                if (selectedTests === 0) {
                    e.preventDefault();
                    $('#noTestsAlert').show();
                    $('html, body').animate({
                        scrollTop: $('#noTestsAlert').offset().top - 100
                    }, 500);
                    return false;
                }
            });

            <?php if(isset($_SESSION['error_message'])): ?>
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: '<?php echo addslashes($_SESSION['error_message']); ?>',
                    confirmButtonColor: '#764ba2'
                });
                <?php unset($_SESSION['error_message']); ?>
            <?php endif; ?>
        });
    </script>
</body>
</html>