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

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'AUDIOLOGIST', 'LAB_TECHNICIAN', 'ENT_DOCTOR', 'ENT_CONSULTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$page_title = "Vestibular Tests";

// Fetch vestibular test orders - check for AUDIOLOGY department with vestibular category
$query = "SELECT 
            lo.order_id,
            lo.order_number,
            lo.order_date,
            lo.status as order_status,
            lo.total_cost,
            lo.paid_amount,
            p.patient_id,
            p.patient_number,
            u.full_name as patient_name,
            u.phone_primary,
            lot.order_test_id,
            lot.status as test_status,
            lot.result_value,
            lot.completed_at,
            tt.test_name,
            tt.test_code,
            tt.cost,
            tt.turnaround_time_hours,
            tech_user.full_name as technician_name,
            doc_user.full_name as ordered_by_name
          FROM lab_orders lo
          INNER JOIN patients p ON lo.patient_id = p.patient_id
          INNER JOIN users u ON p.user_id = u.user_id
          LEFT JOIN lab_order_tests lot ON lo.order_id = lot.order_id
          LEFT JOIN ent_test_types tt ON lot.test_type_id = tt.test_type_id
          LEFT JOIN users tech_user ON lot.tested_by = tech_user.user_id
          LEFT JOIN users doc_user ON lo.ordered_by = doc_user.user_id
          WHERE tt.category = 'AUDIOLOGY'
          ORDER BY lo.order_date DESC, lo.created_at DESC
          LIMIT 100";
$result = mysqli_query($conn, $query);

// Get statistics
$stats_query = "SELECT 
                COUNT(DISTINCT lot.order_test_id) as total_tests,
                COUNT(DISTINCT CASE WHEN lot.status = 'PENDING' THEN lot.order_test_id END) as pending_tests,
                COUNT(DISTINCT CASE WHEN lot.status = 'IN_PROGRESS' THEN lot.order_test_id END) as in_progress_tests,
                COUNT(DISTINCT CASE WHEN lot.status = 'COMPLETED' THEN lot.order_test_id END) as completed_tests,
                SUM(CASE WHEN lot.status = 'COMPLETED' THEN lot.test_cost ELSE 0 END) as total_revenue
                FROM lab_order_tests lot
                INNER JOIN ent_test_types tt ON lot.test_type_id = tt.test_type_id
                WHERE tt.category = 'AUDIOLOGY'";
$stats_result = mysqli_query($conn, $stats_query);
$stats = mysqli_fetch_assoc($stats_result);

// Get available vestibular test types
$test_types_query = "SELECT * FROM ent_test_types 
                     WHERE category = 'AUDIOLOGY' AND is_active = 1 
                     ORDER BY test_name";
$test_types_result = mysqli_query($conn, $test_types_query);

// Get patients
$patients_query = "SELECT p.patient_id, p.patient_number, u.full_name 
                   FROM patients p 
                   INNER JOIN users u ON p.user_id = u.user_id 
                   WHERE p.is_active = 1 
                   ORDER BY u.full_name";
