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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Fetch current user details
$current_user_id = $_SESSION['user_id'];
$sql_current_user = "SELECT u.*, ur.role_name FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_current = $conn->prepare($sql_current_user);
$stmt_current->bind_param("i", $current_user_id);
$stmt_current->execute();
$current_user = $stmt_current->get_result()->fetch_assoc();

// Get filter parameters
$role_filter = $_GET['role_filter'] ?? '';
$branch_filter = $_GET['branch_filter'] ?? '';
$period_filter = $_GET['period_filter'] ?? '30'; // Default to 30 days

// Date range based on period
$date_condition = "DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL ? DAY)";
switch($period_filter) {
    case '7':
        $days = 7;
        break;
    case '30':
        $days = 30;
        break;
    case '90':
        $days = 90;
        break;
    case '365':
        $days = 365;
        break;
    default:
        $days = 30;
}

// Build filters
$where_conditions = array("u.status = 'ACTIVE'");
$params = array();
$param_types = "";

if (!empty($role_filter)) {
    $where_conditions[] = "u.role_id = ?";
    $params[] = $role_filter;
    $param_types .= "i";
}

if (!empty($branch_filter)) {
    $where_conditions[] = "u.branch_id = ?";
    $params[] = $branch_filter;
    $param_types .= "i";
}

$where_clause = implode(" AND ", $where_conditions);

