<?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 {
    $week = isset($_POST['week']) ? $_POST['week'] : date('Y-\WW');
    
    // Parse the week
    $year = substr($week, 0, 4);
    $week_num = substr($week, 6);
    
    // Calculate week start and end dates
    $dto = new DateTime();
    $dto->setISODate($year, $week_num);
    $week_start = $dto->format('Y-m-d');
    $dto->modify('+6 days');
    $week_end = $dto->format('Y-m-d');
    
    // Get all active nurses
    $nurses_sql = "SELECT n.nurse_id, CONCAT(u.first_name, ' ', u.last_name) as nurse_name,
                   n.shift_type, n.ward_assignments, n.specialization
                   FROM nurses n
                   INNER JOIN users u ON n.user_id = u.user_id
                   WHERE n.is_active = 1
                   ORDER BY u.first_name, u.last_name";
    $nurses_result = $conn->query($nurses_sql);
    
    $html = '';
    
    while ($nurse = $nurses_result->fetch_assoc()) {
        $html .= '<tr>';
        $html .= '<td class="nurse-name-cell">';
        $html .= '<div>' . htmlspecialchars($nurse['nurse_name']) . '</div>';
        $html .= '<small class="text-muted">' . ucfirst($nurse['shift_type']) . ' Shift';
        if ($nurse['specialization']) {
            $html .= ' | ' . htmlspecialchars($nurse['specialization']);
        }
        $html .= '</small></td>';
        
        // Generate 7 days of shifts
        $current_date = new DateTime($week_start);
        for ($i = 0; $i < 7; $i++) {
            $date_str = $current_date->format('Y-m-d');
            $day_num = $current_date->format('N'); // 1=Mon, 7=Sun
            
            // Default shift pattern
            $shift = 'OFF';
            if ($day_num <= 5) { // Weekdays
                $shift = $nurse['shift_type'] === 'NIGHT' ? 'NIGHT' : 'DAY';
            } elseif ($day_num == 6 && $nurse['shift_type'] === 'ROTATING') {
                $shift = 'DAY'; // Saturday for rotating
            }
            
            // In production, fetch actual roster assignments from database
            // For now, using default patterns
            
            $cell_class = 'shift-cell shift-' . strtolower($shift);
            $badge_class = 'shift-badge shift-badge-' . strtolower($shift);
            
            $html .= '<td class="' . $cell_class . '" ';
            $html .= 'onclick="editShift(' . $nurse['nurse_id'] . ', \'' . $date_str . '\', \'' . $shift . '\')">';
            
            if ($shift !== 'OFF') {
                $html .= '<span class="' . $badge_class . '">' . $shift . '</span>';
            } else {
                $html .= '<span class="' . $badge_class . '">OFF</span>';
            }
            
            $html .= '</td>';
            
            $current_date->modify('+1 day');
        }
        
        $html .= '</tr>';
    }
    
    echo json_encode([
        'success' => true,
        'html' => $html,
        'week_start' => $week_start,
        'week_end' => $week_end
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>