<?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
$shift_type = isset($_POST['shift_type']) ? $_POST['shift_type'] : '';
$date = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');

// Determine current shift based on time
$current_hour = date('H');
if (empty($shift_type)) {
    $shift_type = ($current_hour >= 6 && $current_hour < 18) ? 'DAY' : 'NIGHT';
}

// Get nurses on current shift
$base_query = "FROM nurses n
               INNER JOIN users u ON n.user_id = u.user_id
               WHERE n.is_active = 1
               AND (n.shift_type = ? OR n.shift_type = 'ROTATING')";

$params = [$shift_type];
$types = 's';

// Count total
$count_sql = "SELECT COUNT(*) as total " . $base_query;
$stmt = $conn->prepare($count_sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$total_records = $stmt->get_result()->fetch_assoc()['total'];

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

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

$data = [];

while ($row = $result->fetch_assoc()) {
    // Parse ward assignments
    $ward_assignments = json_decode($row['ward_assignments'], true);
    $ward_display = 'Not Assigned';
    if (is_array($ward_assignments) && !empty($ward_assignments)) {
        $ward_display = implode(', ', array_map(function($w) {
            return str_replace('_', ' ', $w);
        }, $ward_assignments));
    }
    
    // Shift type badge
    $shift_badge = '';
    switch($row['shift_type']) {
        case 'DAY':
            $shift_badge = '<span class="badge badge-day-shift">Day Shift</span>';
            break;
        case 'NIGHT':
            $shift_badge = '<span class="badge badge-night-shift">Night Shift</span>';
            break;
        case 'ROTATING':
            $shift_badge = '<span class="badge badge-rotating">Rotating</span>';
            break;
    }
    
    // Shift time
    $shift_time = '';
    if ($row['shift_type'] === 'DAY' || ($row['shift_type'] === 'ROTATING' && $shift_type === 'DAY')) {
        $shift_time = '6:00 AM - 6:00 PM';
    } else {
        $shift_time = '6:00 PM - 6:00 AM';
    }
    
    // Status (simulated - in production, check actual clock-in status)
    $is_on_duty = true; // In production, check from attendance table
    $status = $is_on_duty ? 
        '<span class="nurse-status status-on-duty"><i class="ri-checkbox-circle-line"></i> On Duty</span>' :
        '<span class="nurse-status status-off-duty"><i class="ri-close-circle-line"></i> Off Duty</span>';
    
    // Actions
    $actions = '
        <div class="btn-group btn-group-sm">
            <button class="btn btn-outline-primary" onclick="viewNurseDetails(' . $row['nurse_id'] . ')" title="View Details">
                <i class="ri-eye-line"></i>
            </button>
            <button class="btn btn-outline-success" onclick="assignTask(' . $row['nurse_id'] . ')" title="Assign Task">
                <i class="ri-task-line"></i>
            </button>
        </div>
    ';
    
    $data[] = [
        'nurse_name' => htmlspecialchars($row['nurse_name']),
        'shift_type' => $shift_badge,
        'ward_assignment' => $ward_display,
        'shift_time' => $shift_time,
        'status' => $status,
        'actions' => $actions
    ];
}

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

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