<?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', 'LAB_TECHNICIAN', 'AUDIOLOGIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Get test type ID
$test_type_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$test_type_id) {
    header('Location: test_types.php');
    exit();
}

// Fetch test type details
$query = "SELECT * FROM ent_test_types WHERE test_type_id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "i", $test_type_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if (mysqli_num_rows($result) === 0) {
    header('Location: test_types.php');
    exit();
}

$test = mysqli_fetch_assoc($result);
$page_title = htmlspecialchars($test['test_name']);

// Get test statistics
$stats_query = "SELECT 
                    COUNT(*) as total_orders,
                    COUNT(CASE WHEN status = 'PENDING' THEN 1 END) as pending_count,
                    COUNT(CASE WHEN status = 'SCHEDULED' THEN 1 END) as scheduled_count,
                    COUNT(CASE WHEN status = 'IN_PROGRESS' THEN 1 END) as in_progress_count,
                    COUNT(CASE WHEN status = 'COMPLETED' THEN 1 END) as completed_count,
                    COUNT(CASE WHEN status = 'CANCELLED' THEN 1 END) as cancelled_count,
                    SUM(test_cost) as total_revenue,
                    AVG(test_cost) as avg_cost,
                    MIN(completed_at) as first_test_date,
                    MAX(completed_at) as last_test_date
                FROM lab_order_tests
                WHERE test_type_id = ?";
$stats_stmt = mysqli_prepare($conn, $stats_query);
mysqli_stmt_bind_param($stats_stmt, "i", $test_type_id);
mysqli_stmt_execute($stats_stmt);
$stats = mysqli_fetch_assoc(mysqli_stmt_get_result($stats_stmt));

// Get recent test orders
$recent_query = "SELECT 
                    lot.order_test_id,
                    lot.status,
                    lot.test_cost,
                    lot.scheduled_at,
                    lot.completed_at,
                    lot.created_at,
                    lo.order_number,
                    lo.priority,
                    p.patient_number,
                    u.full_name as patient_name,
                    tech_user.full_name as technician_name,
                    doc_user.full_name as ordered_by_name
                FROM lab_order_tests lot
                INNER JOIN lab_orders lo ON lot.order_id = lo.order_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 users tech_user ON lot.tested_by = tech_user.user_id
                LEFT JOIN users doc_user ON lo.ordered_by = doc_user.user_id
                WHERE lot.test_type_id = ?
                ORDER BY lot.created_at DESC
                LIMIT 10";
$recent_stmt = mysqli_prepare($conn, $recent_query);
mysqli_stmt_bind_param($recent_stmt, "i", $test_type_id);
mysqli_stmt_execute($recent_stmt);
$recent_tests = mysqli_stmt_get_result($recent_stmt);
?>