$patients_result = mysqli_query($conn, $patients_query);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            border-left: 4px solid #667eea;
            transition: transform 0.2s;
            margin-bottom: 1.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
            text-transform: uppercase;
        }
        
        .test-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            border-left: 4px solid #10b981;
            transition: all 0.3s;
        }
        
        .status-badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 500;
            text-transform: uppercase;
        }
        
        .status-PENDING {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-IN_PROGRESS, .status-SCHEDULED {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .status-COMPLETED {
            background: #d1fae5;
            color: #065f46;
        }
        
        .patient-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 1.25rem;
        }
        
        .test-type-card {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .test-type-card:hover {
            border-color: #667eea;
            background: #f0f4ff;
        }
        
        .test-type-card.selected {
            border-color: #667eea;
            background: #f0f4ff;
        }
    </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">Vestibular Tests</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">ENT Tests</li>
                                        <li class="breadcrumb-item active">Vestibular</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-wheelchair-line me-2"></i>Vestibular Tests</h4>
                                <p class="mb-0">Balance and vestibular function assessments</p>
                            </div>
                            <button class="btn btn-light btn-lg" onclick="showNewTestModal()">
                                <i class="ri-add-line me-2"></i>Order New Test
                            </button>
                        </div>
                    </div>

                    <!-- Statistics -->
                    <div class="row">
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo $stats['total_tests']; ?></div>
                                <div class="stat-label">Total Tests</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value text-warning"><?php echo $stats['pending_tests']; ?></div>
                                <div class="stat-label">Pending</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value text-info"><?php echo $stats['in_progress_tests']; ?></div>
                                <div class="stat-label">In Progress</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value text-success"><?php echo number_format($stats['total_revenue'], 2); ?></div>
                                <div class="stat-label">Revenue (KES)</div>
                            </div>
                        </div>
                    </div>

                    <!-- Tests List -->
                    <div id="testsList">
                        <?php if(mysqli_num_rows($result) > 0): ?>
                        <?php while($test = mysqli_fetch_assoc($result)): 
                            $initials = strtoupper(substr($test['patient_name'], 0, 1));
                        ?>
                        
                        <div class="test-card">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <div class="d-flex align-items-center gap-3 mb-2">
                                        <div class="patient-avatar"><?php echo $initials; ?></div>
                                        <div>
                                            <h6 class="mb-1"><?php echo htmlspecialchars($test['patient_name']); ?></h6>
                                            <small class="text-muted">#<?php echo htmlspecialchars($test['patient_number']); ?></small>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex align-items-center gap-3 mb-2">
                                        <h6 class="mb-0"><?php echo htmlspecialchars($test['test_name']); ?></h6>
                                        <span class="status-badge status-<?php echo $test['test_status']; ?>">
                                            <?php echo str_replace('_', ' ', $test['test_status']); ?>
                                        </span>
                                    </div>
                                    
                                    <div class="d-flex gap-3 flex-wrap text-muted small">
                                        <span><i class="ri-calendar-line me-1"></i><?php echo date('M d, Y', strtotime($test['order_date'])); ?></span>
                                        <span><i class="ri-time-line me-1"></i><?php echo $test['duration_minutes']; ?> min</span>
                                        <span><i class="ri-money-dollar-circle-line me-1"></i>KES <?php echo number_format($test['base_cost'], 2); ?></span>
                                    </div>
                                </div>
                                
                                <div class="d-flex flex-column gap-2">
                                    <?php if($test['test_status'] == 'PENDING'): ?>
                                    <button onclick="startTest(<?php echo $test['order_test_id']; ?>)" class="btn btn-sm" style="background: #667eea; color: white;">
                                        <i class="ri-play-line"></i> Start
                                    </button>
                                    <?php endif; ?>
                                    <button onclick="viewDetails(<?php echo $test['order_test_id']; ?>)" class="btn btn-outline-secondary btn-sm">
                                        <i class="ri-eye-line"></i> View
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <?php endwhile; ?>
                        <?php else: ?>
                        <div class="text-center py-5">
                            <i class="ri-file-list-line" style="font-size: 4rem; opacity: 0.3;"></i>
                            <p class="text-muted mt-3">No vestibular tests found</p>
                            <button class="btn btn-primary" onclick="showNewTestModal()">Order First Test</button>
                        </div>
                        <?php endif; ?>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- New Test Modal -->
    <div class="modal fade" id="newTestModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Order Vestibular Test</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="newTestForm">
                    <input type="hidden" name="test_type" value="vestibular">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Select Patient <span class="text-danger">*</span></label>
                            <select class="form-select select2" name="patient_id" required>
                                <option value="">Choose patient...</option>
                                <?php while($patient = mysqli_fetch_assoc($patients_result)): ?>
                                <option value="<?php echo $patient['patient_id']; ?>">
                                    <?php echo htmlspecialchars($patient['full_name']); ?> - #<?php echo $patient['patient_number']; ?>
                                </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Select Tests <span class="text-danger">*</span></label>
                            <?php if(mysqli_num_rows($test_types_result) > 0): ?>
                            <div id="testTypesList">
                                <?php while($test_type = mysqli_fetch_assoc($test_types_result)): ?>
                                <div class="test-type-card" onclick="toggleTestType(this)">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="test_types[]" 
                                               value="<?php echo $test_type['test_type_id']; ?>" 
                                               data-cost="<?php echo $test_type['base_cost']; ?>">
                                        <label class="form-check-label flex-grow-1">
                                            <strong><?php echo htmlspecialchars($test_type['test_name']); ?></strong>
                                            <span class="float-end text-primary">KES <?php echo number_format($test_type['base_cost'], 2); ?></span>
                                            <br>
                                            <small class="text-muted"><?php echo htmlspecialchars($test_type['description']); ?></small>
                                        </label>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                            <?php else: ?>
                            <div class="alert alert-warning">
                                No vestibular test types available. <a href="add_test_type.php">Add new test type</a>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="alert alert-info">
                            <div class="d-flex justify-content-between">
                                <strong>Total Cost:</strong>
                                <strong class="text-primary" id="totalCost">KES 0.00</strong>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" style="background: #667eea; border: none;">
                            <i class="ri-save-line me-2"></i>Create Order
                        </button>
                    </div>
                </form>
            </div>
        </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/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/js/app.js"></script>

    <script>
        $('.select2').select2({
            dropdownParent: $('#newTestModal'),
            width: '100%'
        });
        
        function showNewTestModal() {
            var modal = new bootstrap.Modal(document.getElementById('newTestModal'));
            modal.show();
        }
        
        function toggleTestType(card) {
            $(card).toggleClass('selected');
            const checkbox = $(card).find('input[type="checkbox"]');
            checkbox.prop('checked', !checkbox.prop('checked'));
            calculateTotal();
        }
        
        function calculateTotal() {
            let total = 0;
            $('input[name="test_types[]"]:checked').each(function() {
                total += parseFloat($(this).data('cost'));
            });
            $('#totalCost').text('KES ' + total.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
        }
        
        $('#newTestForm').on('submit', function(e) {
            e.preventDefault();
            
            $.ajax({
                url: 'actions/create_audiometry_order.php',
                method: 'POST',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        Swal.fire('Success!', response.message, 'success')
                        .then(() => location.reload());
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                }
            });
        });
        
        function startTest(testId) {
            $.ajax({
                url: 'actions/update_test_status.php',
                method: 'POST',
                data: { order_test_id: testId, status: 'IN_PROGRESS' },
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        location.reload();
                    }
                }
            });
        }
        
        function viewDetails(testId) {
            window.location.href = 'view_test_details.php?test_id=' + testId;
        }
    </script>
</body>
</html>