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

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

$page_title = "Sleep Studies";

// Fetch sleep studies - aligned with ent_test_types schema
$query = "SELECT 
            lo.order_id,
            lo.order_number,
            lo.ordered_at,
            lo.status as order_status,
            lo.total_cost,
            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.scheduled_at,
            lot.test_cost,
            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 = 'SLEEP_STUDY' AND tt.is_active = 1
          ORDER BY lo.ordered_at DESC
          LIMIT 100";
$result = mysqli_query($conn, $query);

// Get statistics
$stats_query = "SELECT 
                COUNT(DISTINCT lot.order_test_id) as total_studies,
                COUNT(DISTINCT CASE WHEN lot.status = 'SCHEDULED' THEN lot.order_test_id END) as scheduled_studies,
                COUNT(DISTINCT CASE WHEN lot.status = 'IN_PROGRESS' THEN lot.order_test_id END) as in_progress_studies,
                COUNT(DISTINCT CASE WHEN lot.status = 'COMPLETED' THEN lot.order_test_id END) as completed_studies,
                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 = 'SLEEP_STUDY' AND tt.is_active = 1";
$stats_result = mysqli_query($conn, $stats_query);
$stats = mysqli_fetch_assoc($stats_result);

// Get available sleep study types
$test_types_query = "SELECT * FROM ent_test_types 
                     WHERE category = 'SLEEP_STUDY' 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" />
    <link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.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;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
            text-transform: uppercase;
        }
        
        .study-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 #a855f7;
            transition: all 0.3s;
        }
        
        .study-card:hover {
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }
        
        .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-SCHEDULED {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .status-IN_PROGRESS {
            background: #e9d5ff;
            color: #6b21a8;
        }
        
        .status-COMPLETED {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-CANCELLED {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .patient-info {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .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-details {
            display: flex;
            gap: 1.5rem;
            flex-wrap: wrap;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #e2e8f0;
        }
        
        .detail-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .detail-item i {
            color: #667eea;
        }
        
        .filter-section {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            margin-bottom: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .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;
        }
        
        .overnight-badge {
            background: #e9d5ff;
            color: #6b21a8;
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 500;
        }
    </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">Sleep Studies</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">Sleep Studies</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-moon-line me-2"></i>Sleep Studies</h4>
                                <p class="mb-0">Polysomnography, sleep apnea testing, and overnight monitoring</p>
                            </div>
                            <button class="btn btn-light btn-lg" onclick="showScheduleModal()">
                                <i class="ri-add-line me-2"></i>Schedule Study
                            </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_studies']; ?></div>
                                <div class="stat-label">Total Studies</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value text-info"><?php echo $stats['scheduled_studies']; ?></div>
                                <div class="stat-label">Scheduled</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value text-warning"><?php echo $stats['in_progress_studies']; ?></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">KES <?php echo number_format($stats['total_revenue'], 2); ?></div>
                                <div class="stat-label">Revenue</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="filter-section">
                        <div class="row">
                            <div class="col-md-6">
                                <select class="form-select" id="statusFilter">
                                    <option value="">All Status</option>
                                    <option value="PENDING">Pending</option>
                                    <option value="SCHEDULED">Scheduled</option>
                                    <option value="IN_PROGRESS">In Progress</option>
                                    <option value="COMPLETED">Completed</option>
                                    <option value="CANCELLED">Cancelled</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-secondary w-100" onclick="resetFilters()">
                                    <i class="ri-refresh-line me-2"></i>Reset Filters
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Studies List -->
                    <div id="studiesList">
                        <?php if(mysqli_num_rows($result) > 0): ?>
                        <?php while($study = mysqli_fetch_assoc($result)): 
                            $initials = strtoupper(substr($study['patient_name'], 0, 1));
                            $is_overnight = ($study['turnaround_time_hours'] >= 8); // 8+ hours considered overnight
                        ?>
                        
                        <div class="study-card" data-status="<?php echo $study['test_status']; ?>">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <div class="patient-info">
                                        <div class="patient-avatar"><?php echo $initials; ?></div>
                                        <div>
                                            <h6 class="mb-1"><?php echo htmlspecialchars($study['patient_name']); ?></h6>
                                            <small class="text-muted">
                                                #<?php echo htmlspecialchars($study['patient_number']); ?> | 
                                                Order: <?php echo htmlspecialchars($study['order_number']); ?>
                                            </small>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex align-items-center gap-3 mb-2 flex-wrap">
                                        <h6 class="mb-0"><?php echo htmlspecialchars($study['test_name']); ?></h6>
                                        <span class="badge bg-secondary"><?php echo htmlspecialchars($study['test_code']); ?></span>
                                        <span class="status-badge status-<?php echo $study['test_status']; ?>">
                                            <?php echo str_replace('_', ' ', $study['test_status']); ?>
                                        </span>
                                        <?php if($is_overnight): ?>
                                        <span class="overnight-badge">
                                            <i class="ri-moon-line me-1"></i>Overnight Study
                                        </span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="test-details">
                                        <div class="detail-item">
                                            <i class="ri-calendar-line"></i>
                                            <?php echo date('M d, Y', strtotime($study['ordered_at'])); ?>
                                        </div>
                                        <?php if($study['scheduled_at']): ?>
                                        <div class="detail-item">
                                            <i class="ri-time-line"></i>
                                            Scheduled: <?php echo date('M d, Y h:i A', strtotime($study['scheduled_at'])); ?>
                                        </div>
                                        <?php endif; ?>
                                        <div class="detail-item">
                                            <i class="ri-hourglass-line"></i>
                                            <?php echo $study['turnaround_time_hours']; ?> hours
                                        </div>
                                        <div class="detail-item">
                                            <i class="ri-money-dollar-circle-line"></i>
                                            <strong>KES <?php echo number_format($study['test_cost'], 2); ?></strong>
                                        </div>
                                        <?php if($study['technician_name']): ?>
                                        <div class="detail-item">
                                            <i class="ri-user-line"></i>
                                            <?php echo htmlspecialchars($study['technician_name']); ?>
                                        </div>
                                        <?php endif; ?>
                                        <?php if($study['ordered_by_name']): ?>
                                        <div class="detail-item">
                                            <i class="ri-stethoscope-line"></i>
                                            Dr. <?php echo htmlspecialchars($study['ordered_by_name']); ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="d-flex flex-column gap-2" style="min-width: 120px;">
                                    <?php if($study['test_status'] == 'SCHEDULED'): ?>
                                    <button onclick="startStudy(<?php echo $study['order_test_id']; ?>)" 
                                            class="btn btn-sm" style="background: #667eea; color: white;">
                                        <i class="ri-play-line"></i> Start Study
                                    </button>
                                    <?php endif; ?>
                                    
                                    <button onclick="viewStudyDetails(<?php echo $study['order_test_id']; ?>)" 
                                            class="btn btn-outline-secondary btn-sm">
                                        <i class="ri-eye-line"></i> View
                                    </button>
                                    
                                    <?php if($study['test_status'] == 'COMPLETED'): ?>
                                    <button onclick="viewResults(<?php echo $study['order_test_id']; ?>)" 
                                            class="btn btn-outline-primary btn-sm">
                                        <i class="ri-file-text-line"></i> Results
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <?php endwhile; ?>
                        <?php else: ?>
                        <div class="text-center py-5">
                            <i class="ri-moon-line" style="font-size: 4rem; opacity: 0.3;"></i>
                            <p class="text-muted mt-3">No sleep studies found</p>
                            <button class="btn btn-primary" style="background: #667eea; border: none;" onclick="showScheduleModal()">Schedule First Study</button>
                        </div>
                        <?php endif; ?>
                    </div>

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

    <!-- Schedule Study Modal -->
    <div class="modal fade" id="scheduleModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Schedule Sleep Study</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="scheduleForm">
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="ri-information-line me-2"></i>
                            Sleep studies typically require overnight monitoring. Please ensure proper scheduling.
                        </div>
                        
                        <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 Study Type <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['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['cost'], 2); ?></span>
                                            <br>
                                            <small class="text-muted"><?php echo htmlspecialchars($test_type['description']); ?></small>
                                            <?php if($test_type['requires_appointment']): ?>
                                            <br><small class="badge bg-warning text-dark mt-1">Appointment Required</small>
                                            <?php endif; ?>
                                        </label>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                            <?php else: ?>
                            <div class="alert alert-warning">
                                No sleep study types available. <a href="add_test_type.php">Add new study type</a>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Study Date <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="study_date" id="studyDate" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Start Time <span class="text-danger">*</span></label>
                                <input type="time" class="form-control" name="study_time" value="20:00" required>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Clinical Notes</label>
                            <textarea class="form-control" name="clinical_notes" rows="2" 
                                      placeholder="Symptoms, suspected conditions, snoring patterns..."></textarea>
                        </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-calendar-check-line me-2"></i>Schedule Study
                        </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="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="assets/js/app.js"></script>

    <script>
        $('.select2').select2({
            dropdownParent: $('#scheduleModal'),
            width: '100%'
        });
        
        flatpickr("#studyDate", {
            minDate: "today",
            dateFormat: "Y-m-d"
        });
        
        function showScheduleModal() {
            var modal = new bootstrap.Modal(document.getElementById('scheduleModal'));
            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, '$&,'));
        }
        
        $('#scheduleForm').on('submit', function(e) {
            e.preventDefault();
            
            const selectedTests = $('input[name="test_types[]"]:checked').length;
            if(selectedTests === 0) {
                Swal.fire('Error', 'Please select at least one study type', 'error');
                return;
            }
            
            Swal.fire({
                title: 'Scheduling...',
                text: 'Please wait',
                allowOutsideClick: false,
                showConfirmButton: false,
                willOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                url: 'actions/schedule_sleep_study.php',
                method: 'POST',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(response) {
                    Swal.close();
                    if(response.success) {
                        Swal.fire('Success!', response.message, 'success')
                        .then(() => location.reload());
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                },
                error: function() {
                    Swal.close();
                    Swal.fire('Error!', 'Failed to schedule study', 'error');
                }
            });
        });
        
        function startStudy(testId) {
            Swal.fire({
                title: 'Start Sleep Study?',
                text: 'This will mark the study as in progress',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#667eea',
                cancelButtonColor: '#64748b',
                confirmButtonText: 'Yes, start study'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.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) {
                                Swal.fire('Started!', 'Sleep study is now in progress', 'success')
                                .then(() => location.reload());
                            } else {
                                Swal.fire('Error!', response.message, 'error');
                            }
                        }
                    });
                }
            });
        }
        
        function viewStudyDetails(testId) {
            window.location.href = 'view_test_details.php?test_id=' + testId;
        }
        
        function viewResults(testId) {
            window.location.href = 'view_test_results.php?test_id=' + testId;
        }
        
        $('#statusFilter').on('change', function() {
            filterStudies();
        });
        
        function filterStudies() {
            const status = $('#statusFilter').val();
            $('.study-card').each(function() {
                const cardStatus = $(this).data('status');
                const matchesStatus = !status || cardStatus === status;
                $(this).toggle(matchesStatus);
            });
        }
        
        function resetFilters() {
            $('#statusFilter').val('');
            filterStudies();
        }
    </script>
</body>
</html>