<?php
require_once '../layouts/session.php';
require_once '../layouts/dbconn.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'HEAD_NURSE') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$conn = db_connect();

try {
    $start_date = isset($_POST['start_date']) ? $_POST['start_date'] : date('Y-m-d', strtotime('-30 days'));
    $end_date = isset($_POST['end_date']) ? $_POST['end_date'] : date('Y-m-d');
    
    // Get top 5 performers based on activity
    $sql = "SELECT n.nurse_id, CONCAT(u.first_name, ' ', u.last_name) as nurse_name,
            n.specialization,
            (SELECT COUNT(*) FROM vital_signs vs 
             WHERE vs.recorded_by = n.nurse_id 
             AND DATE(vs.recorded_date) BETWEEN ? AND ?) as vitals_count,
            (SELECT COUNT(*) FROM consultations c 
             WHERE c.doctor_id = n.nurse_id 
             AND c.consultation_type = 'NURSING_NOTE'
             AND DATE(c.consultation_date) BETWEEN ? AND ?) as notes_count
            FROM nurses n
            INNER JOIN users u ON n.user_id = u.user_id
            WHERE n.is_active = 1
            ORDER BY (vitals_count + notes_count) DESC
            LIMIT 5";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ssss', $start_date, $end_date, $start_date, $end_date);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $html = '';
    $rank = 1;
    
    while ($nurse = $result->fetch_assoc()) {
        $total_activities = $nurse['vitals_count'] + $nurse['notes_count'];
        
        // Calculate performance score
        $days = max((strtotime($end_date) - strtotime($start_date)) / 86400, 1);
        $performance = min(round(($total_activities / ($days * 5)) * 100), 100);
        
        $medal_icon = '';
        $medal_color = '';
        switch($rank) {
            case 1:
                $medal_icon = 'ri-medal-line';
                $medal_color = 'text-warning'; // Gold
                break;
            case 2:
                $medal_icon = 'ri-medal-2-line';
                $medal_color = 'text-secondary'; // Silver
                break;
            case 3:
                $medal_icon = 'ri-medal-line';
                $medal_color = 'text-danger'; // Bronze
                break;
            default:
                $medal_icon = 'ri-star-line';
                $medal_color = 'text-primary';
        }
        
        $html .= '<div class="nurse-profile-card">';
        $html .= '<div class="nurse-avatar">' . strtoupper(substr($nurse['nurse_name'], 0, 2)) . '</div>';
        $html .= '<div class="flex-fill">';
        $html .= '<div class="d-flex justify-content-between align-items-start">';
        $html .= '<div>';
        $html .= '<h6 class="mb-1">';
        $html .= '<i class="' . $medal_icon . ' ' . $medal_color . ' me-2"></i>';
        $html .= htmlspecialchars($nurse['nurse_name']);
        $html .= '</h6>';
        $html .= '<small class="text-muted">' . htmlspecialchars($nurse['specialization'] ?? 'General Nursing') . '</small>';
        $html .= '</div>';
        $html .= '<div class="text-end">';
        $html .= '<div class="performance-metric">';
        $html .= '<div class="metric-value" style="font-size: 1.25rem;">' . $performance . '%</div>';
        $html .= '<div class="metric-label">Score</div>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '<div class="row mt-2">';
        $html .= '<div class="col-6">';
        $html .= '<small class="text-muted">Vitals Recorded</small><br>';
        $html .= '<strong>' . number_format($nurse['vitals_count']) . '</strong>';
        $html .= '</div>';
        $html .= '<div class="col-6">';
        $html .= '<small class="text-muted">Notes Entered</small><br>';
        $html .= '<strong>' . number_format($nurse['notes_count']) . '</strong>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';
        
        $rank++;
    }
    
    if (empty($html)) {
        $html = '<div class="alert alert-info">';
        $html .= '<i class="ri-information-line me-2"></i>';
        $html .= 'No performance data available for the selected period.';
        $html .= '</div>';
    }
    
    echo json_encode([
        'success' => true,
        'html' => $html
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>