<?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>
        .profile-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);
        }
        
        .test-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            color: #667eea;
            border: 4px solid rgba(255,255,255,0.3);
        }
        
        .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;
        }
        
        .info-row {
            display: flex;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-label {
            flex: 0 0 180px;
            font-weight: 500;
            color: #64748b;
        }
        
        .info-value {
            flex: 1;
            color: #1e293b;
        }
        
        .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;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
            text-transform: uppercase;
        }
        
        .category-badge {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 500;
            text-transform: uppercase;
        }
        
        .badge-active {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-inactive {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .test-order-card {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            border-left: 4px solid #3b82f6;
        }
        
        .status-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
            text-transform: uppercase;
        }
        
        .status-PENDING {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-SCHEDULED {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .status-IN_PROGRESS {
            background: #e0e7ff;
            color: #4338ca;
        }
        
        .status-COMPLETED {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-CANCELLED {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .priority-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .priority-ROUTINE {
            background: #e2e8f0;
            color: #475569;
        }
        
        .priority-URGENT {
            background: #fed7aa;
            color: #9a3412;
        }
        
        .priority-STAT {
            background: #fecaca;
            color: #991b1b;
        }
        
        .requirement-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            padding: 0.5rem 0.75rem;
            background: #f1f5f9;
            color: #475569;
            border-radius: 6px;
            font-size: 0.875rem;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
        }
        
        .requirement-badge.active {
            background: #dbeafe;
            color: #1e40af;
        }
    </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 Type Details</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"><a href="test_types.php">Test Types</a></li>
                                        <li class="breadcrumb-item active"><?php echo $page_title; ?></li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Profile Header -->
                    <div class="profile-header">
                        <div class="row align-items-center">
                            <div class="col-auto">
                                <div class="test-icon">
                                    <i class="ri-test-tube-line"></i>
                                </div>
                            </div>
                            <div class="col">
                                <h3 class="mb-1"><?php echo htmlspecialchars($test['test_name']); ?></h3>
                                <div class="d-flex align-items-center gap-3 flex-wrap">
                                    <span><strong>Code:</strong> <?php echo htmlspecialchars($test['test_code']); ?></span>
                                    <span><strong>Category:</strong> <?php echo str_replace('_', ' ', $test['category']); ?></span>
                                    <span class="badge-active badge">
                                        <?php echo $test['is_active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="d-flex gap-2">
                                    <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN'])): ?>
                                    <a href="edit_test_type.php?id=<?php echo $test_type_id; ?>" class="btn btn-light">
                                        <i class="ri-edit-line me-1"></i> Edit Test Type
                                    </a>
                                    <?php endif; ?>
                                    <a href="test_types.php" class="btn btn-light">
                                        <i class="ri-arrow-left-line me-1"></i> Back to List
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['total_orders']); ?></div>
                                <div class="stat-label">Total Orders</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value text-success"><?php echo number_format($stats['completed_count']); ?></div>
                                <div class="stat-label">Completed</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value text-warning"><?php echo number_format($stats['pending_count']); ?></div>
                                <div class="stat-label">Pending</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value text-primary">KES <?php echo number_format($stats['total_revenue'], 2); ?></div>
                                <div class="stat-label">Total Revenue</div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-lg-8">
                            
                            <!-- Test Information -->
                            <div class="info-card">
                                <h5><i class="ri-information-line me-2"></i>Test Information</h5>
                                
                                <?php if($test['description']): ?>
                                <div class="info-row">
                                    <div class="info-label">Description</div>
                                    <div class="info-value"><?php echo nl2br(htmlspecialchars($test['description'])); ?></div>
                                </div>
                                <?php endif; ?>
                                
                                <div class="info-row">
                                    <div class="info-label">Test Code</div>
                                    <div class="info-value"><code><?php echo htmlspecialchars($test['test_code']); ?></code></div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">Category</div>
                                    <div class="info-value">
                                        <span class="badge bg-primary"><?php echo str_replace('_', ' ', $test['category']); ?></span>
                                    </div>
                                </div>
                                
                                <?php if($test['subcategory']): ?>
                                <div class="info-row">
                                    <div class="info-label">Subcategory</div>
                                    <div class="info-value"><?php echo htmlspecialchars($test['subcategory']); ?></div>
                                </div>
                                <?php endif; ?>
                                
                                <div class="info-row">
                                    <div class="info-label">Cost</div>
                                    <div class="info-value">
                                        <strong class="text-primary">KES <?php echo number_format($test['cost'], 2); ?></strong>
                                    </div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">Turnaround Time</div>
                                    <div class="info-value"><?php echo $test['turnaround_time_hours']; ?> hours</div>
                                </div>
                                
                                <?php if($test['sample_type']): ?>
                                <div class="info-row">
                                    <div class="info-label">Sample Type</div>
                                    <div class="info-value"><?php echo htmlspecialchars($test['sample_type']); ?></div>
                                </div>
                                <?php endif; ?>
                                
                                <?php if($test['normal_range']): ?>
                                <div class="info-row">
                                    <div class="info-label">Normal Range</div>
                                    <div class="info-value"><?php echo htmlspecialchars($test['normal_range']); ?></div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Requirements -->
                            <div class="info-card">
                                <h5><i class="ri-checkbox-circle-line me-2"></i>Requirements & Preparation</h5>
                                
                                <div class="mb-3">
                                    <span class="requirement-badge <?php echo $test['requires_fasting'] ? 'active' : ''; ?>">
                                        <i class="ri-restaurant-line"></i>
                                        Fasting Required: <?php echo $test['requires_fasting'] ? 'Yes' : 'No'; ?>
                                    </span>
                                    <span class="requirement-badge <?php echo $test['requires_appointment'] ? 'active' : ''; ?>">
                                        <i class="ri-calendar-line"></i>
                                        Appointment Required: <?php echo $test['requires_appointment'] ? 'Yes' : 'No'; ?>
                                    </span>
                                    <span class="requirement-badge <?php echo $test['technician_required'] ? 'active' : ''; ?>">
                                        <i class="ri-user-star-line"></i>
                                        Technician Required: <?php echo $test['technician_required'] ? 'Yes' : 'No'; ?>
                                    </span>
                                    <span class="requirement-badge <?php echo $test['external_lab'] ? 'active' : ''; ?>">
                                        <i class="ri-building-line"></i>
                                        External Lab: <?php echo $test['external_lab'] ? 'Yes' : 'No'; ?>
                                    </span>
                                </div>
                                
                                <?php if($test['equipment_required']): ?>
                                <div class="info-row">
                                    <div class="info-label">Equipment Required</div>
                                    <div class="info-value"><?php echo htmlspecialchars($test['equipment_required']); ?></div>
                                </div>
                                <?php endif; ?>
                                
                                <?php if($test['room_type_required']): ?>
                                <div class="info-row">
                                    <div class="info-label">Room Type Required</div>
                                    <div class="info-value"><?php echo htmlspecialchars($test['room_type_required']); ?></div>
                                </div>
                                <?php endif; ?>
                                
                                <?php if($test['preparation_instructions']): ?>
                                <div class="info-row">
                                    <div class="info-label">Preparation Instructions</div>
                                    <div class="info-value"><?php echo nl2br(htmlspecialchars($test['preparation_instructions'])); ?></div>
                                </div>
                                <?php endif; ?>
                                
                                <?php if($test['external_lab'] && $test['external_lab_name']): ?>
                                <div class="info-row">
                                    <div class="info-label">External Lab Name</div>
                                    <div class="info-value"><?php echo htmlspecialchars($test['external_lab_name']); ?></div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Recent Test Orders -->
                            <div class="info-card">
                                <h5><i class="ri-history-line me-2"></i>Recent Test Orders</h5>
                                
                                <?php if (mysqli_num_rows($recent_tests) > 0): ?>
                                    <?php while($order = mysqli_fetch_assoc($recent_tests)): ?>
                                    <div class="test-order-card">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <div class="fw-bold"><?php echo htmlspecialchars($order['order_number']); ?></div>
                                                <div class="text-muted small mb-1">
                                                    Patient: <?php echo htmlspecialchars($order['patient_name']); ?> 
                                                    (#<?php echo htmlspecialchars($order['patient_number']); ?>)
                                                </div>
                                                <?php if($order['ordered_by_name']): ?>
                                                <div class="text-muted small mb-1">
                                                    Ordered by: <?php echo htmlspecialchars($order['ordered_by_name']); ?>
                                                </div>
                                                <?php endif; ?>
                                                <?php if($order['technician_name']): ?>
                                                <div class="text-muted small mb-1">
                                                    Technician: <?php echo htmlspecialchars($order['technician_name']); ?>
                                                </div>
                                                <?php endif; ?>
                                                <div class="text-muted small">
                                                    <?php echo date('M d, Y h:i A', strtotime($order['created_at'])); ?>
                                                </div>
                                            </div>
                                            <div class="text-end">
                                                <span class="status-badge status-<?php echo $order['status']; ?>">
                                                    <?php echo str_replace('_', ' ', $order['status']); ?>
                                                </span>
                                                <div class="mt-2">
                                                    <span class="priority-badge priority-<?php echo $order['priority']; ?>">
                                                        <?php echo $order['priority']; ?>
                                                    </span>
                                                </div>
                                                <div class="mt-2 fw-bold text-primary">
                                                    KES <?php echo number_format($order['test_cost'], 2); ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <div class="text-center py-4 text-muted">
                                        <i class="ri-inbox-line" style="font-size: 3rem; opacity: 0.3;"></i>
                                        <p class="mt-2">No test orders yet</p>
                                    </div>
                                <?php endif; ?>
                            </div>

                        </div>

                        <!-- Right Column -->
                        <div class="col-lg-4">
                            
                            <!-- Quick Stats -->
                            <div class="info-card">
                                <h5><i class="ri-bar-chart-line me-2"></i>Statistics</h5>
                                
                                <div class="info-row">
                                    <div class="info-label">Total Orders</div>
                                    <div class="info-value"><strong><?php echo number_format($stats['total_orders']); ?></strong></div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">Pending</div>
                                    <div class="info-value text-warning"><strong><?php echo number_format($stats['pending_count']); ?></strong></div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">Scheduled</div>
                                    <div class="info-value text-info"><strong><?php echo number_format($stats['scheduled_count']); ?></strong></div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">In Progress</div>
                                    <div class="info-value text-primary"><strong><?php echo number_format($stats['in_progress_count']); ?></strong></div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">Completed</div>
                                    <div class="info-value text-success"><strong><?php echo number_format($stats['completed_count']); ?></strong></div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">Cancelled</div>
                                    <div class="info-value text-danger"><strong><?php echo number_format($stats['cancelled_count']); ?></strong></div>
                                </div>
                            </div>

                            <!-- Revenue Information -->
                            <div class="info-card">
                                <h5><i class="ri-money-dollar-circle-line me-2"></i>Revenue Information</h5>
                                
                                <div class="info-row">
                                    <div class="info-label">Total Revenue</div>
                                    <div class="info-value">
                                        <strong class="text-primary">KES <?php echo number_format($stats['total_revenue'], 2); ?></strong>
                                    </div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">Average Cost</div>
                                    <div class="info-value">KES <?php echo number_format($stats['avg_cost'], 2); ?></div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">Standard Cost</div>
                                    <div class="info-value">KES <?php echo number_format($test['cost'], 2); ?></div>
                                </div>
                            </div>

                            <!-- Test History -->
                            <div class="info-card">
                                <h5><i class="ri-calendar-line me-2"></i>Test History</h5>
                                
                                <?php if($stats['first_test_date']): ?>
                                <div class="info-row">
                                    <div class="info-label">First Test</div>
                                    <div class="info-value"><?php echo date('M d, Y', strtotime($stats['first_test_date'])); ?></div>
                                </div>
                                <?php endif; ?>
                                
                                <?php if($stats['last_test_date']): ?>
                                <div class="info-row">
                                    <div class="info-label">Last Test</div>
                                    <div class="info-value"><?php echo date('M d, Y', strtotime($stats['last_test_date'])); ?></div>
                                </div>
                                <?php endif; ?>
                                
                                <div class="info-row">
                                    <div class="info-label">Created At</div>
                                    <div class="info-value"><?php echo date('M d, Y h:i A', strtotime($test['created_at'])); ?></div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">Status</div>
                                    <div class="info-value">
                                        <span class="badge <?php echo $test['is_active'] ? 'badge-active' : 'badge-inactive'; ?>">
                                            <?php echo $test['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </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>
</body>
</html>