<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include 'layouts/dbconn.php';

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

$user_id = $_SESSION['user_id'];
$role_code = $_SESSION['role_code'];

if ($role_code !== 'LAB_TECHNICIAN') {
   $redirect_url = match($role_code) {
        'SUPER_ADMIN', 'HOSPITAL_ADMIN' => 'admin_dashboard.php',
        'ENT_CONSULTANT', 'ENT_DOCTOR' => 'doctor_dashboard.php',
        'RESIDENT_DOCTOR' => 'resident_dashboard.php',
        'HEAD_NURSE', 'ENT_NURSE' => 'nursing_dashboard.php',
        'AUDIOLOGIST' => 'audiologist_dashboard.php',
        'RECEPTIONIST' => 'reception_dashboard.php',
        'BILLING_CLERK' => 'billing_dashboard.php',
        'MEDICAL_RECORDS' => 'records_dashboard.php',
        'PATIENT' => 'patient_portal.php',
        default => 'index.php'
    };
    header("Location: $redirect_url");
    exit();
}

// Fetch user details
$sql_user_details = "SELECT full_name FROM users WHERE user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$val = $stmt_user->get_result()->fetch_assoc();
$full_name = $val['full_name'];

$metrics = [];
$today = date('Y-m-d');

// My pending tests
$my_pending_tests_sql = "SELECT COUNT(*) as count FROM lab_order_tests lot
                        JOIN lab_orders lo ON lot.order_id = lo.order_id
                        WHERE lot.status IN ('PENDING', 'SCHEDULED')";
$metrics['my_pending_tests'] = $conn->query($my_pending_tests_sql)->fetch_assoc()['count'];

// Tests completed today
$completed_today_sql = "SELECT COUNT(*) as count FROM lab_order_tests 
                       WHERE DATE(completed_at) = ? AND status = 'COMPLETED'";
$stmt = $conn->prepare($completed_today_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['completed_tests_today'] = $stmt->get_result()->fetch_assoc()['count'];

// Recent tests
$recent_activities_sql = "SELECT 'test' as type, lo.order_number as reference,
                        p.patient_number, u.full_name as patient_name, lot.completed_at as activity_time,
                        ett.test_name
                        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 users u ON p.user_id = u.user_id
                        JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
                        WHERE lot.status = 'COMPLETED' AND lot.tested_by = ?
                        ORDER BY lot.completed_at DESC LIMIT 5";
$stmt = $conn->prepare($recent_activities_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$recent_activities = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

?>
<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Laboratory Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .welcome-header {
            background: linear-gradient(135deg, #40E0D0 0%, #20B2AA 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        .metric-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;
            transition: all 0.2s;
        }
        .metric-card:hover { transform: translateY(-2px); box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
        .metric-title { font-size: 0.875rem; font-weight: 600; color: #64748b; margin: 0; }
        .metric-icon { font-size: 1.5rem; float: right; }
        .metric-value { font-size: 2rem; font-weight: 700; color: #40E0D0; margin-top: 0.5rem; }
        .metric-change { font-size: 0.875rem; color: #64748b; margin-top: 0.25rem; }
        
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        .quick-action {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            text-align: center;
            border: 1px solid #e2e8f0;
            text-decoration: none;
            color: inherit;
            transition: all 0.2s;
        }
        .quick-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
            border-color: #40E0D0;
        }
        .quick-action-icon { font-size: 2rem; margin-bottom: 0.5rem; display: block; color: #40E0D0;}
        .quick-action-title { font-weight: 600; margin-bottom: 0.25rem; color: #334155; }
        .quick-action-desc { font-size: 0.875rem; color: #64748b; margin: 0; }
    </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="welcome-header">
                        <h2>Hello, <?php echo htmlspecialchars($full_name); ?></h2>
                        <p>Laboratory Dashboard</p>
                    </div>

                    <div class="row">
                        <div class="col-xl-6 col-md-6 mb-4">
                            <div class="metric-card">
                                <span class="metric-icon">⏳</span>
                                <h6 class="metric-title">Pending Tests</h6>
                                <div class="metric-value"><?php echo number_format($metrics['my_pending_tests'] ?? 0); ?></div>
                                <div class="metric-change">Total queue</div>
                            </div>
                        </div>
                        <div class="col-xl-6 col-md-6 mb-4">
                            <div class="metric-card">
                                <span class="metric-icon">✅</span>
                                <h6 class="metric-title">Completed Today</h6>
                                <div class="metric-value"><?php echo number_format($metrics['completed_tests_today'] ?? 0); ?></div>
                                <div class="metric-change">Tests finalized</div>
                            </div>
                        </div>
                    </div>

                    <h5 class="mb-3">Lab Services</h5>
                    <div class="quick-actions">
                        <a href="sample_collection.php" class="quick-action">
                            <span class="quick-action-icon">🧪</span>
                            <div class="quick-action-title">Sample Collection</div>
                            <p class="quick-action-desc">Collect specimens</p>
                        </a>
                        <a href="test_processing.php" class="quick-action">
                            <span class="quick-action-icon">🔬</span>
                            <div class="quick-action-title">Process Tests</div>
                            <p class="quick-action-desc">Laboratory analysis</p>
                        </a>
                        <a href="enter_results.php" class="quick-action">
                            <span class="quick-action-icon">📊</span>
                            <div class="quick-action-title">Enter Results</div>
                            <p class="quick-action-desc">Input test findings</p>
                        </a>
                        <a href="quality_control.php" class="quick-action">
                            <span class="quick-action-icon">🔍</span>
                            <div class="quick-action-title">Quality Control</div>
                            <p class="quick-action-desc">Verify accuracy</p>
                        </a>
                    </div>
                    
                     <!-- Recent Tests -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">My Recent Tests</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Date/Time</th>
                                                    <th>Order #</th>
                                                    <th>Patient</th>
                                                    <th>Test</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (!empty($recent_activities)): ?>
                                                    <?php foreach ($recent_activities as $activity): ?>
                                                    <tr>
                                                        <td><?php echo date('M d, H:i', strtotime($activity['activity_time'])); ?></td>
                                                        <td><?php echo htmlspecialchars($activity['reference']); ?></td>
                                                        <td><?php echo htmlspecialchars($activity['patient_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($activity['test_name']); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <tr><td colspan="4" class="text-center">No recent tests found.</td></tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
