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

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

// Fetch all lab technicians
$sql_techs = "SELECT 
    lt.*,
    u.full_name,
    u.email,
    u.phone_primary,
    u.staff_number,
    u.status,
    u.hire_date,
    u.last_login,
    b.branch_name,
    (SELECT COUNT(*) FROM lab_orders WHERE status = 'PENDING') as pending_orders,
    (SELECT COUNT(*) FROM lab_order_tests WHERE tested_by = lt.tech_id AND status = 'COMPLETED' AND DATE(completed_at) = CURDATE()) as today_tests
FROM lab_technicians lt
INNER JOIN users u ON lt.user_id = u.user_id
LEFT JOIN hospital_branches b ON u.branch_id = b.branch_id
WHERE u.user_type = 'STAFF'
ORDER BY lt.is_senior_tech DESC, u.full_name ASC";

$result_techs = $conn->query($sql_techs);

// Get statistics
$sql_stats = "SELECT 
    COUNT(*) as total_technicians,
    SUM(CASE WHEN lt.is_senior_tech = 1 THEN 1 ELSE 0 END) as senior_techs,
    SUM(CASE WHEN u.status = 'ACTIVE' THEN 1 ELSE 0 END) as active_techs,
    SUM(CASE WHEN u.last_login >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) as recent_logins