// Get overall staff statistics
$stats_query = "SELECT 
    COUNT(*) as total_active_staff,
    COUNT(CASE WHEN last_login >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as active_last_week,
    COUNT(CASE WHEN last_login >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as active_last_month,
    COUNT(CASE WHEN last_login IS NULL THEN 1 END) as never_logged_in,
    AVG(commission_rate) as avg_commission_rate
    FROM users u 
    WHERE $where_clause";

$stats_stmt = $conn->prepare($stats_query);
if (!empty($params)) {
    $stats_stmt->bind_param($param_types, ...$params);
}
$stats_stmt->execute();
$overall_stats = $stats_stmt->get_result()->fetch_assoc();

// Get doctor performance
$doctor_performance_query = "SELECT 
    u.user_id,
    u.full_name,
    u.staff_number,
    d.specialization,
    d.consultation_fee,
    d.commission_rate,
    b.branch_name,
    COUNT(c.consultation_id) as total_consultations,
    COUNT(CASE WHEN c.status = 'COMPLETED' THEN 1 END) as completed_consultations,
    COUNT(CASE WHEN DATE(c.started_at) >= DATE_SUB(CURDATE(), INTERVAL ? DAY) THEN 1 END) as period_consultations,
    COALESCE(SUM(CASE WHEN c.status = 'COMPLETED' THEN c.consultation_fee END), 0) as total_revenue,
    COALESCE(SUM(CASE WHEN c.status = 'COMPLETED' THEN c.doctor_commission END), 0) as total_commission,
    COUNT(DISTINCT c.patient_id) as unique_patients,
    COALESCE(AVG(CASE WHEN c.status = 'COMPLETED' THEN c.consultation_fee END), 0) as avg_consultation_fee,
    u.last_login
    FROM users u
    JOIN user_roles ur ON u.role_id = ur.role_id
    JOIN doctors d ON u.user_id = d.user_id
    LEFT JOIN branches b ON u.branch_id = b.branch_id
    LEFT JOIN consultations c ON d.doctor_id = c.doctor_id
    WHERE u.status = 'ACTIVE' AND ur.role_name IN ('Doctor', 'Senior Doctor')";

$doctor_params = array($days);
$doctor_param_types = "i";

if (!empty($role_filter)) {
    $doctor_performance_query .= " AND u.role_id = ?";
    $doctor_params[] = $role_filter;
    $doctor_param_types .= "i";
}

if (!empty($branch_filter)) {
    $doctor_performance_query .= " AND u.branch_id = ?";
    $doctor_params[] = $branch_filter;
    $doctor_param_types .= "i";
}

$doctor_performance_query .= " GROUP BY u.user_id, u.full_name, u.staff_number, d.specialization, d.consultation_fee, d.commission_rate, b.branch_name, u.last_login
    ORDER BY total_revenue DESC";

$doctor_stmt = $conn->prepare($doctor_performance_query);
$doctor_stmt->bind_param($doctor_param_types, ...$doctor_params);
$doctor_stmt->execute();
$doctor_performance = $doctor_stmt->get_result();

// Get nurse performance
$nurse_performance_query = "SELECT 
    u.user_id,
    u.full_name,
    u.staff_number,
    n.qualification,
    n.shift_type,
    b.branch_name,
    COUNT(pp.procedure_id) as total_procedures,
    COUNT(CASE WHEN pp.status = 'COMPLETED' THEN 1 END) as completed_procedures,
    COUNT(CASE WHEN DATE(pp.created_at) >= DATE_SUB(CURDATE(), INTERVAL ? DAY) THEN 1 END) as period_procedures,
    COALESCE(SUM(CASE WHEN pp.status = 'COMPLETED' THEN pp.cost END), 0) as total_procedure_revenue,
    u.last_login
    FROM users u
    JOIN user_roles ur ON u.role_id = ur.role_id
    JOIN nurses n ON u.user_id = n.user_id
    LEFT JOIN branches b ON u.branch_id = b.branch_id
    LEFT JOIN patient_procedures pp ON (pp.performed_by = u.user_id OR pp.assisted_by = u.user_id)
    WHERE u.status = 'ACTIVE' AND ur.role_name = 'Nurse'";

$nurse_params = array($days);
$nurse_param_types = "i";

if (!empty($role_filter)) {
    $nurse_performance_query .= " AND u.role_id = ?";
    $nurse_params[] = $role_filter;
    $nurse_param_types .= "i";
}

if (!empty($branch_filter)) {
    $nurse_performance_query .= " AND u.branch_id = ?";
    $nurse_params[] = $branch_filter;
    $nurse_param_types .= "i";
}

$nurse_performance_query .= " GROUP BY u.user_id, u.full_name, u.staff_number, n.qualification, n.shift_type, b.branch_name, u.last_login
    ORDER BY total_procedures DESC";

$nurse_stmt = $conn->prepare($nurse_performance_query);
$nurse_stmt->bind_param($nurse_param_types, ...$nurse_params);
$nurse_stmt->execute();
$nurse_performance = $nurse_stmt->get_result();

// Get lab technician performance
$lab_performance_query = "SELECT 
    u.user_id,
    u.full_name,
    u.staff_number,
    b.branch_name,
    COUNT(lot.order_test_id) as total_tests,
    COUNT(CASE WHEN lot.status = 'COMPLETED' THEN 1 END) as completed_tests,
    COUNT(CASE WHEN DATE(lot.completed_at) >= DATE_SUB(CURDATE(), INTERVAL ? DAY) THEN 1 END) as period_tests,
    COALESCE(SUM(CASE WHEN lot.status = 'COMPLETED' THEN lot.test_cost END), 0) as total_test_revenue,
    u.last_login
    FROM users u
    JOIN user_roles ur ON u.role_id = ur.role_id
    LEFT JOIN branches b ON u.branch_id = b.branch_id
    LEFT JOIN lab_order_tests lot ON lot.tested_by = u.user_id
    WHERE u.status = 'ACTIVE' AND ur.role_name IN ('Lab Technician', 'Lab Manager')";

$lab_params = array($days);
$lab_param_types = "i";

if (!empty($role_filter)) {
    $lab_performance_query .= " AND u.role_id = ?";
    $lab_params[] = $role_filter;
    $lab_param_types .= "i";
}

if (!empty($branch_filter)) {
    $lab_performance_query .= " AND u.branch_id = ?";
    $lab_params[] = $branch_filter;
    $lab_param_types .= "i";
}

$lab_performance_query .= " GROUP BY u.user_id, u.full_name, u.staff_number, b.branch_name, u.last_login
    ORDER BY total_tests DESC";

$lab_stmt = $conn->prepare($lab_performance_query);
$lab_stmt->bind_param($lab_param_types, ...$lab_params);
$lab_stmt->execute();
$lab_performance = $lab_stmt->get_result();

// Get roles for filter dropdown
$roles_query = "SELECT role_id, role_name FROM user_roles WHERE is_active = 1 ORDER BY role_name";
$roles_result = $conn->query($roles_query);

// Get branches for filter dropdown
$branches_query = "SELECT branch_id, branch_name FROM branches WHERE is_active = 1 ORDER BY branch_name";
$branches_result = $conn->query($branches_query);

// Get top performers by revenue
$top_performers_query = "SELECT 
    u.user_id,
    u.full_name,
    ur.role_name,
    b.branch_name,
    COALESCE(
        (SELECT SUM(c.consultation_fee) FROM consultations c JOIN doctors d ON c.doctor_id = d.doctor_id WHERE d.user_id = u.user_id AND c.status = 'COMPLETED'),
        0
    ) +
    COALESCE(
        (SELECT SUM(lot.test_cost) FROM lab_order_tests lot WHERE lot.tested_by = u.user_id AND lot.status = 'COMPLETED'),
        0
    ) as total_revenue
    FROM users u
    JOIN user_roles ur ON u.role_id = ur.role_id
    LEFT JOIN branches b ON u.branch_id = b.branch_id
    WHERE u.status = 'ACTIVE' AND ur.role_name IN ('Doctor', 'Senior Doctor', 'Lab Technician', 'Lab Manager')
    HAVING total_revenue > 0
    ORDER BY total_revenue DESC
    LIMIT 10";

$top_performers_result = $conn->query($top_performers_query);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Staff Performance - Healthcare EMR System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        /* Use the same styling from dashboard */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .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;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* Filter Card */
        .filter-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: 2rem;
        }
        
        /* Performance Cards */
        .performance-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .performance-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        
        .performance-header {
            padding: 1.5rem;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .performance-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .performance-body {
            max-height: 400px;
            overflow-y: auto;
        }
        
        .performance-item {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .performance-item:last-child {
            border-bottom: none;
        }
        
        .performance-item:hover {
            background: #f8fafc;
        }
        
        .staff-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .staff-avatar {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: #3b82f6;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.75rem;
        }
        
        .staff-details {
            flex: 1;
        }
        
        .staff-name {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .staff-meta {
            color: #64748b;
            font-size: 0.75rem;
        }
        
        .performance-metrics {
            text-align: right;
            display: flex;
            flex-direction: column;
            gap: 0.25rem;
        }
        
        .metric-primary {
            font-weight: 700;
            color: #059669;
            font-size: 0.875rem;
        }
        
        .metric-secondary {
            color: #64748b;
            font-size: 0.75rem;
        }
        
        /* Table Cards */
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* Form Controls */
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
        }
        
        /* Status Badges */
        .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-excellent { background: #dcfce7; color: #166534; }
        .status-good { background: #dbeafe; color: #1d4ed8; }
        .status-average { background: #fef3c7; color: #92400e; }
        .status-poor { background: #fee2e2; color: #991b1b; }
        
        /* Performance Rankings */
        .ranking-badge {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.75rem;
            font-weight: 700;
            color: white;
        }
        
        .rank-1 { background: #fbbf24; } /* Gold */
        .rank-2 { background: #9ca3af; } /* Silver */
        .rank-3 { background: #d97706; } /* Bronze */
        .rank-other { background: #64748b; } /* Gray */
        
        /* Top Performers */
        .top-performers {
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .top-performers-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
            text-align: center;
        }
        
        .top-performer-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 0.75rem;
            background: white;
            border-radius: 8px;
            margin-bottom: 0.75rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .top-performer-item:last-child {
            margin-bottom: 0;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .performance-cards {
                grid-template-columns: 1fr;
            }
            
            .data-table {
                font-size: 0.75rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 0.5rem;
            }
        }
    </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 Header -->
                    <div class="page-header">
                        <h1 class="page-title">Staff Performance</h1>
                        <p class="page-subtitle">Monitor and analyze staff performance across all departments</p>
                    </div>

                    <!-- Overall Stats -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $overall_stats['total_active_staff']; ?></div>
                            <div class="stat-label">Active Staff</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $overall_stats['active_last_week']; ?></div>
                            <div class="stat-label">Active This Week</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $overall_stats['active_last_month']; ?></div>
                            <div class="stat-label">Active This Month</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $overall_stats['never_logged_in']; ?></div>
                            <div class="stat-label">Never Logged In</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($overall_stats['avg_commission_rate'], 1); ?>%</div>
                            <div class="stat-label">Avg Commission Rate</div>
                        </div>
                    </div>

                    <!-- Filter Card -->
                    <div class="filter-card">
                        <form method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">Role</label>
                                <select class="form-select" name="role_filter">
                                    <option value="">All Roles</option>
                                    <?php while ($role = $roles_result->fetch_assoc()): ?>
                                        <option value="<?php echo $role['role_id']; ?>" <?php echo $role_filter == $role['role_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($role['role_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Branch</label>
                                <select class="form-select" name="branch_filter">
                                    <option value="">All Branches</option>
                                    <?php while ($branch = $branches_result->fetch_assoc()): ?>
                                        <option value="<?php echo $branch['branch_id']; ?>" <?php echo $branch_filter == $branch['branch_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($branch['branch_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Period</label>
                                <select class="form-select" name="period_filter">
                                    <option value="7" <?php echo $period_filter == '7' ? 'selected' : ''; ?>>Last 7 Days</option>
                                    <option value="30" <?php echo $period_filter == '30' ? 'selected' : ''; ?>>Last 30 Days</option>
                                    <option value="90" <?php echo $period_filter == '90' ? 'selected' : ''; ?>>Last 90 Days</option>
                                    <option value="365" <?php echo $period_filter == '365' ? 'selected' : ''; ?>>Last Year</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">Filter</button>
                                    <a href="staff_performance.php" class="btn btn-outline-secondary">Clear</a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Top Performers -->
                    <?php if ($top_performers_result->num_rows > 0): ?>
                    <div class="top-performers">
                        <h3 class="top-performers-title">🏆 Top Revenue Generators</h3>
                        <?php 
                        $rank = 1;
                        while ($performer = $top_performers_result->fetch_assoc()): 
                        ?>
                        <div class="top-performer-item">
                            <div class="ranking-badge <?php echo $rank <= 3 ? 'rank-' . $rank : 'rank-other'; ?>">
                                <?php echo $rank; ?>
                            </div>
                            <div class="staff-info">
                                <div class="staff-avatar">
                                    <?php echo strtoupper(substr($performer['full_name'], 0, 2)); ?>
                                </div>
                                <div class="staff-details">
                                    <div class="staff-name"><?php echo htmlspecialchars($performer['full_name']); ?></div>
                                    <div class="staff-meta">
                                        <?php echo htmlspecialchars($performer['role_name']); ?>
                                        <?php if ($performer['branch_name']): ?>
                                            | <?php echo htmlspecialchars($performer['branch_name']); ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <div class="performance-metrics">
                                <div class="metric-primary">KES <?php echo number_format($performer['total_revenue']); ?></div>
                                <div class="metric-secondary">Total Revenue</div>
                            </div>
                        </div>
                        <?php 
                        $rank++;
                        endwhile; 
                        ?>
                    </div>
                    <?php endif; ?>

                    <!-- Performance Cards -->
                    <div class="performance-cards">
                        <!-- Doctor Performance -->
                        <?php if ($doctor_performance->num_rows > 0): ?>
                        <div class="performance-card">
                            <div class="performance-header">
                                <h3 class="performance-title">Doctor Performance</h3>
                            </div>
                            <div class="performance-body">
                                <?php while ($doctor = $doctor_performance->fetch_assoc()): ?>
                                <div class="performance-item">
                                    <div class="staff-info">
                                        <div class="staff-avatar">
                                            <?php echo strtoupper(substr($doctor['full_name'], 0, 2)); ?>
                                        </div>
                                        <div class="staff-details">
                                            <div class="staff-name">
                                                <a href="view_user.php?id=<?php echo $doctor['user_id']; ?>" style="color: #1e293b; text-decoration: none;">
                                                    Dr. <?php echo htmlspecialchars($doctor['full_name']); ?>
                                                </a>
                                            </div>
                                            <div class="staff-meta">
                                                <?php echo htmlspecialchars($doctor['specialization'] ?: 'General Practice'); ?>
                                                <?php if ($doctor['branch_name']): ?>
                                                    | <?php echo htmlspecialchars($doctor['branch_name']); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="performance-metrics">
                                        <div class="metric-primary">KES <?php echo number_format($doctor['total_revenue']); ?></div>
                                        <div class="metric-secondary"><?php echo $doctor['completed_consultations']; ?> consultations</div>
                                        <div class="metric-secondary"><?php echo $doctor['unique_patients']; ?> patients</div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Nurse Performance -->
                        <?php if ($nurse_performance->num_rows > 0): ?>
                        <div class="performance-card">
                            <div class="performance-header">
                                <h3 class="performance-title">Nurse Performance</h3>
                            </div>
                            <div class="performance-body">
                                <?php while ($nurse = $nurse_performance->fetch_assoc()): ?>
                                <div class="performance-item">
                                    <div class="staff-info">
                                        <div class="staff-avatar">
                                            <?php echo strtoupper(substr($nurse['full_name'], 0, 2)); ?>
                                        </div>
                                        <div class="staff-details">
                                            <div class="staff-name">
                                                <a href="view_user.php?id=<?php echo $nurse['user_id']; ?>" style="color: #1e293b; text-decoration: none;">
                                                    <?php echo htmlspecialchars($nurse['full_name']); ?>
                                                </a>
                                            </div>
                                            <div class="staff-meta">
                                                <?php echo ucfirst(strtolower($nurse['shift_type'])); ?> Shift
                                                <?php if ($nurse['branch_name']): ?>
                                                    | <?php echo htmlspecialchars($nurse['branch_name']); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="performance-metrics">
                                        <div class="metric-primary"><?php echo $nurse['completed_procedures']; ?></div>
                                        <div class="metric-secondary">Completed Procedures</div>
                                        <div class="metric-secondary">KES <?php echo number_format($nurse['total_procedure_revenue']); ?> revenue</div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Lab Performance -->
                        <?php if ($lab_performance->num_rows > 0): ?>
                        <div class="performance-card">
                            <div class="performance-header">
                                <h3 class="performance-title">Lab Technician Performance</h3>
                            </div>
                            <div class="performance-body">
                                <?php while ($lab = $lab_performance->fetch_assoc()): ?>
                                <div class="performance-item">
                                    <div class="staff-info">
                                        <div class="staff-avatar">
                                            <?php echo strtoupper(substr($lab['full_name'], 0, 2)); ?>
                                        </div>
                                        <div class="staff-details">
                                            <div class="staff-name">
                                                <a href="view_user.php?id=<?php echo $lab['user_id']; ?>" style="color: #1e293b; text-decoration: none;">
                                                    <?php echo htmlspecialchars($lab['full_name']); ?>
                                                </a>
                                            </div>
                                            <div class="staff-meta">
                                                Lab Technician
                                                <?php if ($lab['branch_name']): ?>
                                                    | <?php echo htmlspecialchars($lab['branch_name']); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="performance-metrics">
                                        <div class="metric-primary"><?php echo $lab['completed_tests']; ?></div>
                                        <div class="metric-secondary">Tests Completed</div>
                                        <div class="metric-secondary">KES <?php echo number_format($lab['total_test_revenue']); ?> revenue</div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Detailed Doctor Performance Table -->
                    <?php 
                    // Reset the result pointer for detailed table
                    $doctor_stmt->execute();
                    $doctor_performance_detail = $doctor_stmt->get_result();
                    if ($doctor_performance_detail->num_rows > 0): 
                    ?>
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Detailed Doctor Performance</h3>
                        </div>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Doctor</th>
                                    <th>Specialization</th>
                                    <th>Total Consultations</th>
                                    <th>Completed</th>
                                    <th>Last <?php echo $days; ?> Days</th>
                                    <th>Total Revenue</th>
                                    <th>Commission Earned</th>
                                    <th>Avg Fee</th>
                                    <th>Last Login</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($doctor = $doctor_performance_detail->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div style="font-weight: 600;">
                                            <a href="view_user.php?id=<?php echo $doctor['user_id']; ?>" style="color: #3b82f6; text-decoration: none;">
                                                Dr. <?php echo htmlspecialchars($doctor['full_name']); ?>
                                            </a>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            <?php echo $doctor['staff_number']; ?>
                                            <?php if ($doctor['branch_name']): ?>
                                                | <?php echo htmlspecialchars($doctor['branch_name']); ?>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td><?php echo htmlspecialchars($doctor['specialization'] ?: 'General Practice'); ?></td>
                                    <td style="font-weight: 600;"><?php echo $doctor['total_consultations']; ?></td>
                                    <td style="font-weight: 600; color: #059669;"><?php echo $doctor['completed_consultations']; ?></td>
                                    <td style="font-weight: 600;"><?php echo $doctor['period_consultations']; ?></td>
                                    <td style="font-weight: 600; color: #059669;">KES <?php echo number_format($doctor['total_revenue']); ?></td>
                                    <td style="font-weight: 600; color: #d97706;">KES <?php echo number_format($doctor['total_commission']); ?></td>
                                    <td style="font-weight: 600;">KES <?php echo number_format($doctor['avg_consultation_fee']); ?></td>
                                    <td style="color: #64748b;">
                                        <?php echo $doctor['last_login'] ? date('M j, Y', strtotime($doctor['last_login'])) : 'Never'; ?>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </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>
        $(document).ready(function() {
            // Auto-submit form on filter change
            $('.form-select').on('change', function() {
                $(this).closest('form').submit();
            });
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

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