<?php
/**
 * Balance Assessment Page
 * Audiologist Role - Vestibular Function Testing
 */

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 = "Balance Assessment";
$user_id = $_SESSION['user_id'];

// Get statistics for balance/vestibular tests
$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 '%Balance%' OR ett.test_name LIKE '%Vestibular%')
              AND lot.tested_by = ?";
$stmt = $conn->prepare($stats_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stats = $stmt->get_result()->fetch_assoc();

// Get balance assessment tests
$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 '%Balance%' OR ett.test_name LIKE '%Vestibular%')
              ORDER BY 
                CASE lot.status 
                    WHEN 'IN_PROGRESS' THEN 1
                    WHEN 'SCHEDULED' THEN 2
                    WHEN 'PENDING' THEN 3
                    WHEN 'COMPLETED' THEN 4
                    ELSE 5
                END,
                CASE lo.priority
                    WHEN 'STAT' THEN 1
                    WHEN 'URGENT' THEN 2
                    WHEN 'ROUTINE' THEN 3
                    ELSE 4
                END,
                lot.scheduled_at ASC,
                lot.created_at DESC";
$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" type="text/css" />
    <link href="assets/libs/datatables.net-responsive-bs5/css/responsive.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <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: #fef3c7;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            border-left: 4px solid #f59e0b;
        }
        
        .alert-warning-custom {
            background: #fffbeb;
            border: 1px solid #fef3c7;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
    </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-anticlockwise-line me-2" style="color: #2d7a2d;"></i>Balance & Vestibular Assessment</h4>
                                <p class="mb-0">Evaluate vestibular system function and balance disorders</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="alert-warning-custom">
                        <h6 class="mb-2"><i class="ri-alert-line me-1"></i> Safety Protocol</h6>
                        <small>Ensure fall prevention measures are in place. Patient may experience dizziness or nausea during testing. Have assistant available.</small>
                    </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>Balance Assessment 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">
                                        Comprehensive vestibular assessment includes clinical balance tests, positional testing, 
                                        and evaluation of vestibulo-ocular reflex. Used to diagnose BPPV, vestibular neuritis, and other balance disorders.
                                    </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>Test Type</th>
                                                <th>Chief Complaint</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><small><?php echo htmlspecialchars($test['test_name']); ?></small></td>
                                                        <td>
                                                            <small class="text-muted">
                                                                <?php 
                                                                if ($test['clinical_notes']) {
                                                                    echo htmlspecialchars(substr($test['clinical_notes'], 0, 30));
                                                                    if (strlen($test['clinical_notes']) > 30) echo '...';
                                                                } else {
                                                                    echo '—';
                                                                }
                                                                ?>
                                                            </small>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($test['doctor_name'] ?? 'N/A'); ?></td>
                                                        <td>
                                                            <?php
                                                            $priority_badges = [
                                                                'STAT' => 'badge-stat',
                                                                'URGENT' => 'badge-urgent',
                                                                'ROUTINE' => 'badge-routine'
                                                            ];
                                                            $badge_class = $priority_badges[$test['priority']] ?? 'badge-routine';
                                                            ?>
                                                            <span class="badge <?php echo $badge_class; ?>">
                                                                <?php echo htmlspecialchars($test['priority']); ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <?php
                                                            if ($test['scheduled_at']) {
                                                                echo date('M j, Y g:i A', strtotime($test['scheduled_at']));
                                                            } else {
                                                                echo '<span class="text-muted">Not Scheduled</span>';
                                                            }
                                                            ?>
                                                        </td>
                                                        <td>
                                                            <?php
                                                            $status_badges = [
                                                                'PENDING' => 'badge-pending',
                                                                'SCHEDULED' => 'badge-scheduled',
                                                                'IN_PROGRESS' => 'badge-in-progress',
                                                                'COMPLETED' => 'badge-completed'
                                                            ];
                                                            $badge_class = $status_badges[$test['status']] ?? 'badge-pending';
                                                            ?>
                                                            <span class="badge <?php echo $badge_class; ?>">
                                                                <?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 Results
                                                                    </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="10" class="text-center">No balance assessment 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/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
    <script src="assets/libs/datatables.net-responsive-bs5/js/responsive.bootstrap5.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            $('#testsTable').DataTable({
                responsive: true,
                order: [[8, 'asc']],
                pageLength: 25,
                language: {
                    search: "_INPUT_",
                    searchPlaceholder: "Search tests..."
                }
            });
        });
        
        function startTest(orderTestId) {
            Swal.fire({
                title: 'Start Balance Assessment?',
                html: 'Mark this test as in progress.<br><small class="text-muted">Ensure safety protocols are in place and assistant is available.</small>',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#2d7a2d',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Start Test'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/start_audio_test.php',
                        method: 'POST',
                        data: { order_test_id: orderTestId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Test Started',
                                    text: response.message,
                                    confirmButtonColor: '#2d7a2d'
                                }).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: response.message,
                                    confirmButtonColor: '#dc3545'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'Failed to start test. Please try again.',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    });
                }
            });
        }
        
        function recordResults(orderTestId) {
            window.location.href = 'record_vestibular_results.php?test_id=' + orderTestId + '&type=balance';
        }
        
        function viewResults(orderTestId) {
            window.location.href = 'view_vestibular_results.php?test_id=' + orderTestId;
        }
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>