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

// Check authentication
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Get filters
$priority_filter = isset($_GET['priority']) ? $_GET['priority'] : '';
$category_filter = isset($_GET['category']) ? $_GET['category'] : '';
$date_filter = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// Build query for pending tests
$sql = "SELECT 
    lot.order_test_id,
    lot.test_cost,
    lot.status,
    lot.scheduled_at,
    lo.order_id,
    lo.order_number,
    lo.priority,
    lo.clinical_notes,
    lo.ordered_at,
    p.patient_id,
    p.patient_number,
    u.full_name as patient_name,
    u.phone_primary,
    u.date_of_birth,
    ett.test_name,
    ett.test_code,
    ett.category,
    ett.requires_appointment,
    ett.turnaround_time_hours,
    u.full_name as ordered_by_name,
    pv.registration_type,
    pv.smart_session_id
FROM lab_order_tests lot
JOIN lab_orders lo ON lot.order_id = lo.order_id
JOIN patients p ON lo.patient_id = p.patient_id
JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
JOIN users u ON lo.ordered_by = u.user_id
LEFT JOIN patient_visits pv ON lo.visit_id = pv.visit_id
WHERE lot.status IN ('PENDING', 'SCHEDULED')";

$params = [];
$types = "";

if ($priority_filter) {
    $sql .= " AND lo.priority = ?";
    $params[] = $priority_filter;
    $types .= "s";
}

if ($category_filter) {
    $sql .= " AND ett.category = ?";
    $params[] = $category_filter;
    $types .= "s";
}

if ($date_filter) {
    $sql .= " AND DATE(lo.ordered_at) = ?";
    $params[] = $date_filter;
    $types .= "s";
}

$sql .= " ORDER BY 
    FIELD(lo.priority, 'STAT', 'URGENT', 'ROUTINE'),
    lo.ordered_at ASC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$pending_tests = $stmt->get_result();

// Get statistics
$stats_sql = "SELECT 
    COUNT(*) as total_pending,
    SUM(CASE WHEN lo.priority = 'STAT' THEN 1 ELSE 0 END) as stat_count,
    SUM(CASE WHEN lo.priority = 'URGENT' THEN 1 ELSE 0 END) as urgent_count,
    SUM(CASE WHEN lo.priority = 'ROUTINE' THEN 1 ELSE 0 END) as routine_count,
    SUM(CASE WHEN lot.status = 'SCHEDULED' THEN 1 ELSE 0 END) as scheduled_count
FROM lab_order_tests lot
JOIN lab_orders lo ON lot.order_id = lo.order_id
WHERE lot.status IN ('PENDING', 'SCHEDULED')";

if ($date_filter) {
    $stats_sql .= " AND DATE(lo.ordered_at) = '$date_filter'";
}

$stats = $conn->query($stats_sql)->fetch_assoc();

