<?php
/**
 * VNG (Videonystagmography) Testing Page
 * Audiologist Role - Eye Movement & Vestibular 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 = "VNG 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 '%VNG%'
              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.result_files, lot.abnormal_flag,
                     lo.order_number, lo.patient_id, lo.priority, lo.clinical_notes,
                     p.patient_number, u.full_name as patient_name, u.phone, u.email, u.date_of_birth,
                     d.user_id as doctor_user_id, du.full_name as doctor_name,
                     ett.test_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 '%VNG%'
              ORDER BY 
                CASE lot.status 
                    WHEN 'IN_PROGRESS' THEN 1
                    WHEN 'SCHEDULED' THEN 2
                    WHEN 'PENDING' THEN 3
                    WHEN 'COMPLETED' THEN 4
                END,
                CASE lo.priority
                    WHEN 'STAT' THEN 1
                    WHEN 'URGENT' THEN 2
                    WHEN 'ROUTINE' THEN 3
                END,
                lot.scheduled_at ASC";
$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 0 rgba(0, 0, 0, 0.1); border: 1px solid #e2e8f0; margin-bottom: 1.5rem; }
        .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; text-align: center; height: 100%; }
        .stat-value { font-size: 2rem; font-weight: 700; color: #1e293b; margin-bottom: 0.5rem; }
        .stat-label { color: #64748b; font-size: 0.875rem; }
        .info-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; margin-bottom: 1.5rem; }
        .info-card h5 { font-size: 1.125rem; font-weight: 600; color: #1e293b; margin-bottom: 1.25rem; padding-bottom: 0.75rem; border-bottom: 2px solid #e2e8f0; }
        .badge-pending { background: #fef3c7; color: #92400e; }
        .badge-scheduled { background: #dbeafe; color: #1e40af; }
        .badge-in-progress { background: #ddd6fe; color: #5b21b6; }
        .badge-completed { background: #d1fae5; color: #065f46; }
        .badge-stat { background: #fee2e2; color: #991b1b; }
        .badge-urgent { background: #fed7aa; color: #9a3412; }
        .badge-routine { background: #e0e7ff; color: #3730a3; }
        .test-info-box { background: #f3e8ff; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; border-left: 4px solid #8b5cf6; }
    </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">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-eye-line me-2" style="color: #2d7a2d;"></i>Videonystagmography Testing</h4>
                                <p class="mb-0">Evaluate eye movements and vestibulo-ocular reflex through video recording</p>
                            </div>
                        </div>
                    </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 Tests</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">Completed 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>VNG 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">
                                        VNG uses infrared video to record eye movements during various vestibular stimuli. 
                                        Includes oculomotor testing, positional testing, and caloric stimulation.
                                    </small>
                                </div>
                                
                                <div class="table-responsive">
                                    <table id="testsTable" class="table table-striped table-hover nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Order #</th>
                                                <th>Patient</th>
                                                <th>Age</th>
                                                <th>Ordered By</th>
                                                <th>Priority</th>
                                                <th>Scheduled</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($tests_result->num_rows > 0): ?>
                                                <?php while ($test = $tests_result->fetch_assoc()): 
                                                    $age = null;
                                                    if ($test['date_of_birth']) {
                                                        $dob = new DateTime($test['date_of_birth']);
                                                        $now = new DateTime();
                                                        $age = $now->diff($dob)->y;
                                                    }
                                                ?>
                                                    <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 $age !== null ? $age . ' yrs' : 'N/A'; ?></td>
                                                        <td><?php echo htmlspecialchars($test['doctor_name'] ?? 'N/A'); ?></td>
                                                        <td>
                                                            <span class="badge badge-<?php echo strtolower($test['priority']) == 'stat' ? 'stat' : (strtolower($test['priority']) == 'urgent' ? 'urgent' : 'routine'); ?>">
                                                                <?php echo htmlspecialchars($test['priority']); ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <?php echo $test['scheduled_at'] ? date('M j, Y g:i A', strtotime($test['scheduled_at'])) : '<span class="text-muted">Not Scheduled</span>'; ?>
                                                        </td>
                                                        <td>
                                                            <span class="badge badge-<?php echo strtolower(str_replace('_', '-', $test['status'])); ?>">
                                                                <?php echo htmlspecialchars($test['status']); ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group">
                                                                <?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-circle-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-file-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; ?>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr><td colspan="8" class="text-center">No VNG tests found</td></tr>
                                            <?php endif; ?>
                                        </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,
                order: [[6, 'asc']],
                pageLength: 25
            });
        });
        
        function startTest(id) {
            Swal.fire({
                title: 'Start VNG Test?',
                html: 'Ensure goggles are properly fitted and patient is comfortable.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#2d7a2d',
                confirmButtonText: 'Yes, Start'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('ajax/start_audio_test.php', {order_test_id: id}, function(res) {
                        if (res.success) {
                            Swal.fire('Test Started', res.message, 'success').then(() => location.reload());
                        } else {
                            Swal.fire('Error', res.message, 'error');
                        }
                    }, 'json');
                }
            });
        }
        
        function recordResults(id) {
            window.location.href = 'record_vng_results.php?test_id=' + id;
        }
        
        function viewResults(id) {
            window.location.href = 'view_vng_results.php?test_id=' + id;
        }
    </script>
    <script src="assets/js/app.js"></script>
</body>
</html>