<?php
/**
 * VEMP (Vestibular Evoked Myogenic Potentials) Testing Page
 * Audiologist Role - Otolith Function Assessment
 */

require_once 'layouts/session.php';
require_once 'layouts/dbconn.php';

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

$page_title = "VEMP Testing";
$user_id = $_SESSION['user_id'];

$stats_sql = "SELECT 
                COUNT(CASE WHEN lot.status = 'PENDING' THEN 1 END) as pending_tests,
                COUNT(CASE WHEN lot.status = 'IN_PROGRESS' THEN 1 END) as in_progress_tests,
                COUNT(CASE WHEN lot.status = 'COMPLETED' AND DATE(lot.completed_at) = CURDATE() THEN 1 END) as completed_today,
                COUNT(CASE WHEN lot.status = 'COMPLETED' AND MONTH(lot.completed_at) = MONTH(CURDATE()) THEN 1 END) as completed_month
              FROM lab_order_tests lot
              INNER JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
              WHERE ett.test_name LIKE '%VEMP%'
              AND lot.tested_by = ?";
$stmt = $conn->prepare($stats_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stats = $stmt->get_result()->fetch_assoc();

$tests_sql = "SELECT lot.order_test_id, lot.order_id, lot.status, lot.scheduled_at, lot.started_at, 
                     lot.completed_at, lot.result_value, lot.abnormal_flag,
                     lo.order_number, lo.patient_id, lo.priority, lo.clinical_notes,
                     p.patient_number, u.full_name as patient_name, u.date_of_birth,
                     du.full_name as doctor_name
              FROM lab_order_tests lot
              INNER JOIN lab_orders lo ON lot.order_id = lo.order_id
              INNER JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
              INNER JOIN patients p ON lo.patient_id = p.patient_id
              INNER JOIN users u ON p.user_id = u.user_id
              LEFT JOIN doctors d ON lo.ordered_by = d.doctor_id
              LEFT JOIN users du ON d.user_id = du.user_id
              WHERE ett.test_name LIKE '%VEMP%'
              ORDER BY lot.status, lo.priority, lot.scheduled_at";
$tests_result = $conn->query($tests_sql);
?>

<?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/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .page-header { background: white; padding: 1.5rem; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 1.5rem; }
        .stat-card { background: white; border-radius: 12px; padding: 1.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1); text-align: center; }
        .stat-value { font-size: 2rem; font-weight: 700; margin-bottom: 0.5rem; }
        .info-card { background: white; border-radius: 12px; padding: 1.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 1.5rem; }
        .info-card h5 { font-size: 1.125rem; font-weight: 600; margin-bottom: 1.25rem; padding-bottom: 0.75rem; border-bottom: 2px solid #e2e8f0; }
        .test-info-box { background: #ecfdf5; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; border-left: 4px solid #10b981; }
    </style>
</head>
<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <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"><?php echo $page_title; ?></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">Vestibular Tests</li>
                                        <li class="breadcrumb-item active"><?php echo $page_title; ?></li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="page-header">
                        <h4><i class="ri-sound-module-line me-2" style="color: #2d7a2d;"></i>Vestibular Evoked Myogenic Potentials</h4>
                        <p class="mb-0">Assess saccule (cVEMP) and utricle (oVEMP) function through muscle responses</p>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #f59e0b;"><?php echo $stats['pending_tests']; ?></div>
                                <div class="stat-label">Pending</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #8b5cf6;"><?php echo $stats['in_progress_tests']; ?></div>
                                <div class="stat-label">In Progress</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #10b981;"><?php echo $stats['completed_today']; ?></div>
                                <div class="stat-label">Today</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #2d7a2d;"><?php echo $stats['completed_month']; ?></div>
                                <div class="stat-label">This Month</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-12">
                            <div class="info-card">
                                <h5><i class="ri-file-list-3-line me-2"></i>VEMP Tests</h5>
                                
                                <div class="test-info-box">
                                    <h6 class="mb-2"><i class="ri-information-line me-1"></i> Test Information</h6>
                                    <small class="text-muted">
                                        cVEMP measures saccule function via SCM muscle response. oVEMP measures utricle function via eye muscle response. 
                                        Important for diagnosing superior canal dehiscence and other otolith disorders.
                                    </small>
                                </div>
                                
                                <div class="table-responsive">
                                    <table id="testsTable" class="table table-striped nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Order #</th>
                                                <th>Patient</th>
                                                <th>Ordered By</th>
                                                <th>Priority</th>
                                                <th>Scheduled</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($test = $tests_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><strong><?php echo htmlspecialchars($test['order_number']); ?></strong></td>
                                                    <td>
                                                        <div><strong><?php echo htmlspecialchars($test['patient_name']); ?></strong></div>
                                                        <small class="text-muted"><?php echo htmlspecialchars($test['patient_number']); ?></small>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($test['doctor_name'] ?? 'N/A'); ?></td>
                                                    <td><span class="badge bg-<?php echo $test['priority'] == 'STAT' ? 'danger' : ($test['priority'] == 'URGENT' ? 'warning' : 'info'); ?>"><?php echo $test['priority']; ?></span></td>
                                                    <td><?php echo $test['scheduled_at'] ? date('M j, g:i A', strtotime($test['scheduled_at'])) : '—'; ?></td>
                                                    <td><span class="badge bg-<?php echo $test['status'] == 'COMPLETED' ? 'success' : ($test['status'] == 'IN_PROGRESS' ? 'primary' : 'secondary'); ?>"><?php echo $test['status']; ?></span></td>
                                                    <td>
                                                        <?php if ($test['status'] == 'PENDING' || $test['status'] == 'SCHEDULED'): ?>
                                                            <button class="btn btn-sm btn-success" onclick="startTest(<?php echo $test['order_test_id']; ?>)"><i class="ri-play-line"></i> Start</button>
                                                        <?php elseif ($test['status'] == 'IN_PROGRESS'): ?>
                                                            <button class="btn btn-sm btn-primary" onclick="recordResults(<?php echo $test['order_test_id']; ?>)"><i class="ri-edit-line"></i> Record</button>
                                                        <?php else: ?>
                                                            <button class="btn btn-sm btn-info" onclick="viewResults(<?php echo $test['order_test_id']; ?>)"><i class="ri-eye-line"></i> View</button>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script>
        $(document).ready(function() { $('#testsTable').DataTable({ responsive: true, pageLength: 25 }); });
        function startTest(id) {
            Swal.fire({
                title: 'Start VEMP Test?',
                html: 'Ensure electrodes are properly placed. Patient should maintain muscle contraction during cVEMP.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#2d7a2d',
                confirmButtonText: 'Start Test'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('ajax/start_audio_test.php', {order_test_id: id}, function(res) {
                        if (res.success) Swal.fire('Started', res.message, 'success').then(() => location.reload());
                        else Swal.fire('Error', res.message, 'error');
                    }, 'json');
                }
            });
        }
        function recordResults(id) { window.location.href = 'record_vestibular_results.php?test_id=' + id + '&type=vemp'; }
        function viewResults(id) { window.location.href = 'view_vestibular_results.php?test_id=' + id; }
    </script>
    <script src="assets/js/app.js"></script>
</body>
</html>