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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'NURSE'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}
$page_title = "Test Types Management";

// Fetch test types with statistics
$query = "SELECT 
            tt.*,
            COUNT(DISTINCT lot.order_test_id) as total_tests,
            COUNT(DISTINCT CASE WHEN lot.status = 'COMPLETED' THEN lot.order_test_id END) as completed_tests,
            COUNT(DISTINCT CASE WHEN lot.status = 'PENDING' THEN lot.order_test_id END) as pending_tests
          FROM ent_test_types tt
          LEFT JOIN lab_order_tests lot ON tt.test_type_id = lot.test_type_id
          WHERE tt.is_active = 1
          GROUP BY tt.test_type_id
          ORDER BY tt.category, tt.test_name";
$result = mysqli_query($conn, $query);

// Get statistics
$stats_query = "SELECT 
                COUNT(*) as total_types,
                SUM(CASE WHEN requires_fasting = 1 THEN 1 ELSE 0 END) as fasting_required,
                SUM(CASE WHEN requires_appointment = 1 THEN 1 ELSE 0 END) as appointment_required,
                COUNT(DISTINCT category) as total_categories
                FROM ent_test_types WHERE is_active = 1";
$stats = mysqli_fetch_assoc(mysqli_query($conn, $stats_query));
?>

<?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/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .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;
            border-left: 4px solid #667eea;
            transition: transform 0.2s;
            margin-bottom: 1.5rem;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
            text-transform: uppercase;
        }
        
        .test-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            border-left: 4px solid #3b82f6;
            transition: all 0.3s;
        }
        
        .test-card:hover {
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        
        .category-badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 500;
            text-transform: uppercase;
        }
        
        .cat-audiometry {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .cat-vestibular {
            background: #fef3c7;
            color: #92400e;
        }
        
        .cat-imaging {
            background: #e0e7ff;
            color: #4338ca;
        }
        
        .cat-endoscopy {
            background: #d1fae5;
            color: #065f46;
        }
        
        .cat-allergy {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .cat-sleep_study {
            background: #e9d5ff;
            color: #6b21a8;
        }
        
        .cat-pathology {
            background: #fce7f3;
            color: #9f1239;
        }
        
        .cat-microbiology {
            background: #cffafe;
            color: #0e7490;
        }
        
        .search-box {
            position: relative;
            margin-bottom: 1.5rem;
        }
        
        .search-box i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
        }
        
        .search-box input {
            padding-left: 2.5rem;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem 1rem 0.75rem 2.5rem;
            width: 100%;
        }
        
        .search-box input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .badge-requirement {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            padding: 0.25rem 0.5rem;
            background: #f1f5f9;
            color: #475569;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .badge-requirement.active {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .test-stats {
            display: flex;
            gap: 1rem;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #e2e8f0;
        }
        
        .stat-mini {
            text-align: center;
            flex: 1;
        }
        
        .stat-mini-value {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
        }
        
        .stat-mini-label {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
        }
    </style>
</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">Test Types Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">Laboratory</li>
                                        <li class="breadcrumb-item active">Test Types</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-test-tube-line me-2"></i><?php echo $page_title; ?></h4>
                                <p class="mb-0">Manage all ENT laboratory test types and configurations</p>
                            </div>
                            <a href="add_test_type.php" class="btn btn-light btn-lg">
                                <i class="ri-add-line me-2"></i>Add New Test Type
                            </a>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['total_types']); ?></div>
                                <div class="stat-label">Total Test Types</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['fasting_required']); ?></div>
                                <div class="stat-label">Require Fasting</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['appointment_required']); ?></div>
                                <div class="stat-label">Need Appointment</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['total_categories']); ?></div>
                                <div class="stat-label">Categories</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="search-box">
                                <i class="ri-search-line"></i>
                                <input type="text" id="searchInput" placeholder="Search test types by name or code...">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <select class="form-select" id="categoryFilter" style="border-radius: 8px; border: 2px solid #e2e8f0; padding: 0.75rem;">
                                <option value="">All Categories</option>
                                <option value="AUDIOMETRY">Audiometry</option>
                                <option value="VESTIBULAR">Vestibular</option>
                                <option value="IMAGING">Imaging</option>
                                <option value="ENDOSCOPY">Endoscopy</option>
                                <option value="ALLERGY">Allergy</option>
                                <option value="SLEEP_STUDY">Sleep Study</option>
                                <option value="PATHOLOGY">Pathology</option>
                                <option value="MICROBIOLOGY">Microbiology</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-outline-secondary w-100" onclick="resetFilters()">
                                <i class="ri-refresh-line me-2"></i>Reset
                            </button>
                        </div>
                    </div>

                    <!-- Test Types List -->
                    <div id="testTypesList">
                        <?php if(mysqli_num_rows($result) > 0): ?>
                        <?php 
                        $current_cat = '';
                        while($test = mysqli_fetch_assoc($result)): 
                            if($current_cat != $test['category']) {
                                if($current_cat != '') echo '</div>';
                                $current_cat = $test['category'];
                                echo '<h5 class="mt-4 mb-3" style="color: #1e293b; font-weight: 600;">' . str_replace('_', ' ', $current_cat) . ' Tests</h5>';
                                echo '<div class="category-group" data-category="' . $current_cat . '">';
                            }
                        ?>
                        
                        <div class="test-card" data-test-name="<?php echo strtolower($test['test_name']); ?>" data-test-code="<?php echo strtolower($test['test_code']); ?>">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <div class="d-flex align-items-center gap-3 mb-2">
                                        <h6 class="mb-0"><?php echo htmlspecialchars($test['test_name']); ?></h6>
                                        <span class="badge bg-secondary"><?php echo htmlspecialchars($test['test_code']); ?></span>
                                        <span class="category-badge cat-<?php echo strtolower($test['category']); ?>">
                                            <?php echo str_replace('_', ' ', $test['category']); ?>
                                        </span>
                                    </div>
                                    
                                    <?php if($test['description']): ?>
                                    <p class="text-muted mb-2 small">
                                        <?php echo htmlspecialchars($test['description']); ?>
                                    </p>
                                    <?php endif; ?>
                                    
                                    <div class="d-flex gap-3 flex-wrap text-muted small mb-2">
                                        <span><i class="ri-money-dollar-circle-line me-1"></i>KES <?php echo number_format($test['cost'], 2); ?></span>
                                        <span><i class="ri-time-line me-1"></i><?php echo $test['turnaround_time_hours']; ?> hours</span>
                                        <?php if($test['requires_fasting']): ?>
                                        <span class="badge-requirement active">
                                            <i class="ri-restaurant-line"></i>Fasting Required
                                        </span>
                                        <?php endif; ?>
                                        <?php if($test['requires_appointment']): ?>
                                        <span class="badge-requirement active">
                                            <i class="ri-calendar-line"></i>Appointment Required
                                        </span>
                                        <?php endif; ?>
                                        <?php if($test['technician_required']): ?>
                                        <span class="badge-requirement active">
                                            <i class="ri-user-star-line"></i>Technician Required
                                        </span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="test-stats">
                                        <div class="stat-mini">
                                            <div class="stat-mini-value"><?php echo number_format($test['total_tests']); ?></div>
                                            <div class="stat-mini-label">Total Tests</div>
                                        </div>
                                        <div class="stat-mini">
                                            <div class="stat-mini-value text-success"><?php echo number_format($test['completed_tests']); ?></div>
                                            <div class="stat-mini-label">Completed</div>
                                        </div>
                                        <div class="stat-mini">
                                            <div class="stat-mini-value text-warning"><?php echo number_format($test['pending_tests']); ?></div>
                                            <div class="stat-mini-label">Pending</div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="d-flex flex-column gap-2" style="min-width: 120px;">
                                    <a href="edit_test_type.php?id=<?php echo $test['test_type_id']; ?>" class="btn btn-sm" style="background: #667eea; color: white;">
                                        <i class="ri-edit-line"></i> Edit
                                    </a>
                                    <button onclick="viewTestDetails(<?php echo $test['test_type_id']; ?>)" class="btn btn-outline-secondary btn-sm">
                                        <i class="ri-eye-line"></i> View
                                    </button>
                                    <button onclick="deactivateTest(<?php echo $test['test_type_id']; ?>)" class="btn btn-outline-danger btn-sm">
                                        <i class="ri-delete-bin-line"></i> Deactivate
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <?php endwhile; ?>
                        <?php if($current_cat != '') echo '</div>'; ?>
                        <?php else: ?>
                        <div class="text-center py-5">
                            <i class="ri-test-tube-line" style="font-size: 4rem; opacity: 0.3;"></i>
                            <p class="text-muted mt-3">No test types found</p>
                            <a href="add_test_type.php" class="btn btn-primary">Add First Test Type</a>
                        </div>
                        <?php endif; ?>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>

    <script>
        // Search functionality
        document.getElementById('searchInput').addEventListener('input', function() {
            filterTests();
        });
        
        document.getElementById('categoryFilter').addEventListener('change', function() {
            filterTests();
        });
        
        function filterTests() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const category = document.getElementById('categoryFilter').value;
            const testCards = document.querySelectorAll('.test-card');
            
            testCards.forEach(card => {
                const testName = card.getAttribute('data-test-name');
                const testCode = card.getAttribute('data-test-code');
                const cardCat = card.closest('.category-group')?.getAttribute('data-category') || '';
                
                const matchesSearch = testName.includes(searchTerm) || testCode.includes(searchTerm);
                const matchesCat = !category || cardCat === category;
                
                card.style.display = (matchesSearch && matchesCat) ? 'block' : 'none';
            });
        }
        
        function resetFilters() {
            document.getElementById('searchInput').value = '';
            document.getElementById('categoryFilter').value = '';
            filterTests();
        }
        
        function viewTestDetails(testId) {
            window.location.href = 'view_test_type.php?id=' + testId;
        }
        
        function deactivateTest(testId) {
            Swal.fire({
                title: 'Deactivate Test Type?',
                text: "This test type will no longer be available for new orders. Existing orders will not be affected.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                cancelButtonColor: '#64748b',
                confirmButtonText: 'Yes, deactivate it!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // AJAX call to deactivate
                    $.ajax({
                        url: 'actions/deactivate_test_type.php',
                        method: 'POST',
                        data: { test_type_id: testId },
                        dataType: 'json',
                        success: function(response) {
                            if(response.success) {
                                Swal.fire('Deactivated!', response.message, 'success')
                                .then(() => location.reload());
                            } else {
                                Swal.fire('Error!', response.message, 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error!', 'Failed to deactivate test type', 'error');
                        }
                    });
                }
            });
        }
    </script>
</body>
</html>