<?php
/**
 * Scheduled Tests Page
 * Audiologist Role - View All Scheduled Tests
 */

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

// Get all scheduled tests for this audiologist
$tests_sql = "SELECT lot.order_test_id, lot.order_id, lot.status, lot.scheduled_at, lot.test_cost,
                     lo.order_number, lo.patient_id, lo.priority, lo.clinical_notes,
                     p.patient_number, u.full_name as patient_name, u.phone, u.email,
                     d.user_id as doctor_user_id, du.full_name as doctor_name,
                     ett.test_name, ett.category, ett.test_code
              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 (lot.status = 'SCHEDULED' OR lot.status = 'PENDING')
              AND ett.category IN ('AUDIOMETRY')
              AND (lot.tested_by = ? OR lot.tested_by IS NULL)
              ORDER BY lot.scheduled_at ASC, lo.priority DESC, lot.created_at DESC";
$stmt = $conn->prepare($tests_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$tests_result = $stmt->get_result();

// Get today's schedule count
$today_sql = "SELECT COUNT(*) as today_count 
              FROM lab_order_tests lot
              INNER JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
              WHERE DATE(lot.scheduled_at) = CURDATE()
              AND lot.status = 'SCHEDULED'
              AND ett.category IN ('AUDIOMETRY')
              AND (lot.tested_by = ? OR lot.tested_by IS NULL)";
$stmt = $conn->prepare($today_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$today_count = $stmt->get_result()->fetch_assoc()['today_count'];

// Get week schedule count
$week_sql = "SELECT COUNT(*) as week_count 
             FROM lab_order_tests lot
             INNER JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
             WHERE YEARWEEK(lot.scheduled_at) = YEARWEEK(CURDATE())
             AND lot.status = 'SCHEDULED'
             AND ett.category IN ('AUDIOMETRY')
             AND (lot.tested_by = ? OR lot.tested_by IS NULL)";
$stmt = $conn->prepare($week_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$week_count = $stmt->get_result()->fetch_assoc()['week_count'];
?>

<?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; }
    </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">Test Management</li>
                                        <li class="breadcrumb-item active"><?php echo $page_title; ?></li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="page-header">
                        <h4><i class="ri-calendar-schedule-line me-2" style="color: #2d7a2d;"></i>My Test Schedule</h4>
                        <p class="mb-0">View and manage upcoming audiology tests</p>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-xl-6 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #3b82f6;"><?php echo $today_count; ?></div>
                                <div class="stat-label">Scheduled Today</div>
                            </div>
                        </div>
                        <div class="col-xl-6 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #2d7a2d;"><?php echo $week_count; ?></div>
                                <div class="stat-label">Scheduled This Week</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>Upcoming Tests</h5>
                                <div class="table-responsive">
                                    <table id="testsTable" class="table table-striped nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Date/Time</th>
                                                <th>Order #</th>
                                                <th>Patient</th>
                                                <th>Contact</th>
                                                <th>Test Type</th>
                                                <th>Ordered By</th>
                                                <th>Priority</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($tests_result->num_rows > 0): ?>
                                                <?php while ($test = $tests_result->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <?php 
                                                            if ($test['scheduled_at']) {
                                                                $scheduled = new DateTime($test['scheduled_at']);
                                                                $now = new DateTime();
                                                                $is_today = $scheduled->format('Y-m-d') == $now->format('Y-m-d');
                                                                echo '<div><strong>' . $scheduled->format('M j, Y') . '</strong></div>';
                                                                echo '<small class="' . ($is_today ? 'text-primary fw-bold' : 'text-muted') . '">' . $scheduled->format('g:i A') . '</small>';
                                                            } else {
                                                                echo '<span class="text-warning">Not Scheduled</span>';
                                                            }
                                                            ?>
                                                        </td>
                                                        <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>
                                                            <small class="text-muted"><?php echo htmlspecialchars($test['phone'] ?? 'N/A'); ?></small>
                                                        </td>
                                                        <td>
                                                            <small><?php echo htmlspecialchars($test['test_name']); ?></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>
                                                            <span class="badge bg-<?php echo $test['status'] == 'SCHEDULED' ? 'primary' : 'secondary'; ?>">
                                                                <?php echo $test['status']; ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group">
                                                                <button class="btn btn-sm btn-success" onclick="startTest(<?php echo $test['order_test_id']; ?>)">
                                                                    <i class="ri-play-line"></i> Start
                                                                </button>
                                                                <button class="btn btn-sm btn-info" onclick="viewDetails(<?php echo $test['order_test_id']; ?>)">
                                                                    <i class="ri-eye-line"></i>
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr><td colspan="9" class="text-center">No scheduled 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: [[0, 'asc']],
                pageLength: 25 
            }); 
        });
        function startTest(id) {
            Swal.fire({
                title: 'Start Test?',
                text: 'Mark this test as in progress and begin testing',
                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 viewDetails(id) {
            window.location.href = 'view_test_details.php?test_id=' + id;
        }
    </script>
    <script src="assets/js/app.js"></script>
</body>
</html>