<?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 {
    // Determine current shift
    $current_hour = date('H');
    $current_shift = ($current_hour >= 6 && $current_hour < 18) ? 'DAY' : 'NIGHT';
    
    // Get shift statistics
    $stats_sql = "SELECT 
                  COUNT(DISTINCT n.nurse_id) as total_nurses,
                  COUNT(DISTINCT CASE WHEN n.shift_type = 'DAY' THEN n.nurse_id END) as day_shift,
                  COUNT(DISTINCT CASE WHEN n.shift_type = 'NIGHT' THEN n.nurse_id END) as night_shift,
                  COUNT(DISTINCT CASE WHEN n.shift_type = 'ROTATING' THEN n.nurse_id END) as rotating_shift
                  FROM nurses n
                  WHERE n.is_active = 1";
    
    $result = $conn->query($stats_sql);
    $stats = $result->fetch_assoc();
    
    // Calculate who should be on duty now
    $on_duty_sql = "SELECT COUNT(*) as current_staff
                    FROM nurses n
                    WHERE n.is_active = 1
                    AND (n.shift_type = ? OR n.shift_type = 'ROTATING')";
    $stmt = $conn->prepare($on_duty_sql);
    $stmt->bind_param('s', $current_shift);
    $stmt->execute();
    $on_duty = $stmt->get_result()->fetch_assoc();
    
    // Calculate off duty (approximation)
    $off_duty = $stats['total_nurses'] - $on_duty['current_staff'];
    
    echo json_encode([
        'success' => true,
        'current_staff' => $on_duty['current_staff'],
        'day_shift' => $stats['day_shift'],
        'night_shift' => $stats['night_shift'],
        'off_duty' => $off_duty,
        'rotating' => $stats['rotating_shift'],
        'current_shift_type' => $current_shift
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>