// Get test categories for filter
$categories_sql = "SELECT DISTINCT category FROM ent_test_types ORDER BY category";
$categories = $conn->query($categories_sql);
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pending Tests')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet">
</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">
                                    <i class="ri-time-line me-2"></i>Pending Laboratory Tests
                                </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 active">Pending Tests</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-xl-2 col-md-4">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted fw-medium mb-2">Total Pending</p>
                                            <h4 class="fs-22 fw-semibold mb-0">
                                                <?php echo $stats['total_pending']; ?>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-primary-subtle text-primary rounded fs-3">
                                                <i class="ri-test-tube-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-2 col-md-4">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted fw-medium mb-2">STAT</p>
                                            <h4 class="fs-22 fw-semibold mb-0 text-danger">
                                                <?php echo $stats['stat_count']; ?>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-danger-subtle text-danger rounded fs-3">
                                                <i class="ri-alarm-warning-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-2 col-md-4">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted fw-medium mb-2">Urgent</p>
                                            <h4 class="fs-22 fw-semibold mb-0 text-warning">
                                                <?php echo $stats['urgent_count']; ?>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-warning-subtle text-warning rounded fs-3">
                                                <i class="ri-error-warning-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-2 col-md-4">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted fw-medium mb-2">Routine</p>
                                            <h4 class="fs-22 fw-semibold mb-0 text-info">
                                                <?php echo $stats['routine_count']; ?>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-info-subtle text-info rounded fs-3">
                                                <i class="ri-calendar-check-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-2 col-md-4">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted fw-medium mb-2">Scheduled</p>
                                            <h4 class="fs-22 fw-semibold mb-0 text-success">
                                                <?php echo $stats['scheduled_count']; ?>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-success-subtle text-success rounded fs-3">
                                                <i class="ri-calendar-event-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="card">
                        <div class="card-body">
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">Date</label>
                                    <input type="text" class="form-control flatpickr-date" name="date" 
                                           value="<?php echo $date_filter; ?>">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Priority</label>
                                    <select class="form-select" name="priority">
                                        <option value="">All Priorities</option>
                                        <option value="STAT" <?php echo ($priority_filter == 'STAT') ? 'selected' : ''; ?>>STAT</option>
                                        <option value="URGENT" <?php echo ($priority_filter == 'URGENT') ? 'selected' : ''; ?>>Urgent</option>
                                        <option value="ROUTINE" <?php echo ($priority_filter == 'ROUTINE') ? 'selected' : ''; ?>>Routine</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Test Category</label>
                                    <select class="form-select" name="category">
                                        <option value="">All Categories</option>
                                        <?php while($cat = $categories->fetch_assoc()): ?>
                                            <option value="<?php echo $cat['category']; ?>" 
                                                <?php echo ($category_filter == $cat['category']) ? 'selected' : ''; ?>>
                                                <?php echo str_replace('_', ' ', $cat['category']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="ri-search-line me-1"></i>Filter
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Pending Tests Table -->
                    <div class="card">
                        <div class="card-header">
                            <div class="d-flex align-items-center">
                                <h5 class="card-title flex-grow-1 mb-0">Pending Tests</h5>
                                <div class="flex-shrink-0">
                                    <button class="btn btn-success btn-sm me-2" onclick="refreshData()">
                                        <i class="ri-refresh-line me-1"></i>Refresh
                                    </button>
                                    <button class="btn btn-info btn-sm" onclick="printList()">
                                        <i class="ri-printer-line me-1"></i>Print
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover align-middle mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Order #</th>
                                            <th>Patient</th>
                                            <th>Test</th>
                                            <th>Priority</th>
                                            <th>Ordered</th>
                                            <th>TAT</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if ($pending_tests->num_rows > 0): ?>
                                            <?php while($test = $pending_tests->fetch_assoc()): ?>
                                                <?php
                                                $priority_badge = [
                                                    'STAT' => 'bg-danger',
                                                    'URGENT' => 'bg-warning',
                                                    'ROUTINE' => 'bg-info'
                                                ];
                                                $badge_class = $priority_badge[$test['priority']] ?? 'bg-secondary';
                                                
                                                $status_badge = [
                                                    'PENDING' => 'bg-warning',
                                                    'SCHEDULED' => 'bg-primary'
                                                ];
                                                $status_class = $status_badge[$test['status']] ?? 'bg-secondary';
                                                
                                                // Calculate time since ordered
                                                $ordered_time = new DateTime($test['ordered_at']);
                                                $now = new DateTime();
                                                $hours_elapsed = $now->diff($ordered_time)->h + ($now->diff($ordered_time)->days * 24);
                                                ?>
                                                <tr class="<?php echo ($test['priority'] == 'STAT') ? 'table-danger' : ''; ?>">
                                                    <td>
                                                        <strong><?php echo $test['order_number']; ?></strong><br>
                                                        <small class="text-muted">
                                                            <?php echo $test['test_code']; ?>
                                                        </small>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <strong><?php echo htmlspecialchars($test['patient_name']); ?></strong>
                                                            <?php if ($test['smart_session_id']): ?>
                                                                <span class="badge bg-primary-subtle text-primary ms-1">
                                                                    <i class="ri-shield-check-line"></i>
                                                                </span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <small class="text-muted">
                                                            <?php echo $test['patient_number']; ?>
                                                        </small>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <?php echo htmlspecialchars($test['test_name']); ?>
                                                        </div>
                                                        <small class="text-muted">
                                                            <?php echo str_replace('_', ' ', $test['category']); ?>
                                                        </small>
                                                    </td>
                                                    <td>
                                                        <span class="badge <?php echo $badge_class; ?>">
                                                            <?php echo $test['priority']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div><?php echo date('M d, h:i A', strtotime($test['ordered_at'])); ?></div>
                                                        <small class="text-muted">
                                                            <?php echo $hours_elapsed; ?>h ago
                                                        </small>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-secondary-subtle text-secondary">
                                                            <?php echo $test['turnaround_time_hours']; ?>h
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <span class="badge <?php echo $status_class; ?>">
                                                            <?php echo $test['status']; ?>
                                                        </span>
                                                        <?php if ($test['requires_appointment'] && $test['status'] == 'PENDING'): ?>
                                                            <br><small class="text-warning">
                                                                <i class="ri-calendar-line"></i> Needs scheduling
                                                            </small>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <?php if ($test['status'] == 'PENDING' && $test['requires_appointment']): ?>
                                                                <button onclick="scheduleTest(<?php echo $test['order_test_id']; ?>)" 
                                                                        class="btn btn-outline-primary" title="Schedule">
                                                                    <i class="ri-calendar-event-line"></i>
                                                                </button>
                                                            <?php else: ?>
                                                                <button onclick="startTest(<?php echo $test['order_test_id']; ?>)" 
                                                                        class="btn btn-outline-success" title="Start Test">
                                                                    <i class="ri-play-circle-line"></i>
                                                                </button>
                                                            <?php endif; ?>
                                                            <a href="patient_profile.php?id=<?php echo $test['patient_id']; ?>" 
                                                               class="btn btn-outline-info" title="View Patient">
                                                                <i class="ri-user-line"></i>
                                                            </a>
                                                            <a href="view_lab_order.php?id=<?php echo $test['order_id']; ?>" 
                                                               class="btn btn-outline-secondary" title="View Order">
                                                                <i class="ri-file-list-3-line"></i>
                                                            </a>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="8" class="text-center py-4">
                                                    <i class="ri-test-tube-line fs-1 text-muted"></i>
                                                    <p class="text-muted mt-2">No pending tests found</p>
                                                </td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>

    <script>
        flatpickr('.flatpickr-date', {
            dateFormat: 'Y-m-d'
        });

        function scheduleTest(orderTestId) {
            Swal.fire({
                title: 'Schedule Test',
                html: `
                    <div class="mb-3">
                        <label class="form-label">Schedule Date & Time</label>
                        <input type="datetime-local" id="scheduleDateTime" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea id="scheduleNotes" class="form-control" rows="2"></textarea>
                    </div>
                `,
                showCancelButton: true,
                confirmButtonText: 'Schedule',
                preConfirm: () => {
                    const datetime = document.getElementById('scheduleDateTime').value;
                    const notes = document.getElementById('scheduleNotes').value;
                    
                    if (!datetime) {
                        Swal.showValidationMessage('Please select date and time');
                        return false;
                    }
                    
                    return { datetime, notes };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/schedule_test.php',
                        type: 'POST',
                        data: {
                            order_test_id: orderTestId,
                            scheduled_at: result.value.datetime,
                            notes: result.value.notes
                        },
                        success: function(response) {
                            const data = JSON.parse(response);
                            if (data.success) {
                                Swal.fire('Scheduled!', data.message, 'success')
                                    .then(() => location.reload());
                            } else {
                                Swal.fire('Error', data.message, 'error');
                            }
                        }
                    });
                }
            });
        }

        function startTest(orderTestId) {
            Swal.fire({
                title: 'Start Test?',
                text: 'This will mark the test as IN PROGRESS',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, start test'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/start_test.php',
                        type: 'POST',
                        data: { order_test_id: orderTestId },
                        success: function(response) {
                            const data = JSON.parse(response);
                            if (data.success) {
                                window.location.href = 'enter_test_results.php?id=' + orderTestId;
                            } else {
                                Swal.fire('Error', data.message, 'error');
                            }
                        }
                    });
                }
            });
        }

        function refreshData() {
            Swal.fire({
                title: 'Refreshing...',
                didOpen: () => Swal.showLoading()
            });
            location.reload();
        }

        function printList() {
            window.print();
        }

        // Auto-refresh every 2 minutes
        setInterval(function() {
            location.reload();
        }, 120000);
    </script>
</body>
</html>