FROM lab_technicians lt
INNER JOIN users u ON lt.user_id = u.user_id";
$result_stats = $conn->query($sql_stats);
$stats = $result_stats->fetch_assoc();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Lab Technicians Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- DataTables CSS -->
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="assets/libs/datatables.net-responsive-bs5/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .tech-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #0ea5e9;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        .status-pending { background: #fef3c7; color: #92400e; }
        
        .specialization-tag {
            background: #dbeafe;
            color: #1e40af;
            padding: 0.15rem 0.4rem;
            border-radius: 4px;
            font-size: 0.7rem;
            display: inline-block;
            margin: 0.1rem;
        }
        
        .stats-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;
        }
        
        .stats-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stats-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .action-buttons .btn {
            padding: 0.375rem 0.75rem;
            margin: 0.125rem;
        }
    </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">Lab Technicians Management</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"><a href="#">Medical Staff</a></li>
                                        <li class="breadcrumb-item active">Lab Technicians</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-primary"><?php echo number_format($stats['total_technicians']); ?></div>
                                <div class="stats-label">Total Technicians</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-success"><?php echo number_format($stats['active_techs']); ?></div>
                                <div class="stats-label">Active</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-warning"><?php echo number_format($stats['senior_techs']); ?></div>
                                <div class="stats-label">Senior Technicians</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-info"><?php echo number_format($stats['recent_logins']); ?></div>
                                <div class="stats-label">Recent Logins</div>
                            </div>
                        </div>
                    </div>

                    <!-- Technicians Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-test-tube-line align-middle me-2"></i>Lab Technicians
                                    </h5>
                                    <div class="d-flex gap-2">
                                        <a href="add_technician.php" class="btn btn-primary">
                                            <i class="ri-user-add-line align-middle me-1"></i> Add Technician
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="techniciansTable" class="table table-striped table-hover align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Technician</th>
                                                    <th>License</th>
                                                    <th>Qualification</th>
                                                    <th>Specializations</th>
                                                    <th>Contact</th>
                                                    <th>Branch</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while($tech = $result_techs->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="tech-avatar me-3">
                                                                <?php echo strtoupper(substr($tech['full_name'], 0, 2)); ?>
                                                            </div>
                                                            <div>
                                                                <div class="fw-bold">
                                                                    <?php echo htmlspecialchars($tech['full_name']); ?>
                                                                    <?php if($tech['is_senior_tech']): ?>
                                                                        <i class="ri-medal-line text-warning" title="Senior Technician"></i>
                                                                    <?php endif; ?>
                                                                </div>
                                                                <div class="text-muted small">
                                                                    ID: <?php echo $tech['staff_number']; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="fw-semibold"><?php echo htmlspecialchars($tech['license_number']); ?></span>
                                                    </td>
                                                    <td>
                                                        <div class="fw-semibold"><?php echo htmlspecialchars($tech['qualification'] ?: 'N/A'); ?></div>
                                                    </td>
                                                    <td>
                                                        <?php if($tech['specializations']): 
                                                            $specializations = json_decode($tech['specializations'], true);
                                                            if($specializations && is_array($specializations) && count($specializations) > 0):
                                                                foreach(array_slice($specializations, 0, 2) as $spec): ?>
                                                                    <span class="specialization-tag"><?php echo htmlspecialchars($spec); ?></span>
                                                                <?php endforeach; 
                                                                if(count($specializations) > 2): ?>
                                                                    <span class="specialization-tag">+<?php echo count($specializations) - 2; ?></span>
                                                                <?php endif; ?>
                                                            <?php else: ?>
                                                                <span class="text-muted">-</span>
                                                            <?php endif; ?>
                                                        <?php else: ?>
                                                            <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <i class="ri-mail-line me-1"></i>
                                                            <small><?php echo htmlspecialchars($tech['email']); ?></small>
                                                        </div>
                                                        <div class="text-muted">
                                                            <i class="ri-phone-line me-1"></i>
                                                            <small><?php echo htmlspecialchars($tech['phone_primary']); ?></small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php echo htmlspecialchars($tech['branch_name'] ?: 'Not Assigned'); ?>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        $status_class = match($tech['status']) {
                                                            'ACTIVE' => 'status-active',
                                                            'INACTIVE' => 'status-inactive',
                                                            'PENDING' => 'status-pending',
                                                            default => 'status-inactive'
                                                        };
                                                        ?>
                                                        <span class="status-badge <?php echo $status_class; ?>">
                                                            <?php echo ucfirst(strtolower($tech['status'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="action-buttons">
                                                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                                                    onclick="viewTechnician(<?php echo $tech['tech_id']; ?>)"
                                                                    title="View Details">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                            <button type="button" class="btn btn-sm btn-outline-success" 
                                                                    onclick="editTechnician(<?php echo $tech['tech_id']; ?>)"
                                                                    title="Edit Technician">
                                                                <i class="ri-edit-line"></i>
                                                            </button>
                                                            <button type="button" class="btn btn-sm btn-outline-info" 
                                                                    onclick="viewWorkload(<?php echo $tech['tech_id']; ?>)"
                                                                    title="View Workload">
                                                                <i class="ri-file-list-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <!-- DataTables JS -->
    <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/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
    <script src="assets/libs/datatables.net-responsive-bs5/js/responsive.bootstrap5.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
        let techniciansTable;
        
        $(document).ready(function() {
            // Initialize DataTable
            techniciansTable = $('#techniciansTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'asc']],
                columnDefs: [
                    { orderable: false, targets: [7] }
                ]
            });
        });

        function viewTechnician(techId) {
            window.location.href = 'view_technician.php?id=' + techId;
        }

        function editTechnician(techId) {
            window.location.href = 'edit_technician.php?id=' + techId;
        }

        function viewWorkload(techId) {
            window.location.href = 'tech_workload.php?tech_id=' + techId;
        }

        <?php if(isset($_SESSION['success_message'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: '<?php echo $_SESSION['success_message']; ?>',
                timer: 3000
            });
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>
    </script>
</body>
</html>

<?php $conn->close(); ?><?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

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

// Fetch all lab technicians
$sql_techs = "SELECT 
    lt.*,
    u.full_name,
    u.email,
    u.phone_primary,
    u.status,
    u.profile_picture,
    b.branch_name,
    (SELECT COUNT(*) FROM lab_orders WHERE status = 'PENDING') as pending_orders,
    (SELECT COUNT(*) FROM lab_order_tests WHERE tested_by = lt.tech_id AND status = 'COMPLETED' AND DATE(completed_at) = CURDATE()) as today_tests
FROM lab_technicians lt
INNER JOIN users u ON lt.user_id = u.user_id
LEFT JOIN hospital_branches b ON u.branch_id = b.branch_id
WHERE u.user_type = 'STAFF'
ORDER BY lt.is_senior_tech DESC, u.full_name ASC";

$result_techs = $conn->query($sql_techs);

// Get statistics
$sql_stats = "SELECT 
    COUNT(*) as total_technicians,
    SUM(CASE WHEN lt.is_senior_tech = 1 THEN 1 ELSE 0 END) as senior_techs,
    SUM(CASE WHEN u.status = 'ACTIVE' THEN 1 ELSE 0 END) as active_techs
FROM lab_technicians lt
INNER JOIN users u ON lt.user_id = u.user_id";
$result_stats = $conn->query($sql_stats);
$stats = $result_stats->fetch_assoc();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Lab Technicians')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .tech-card {
            transition: all 0.3s ease;
            border: 1px solid #e2e8f0;
            height: 100%;
        }
        .tech-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        .tech-avatar {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        .specialization-tag {
            background: #dbeafe;
            color: #1e40af;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.7rem;
            display: inline-block;
            margin: 0.15rem;
        }
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        .stat-item {
            text-align: center;
            padding: 1rem;
        }
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
        }
        .stat-label {
            font-size: 0.875rem;
            opacity: 0.9;
        }
    </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">Lab Technicians Management</h4>
                                <div class="page-title-right">
                                    <a href="add_technician.php" class="btn btn-primary">
                                        <i class="ri-user-add-line align-middle me-1"></i> Add New Technician
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-12">
                            <div class="stats-card">
                                <div class="row">
                                    <div class="col-md-4 col-6 stat-item">
                                        <div class="stat-value"><?php echo $stats['total_technicians']; ?></div>
                                        <div class="stat-label">Total Technicians</div>
                                    </div>
                                    <div class="col-md-4 col-6 stat-item">
                                        <div class="stat-value"><?php echo $stats['active_techs']; ?></div>
                                        <div class="stat-label">Active</div>
                                    </div>
                                    <div class="col-md-4 col-12 stat-item">
                                        <div class="stat-value"><?php echo $stats['senior_techs']; ?></div>
                                        <div class="stat-label">Senior Technicians</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Technicians Grid -->
                    <div class="row">
                        <?php while($tech = $result_techs->fetch_assoc()): ?>
                        <div class="col-xl-4 col-md-6">
                            <div class="card tech-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-start mb-3">
                                        <div class="flex-shrink-0">
                                            <?php if($tech['profile_picture']): ?>
                                                <img src="<?php echo $tech['profile_picture']; ?>" alt="Technician" class="tech-avatar">
                                            <?php else: ?>
                                                <div class="tech-avatar bg-info text-white d-flex align-items-center justify-content-center" style="font-size: 1.75rem;">
                                                    <?php echo strtoupper(substr($tech['full_name'], 0, 1)); ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h5 class="mb-1">
                                                <?php echo htmlspecialchars($tech['full_name']); ?>
                                                <?php if($tech['is_senior_tech']): ?>
                                                    <i class="ri-medal-line text-warning" title="Senior Technician"></i>
                                                <?php endif; ?>
                                            </h5>
                                            <p class="text-muted mb-2">
                                                <small>License: <?php echo htmlspecialchars($tech['license_number']); ?></small>
                                            </p>
                                            <span class="status-badge status-<?php echo strtolower($tech['status']); ?>">
                                                <?php echo ucfirst($tech['status']); ?>
                                            </span>
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <?php if($tech['qualification']): ?>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="text-muted"><i class="ri-award-line me-1"></i>Qualification:</span>
                                            <strong><?php echo htmlspecialchars($tech['qualification']); ?></strong>
                                        </div>
                                        <?php endif; ?>

                                        <?php if($tech['specializations']): 
                                            $specializations = json_decode($tech['specializations'], true);
                                            if($specializations && count($specializations) > 0):
                                        ?>
                                        <div class="mb-2">
                                            <small class="text-muted d-block mb-1"><i class="ri-microscope-line me-1"></i>Specializations:</small>
                                            <div>
                                                <?php foreach($specializations as $spec): ?>
                                                    <span class="specialization-tag"><?php echo htmlspecialchars($spec); ?></span>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                        <?php endif; endif; ?>

                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="text-muted"><i class="ri-phone-line me-1"></i>Phone:</span>
                                            <strong><?php echo htmlspecialchars($tech['phone_primary']); ?></strong>
                                        </div>

                                        <?php if($tech['branch_name']): ?>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="text-muted"><i class="ri-map-pin-line me-1"></i>Branch:</span>
                                            <strong><?php echo htmlspecialchars($tech['branch_name']); ?></strong>
                                        </div>
                                        <?php endif; ?>

                                        <?php if($tech['certifications']): 
                                            $certifications = json_decode($tech['certifications'], true);
                                            if($certifications && count($certifications) > 0):
                                        ?>
                                        <div class="mt-2">
                                            <small class="text-muted d-block mb-1"><i class="ri-medal-line me-1"></i>Certifications:</small>
                                            <div>
                                                <?php foreach($certifications as $cert): ?>
                                                    <span class="specialization-tag bg-success text-white"><?php echo htmlspecialchars($cert); ?></span>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                        <?php endif; endif; ?>
                                    </div>

                                    <div class="row text-center mb-3">
                                        <div class="col-6">
                                            <div class="p-2 bg-light rounded">
                                                <h5 class="mb-0 text-warning"><?php echo $tech['pending_orders']; ?></h5>
                                                <small class="text-muted">Pending Orders</small>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="p-2 bg-light rounded">
                                                <h5 class="mb-0 text-success"><?php echo $tech['today_tests']; ?></h5>
                                                <small class="text-muted">Tests Today</small>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="d-flex gap-2">
                                        <a href="view_technician.php?id=<?php echo $tech['tech_id']; ?>" class="btn btn-sm btn-info flex-fill">
                                            <i class="ri-eye-line align-middle"></i> View
                                        </a>
                                        <a href="edit_technician.php?id=<?php echo $tech['tech_id']; ?>" class="btn btn-sm btn-primary flex-fill">
                                            <i class="ri-edit-line align-middle"></i> Edit
                                        </a>
                                        <a href="tech_workload.php?tech_id=<?php echo $tech['tech_id']; ?>" class="btn btn-sm btn-success flex-fill">
                                            <i class="ri-file-list-line align-middle"></i> Workload
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    </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/js/app.js"></script>
    
    <script>
        <?php if(isset($_SESSION['success_message'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: '<?php echo $_SESSION['success_message']; ?>',
                timer: 3000
            });
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>
    </script>
</body>
</html>

<?php $conn->close(); ?>