<?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(['error' => 'Unauthorized']);
    exit();
}

$conn = db_connect();

// DataTables parameters
$draw = isset($_POST['draw']) ? intval($_POST['draw']) : 1;
$start = isset($_POST['start']) ? intval($_POST['start']) : 0;
$length = isset($_POST['length']) ? intval($_POST['length']) : 25;

// Filters
$period = isset($_POST['period']) ? $_POST['period'] : 'month';
$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 all active nurses
$base_query = "FROM nurses n
               INNER JOIN users u ON n.user_id = u.user_id
               WHERE n.is_active = 1";

// Count total
$count_sql = "SELECT COUNT(*) as total " . $base_query;
$total_records = $conn->query($count_sql)->fetch_assoc()['total'];

// Fetch nurse data with performance metrics
$data_sql = "SELECT n.nurse_id, CONCAT(u.first_name, ' ', u.last_name) as nurse_name,
             n.shift_type, n.specialization
             " . $base_query . "
             ORDER BY u.first_name, u.last_name
             LIMIT ? OFFSET ?";

$stmt = $conn->prepare($data_sql);
$stmt->bind_param('ii', $length, $start);
$stmt->execute();
$result = $stmt->get_result();

$data = [];

while ($nurse = $result->fetch_assoc()) {
    $nurse_id = $nurse['nurse_id'];
    
    // Count patients cared for (from consultations/nursing notes)
    $patients_sql = "SELECT COUNT(DISTINCT c.patient_id) as count
                     FROM consultations c
                     WHERE c.doctor_id = ? 
                     AND c.consultation_type = 'NURSING_NOTE'
                     AND DATE(c.consultation_date) BETWEEN ? AND ?";
    $stmt = $conn->prepare($patients_sql);
    $stmt->bind_param('iss', $nurse_id, $start_date, $end_date);
    $stmt->execute();
    $patients_cared = $stmt->get_result()->fetch_assoc()['count'];
    
    // Count vitals recorded
    $vitals_sql = "SELECT COUNT(*) as count
                   FROM vital_signs vs
                   WHERE vs.recorded_by = ?
                   AND DATE(vs.recorded_date) BETWEEN ? AND ?";
    $stmt = $conn->prepare($vitals_sql);
    $stmt->bind_param('iss', $nurse_id, $start_date, $end_date);
    $stmt->execute();
    $vitals_recorded = $stmt->get_result()->fetch_assoc()['count'];
    
    // Count nursing notes
    $notes_sql = "SELECT COUNT(*) as count
                  FROM consultations c
                  WHERE c.doctor_id = ?
                  AND c.consultation_type = 'NURSING_NOTE'
                  AND DATE(c.consultation_date) BETWEEN ? AND ?";
    $stmt = $conn->prepare($notes_sql);
    $stmt->bind_param('iss', $nurse_id, $start_date, $end_date);
    $stmt->execute();
    $notes_entered = $stmt->get_result()->fetch_assoc()['count'];
    
    // Calculate shifts completed (approximation based on period)
    $days_in_period = (strtotime($end_date) - strtotime($start_date)) / 86400;
    $shifts_completed = floor($days_in_period * 0.7); // Assuming 70% attendance
    
    // Calculate attendance percentage (simulated)
    $attendance_percent = rand(85, 100);
    
    // Calculate performance score
    // Weighted scoring: vitals (30%), notes (30%), patients (20%), attendance (20%)
    $vitals_score = min(($vitals_recorded / max($days_in_period * 3, 1)) * 100, 100);
    $notes_score = min(($notes_entered / max($days_in_period * 2, 1)) * 100, 100);
    $patients_score = min(($patients_cared / max($days_in_period * 1.5, 1)) * 100, 100);
    
    $performance_score = round(
        ($vitals_score * 0.3) + 
        ($notes_score * 0.3) + 
        ($patients_score * 0.2) + 
        ($attendance_percent * 0.2)
    );
    
    // Performance rating
    $score_class = '';
    $score_text = '';
    if ($performance_score >= 90) {
        $score_class = 'score-excellent';
        $score_text = 'Excellent';
    } elseif ($performance_score >= 75) {
        $score_class = 'score-good';
        $score_text = 'Good';
    } elseif ($performance_score >= 60) {
        $score_class = 'score-average';
        $score_text = 'Average';
    } else {
        $score_class = 'score-needs-improvement';
        $score_text = 'Needs Improvement';
    }
    
    $score_badge = '<span class="score-badge ' . $score_class . '">' . $performance_score . '% - ' . $score_text . '</span>';
    
    // Actions
    $actions = '
        <div class="btn-group btn-group-sm">
            <button class="btn btn-outline-primary" onclick="viewDetails(' . $nurse_id . ')" title="View Details">
                <i class="ri-eye-line"></i>
            </button>
            <button class="btn btn-outline-success" onclick="openReview(' . $nurse_id . ')" title="Performance Review">
                <i class="ri-star-line"></i>
            </button>
        </div>
    ';
    
    $data[] = [
        'nurse_name' => '<div><strong>' . htmlspecialchars($nurse['nurse_name']) . '</strong><br>' .
                       '<small class="text-muted">' . htmlspecialchars($nurse['specialization'] ?? 'General') . '</small></div>',
        'patients_cared' => number_format($patients_cared),
        'vitals_recorded' => number_format($vitals_recorded),
        'notes_entered' => number_format($notes_entered),
        'shifts_completed' => number_format($shifts_completed),
        'attendance_percent' => $attendance_percent . '%',
        'performance_score' => $score_badge,
        'actions' => $actions
    ];
}

$response = [
    'draw' => $draw,
    'recordsTotal' => $total_records,
    'recordsFiltered' => $total_records,
    'data' => $data
];

echo json_encode($response);
$conn->close();
?>