<?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 {
    $nurse_id = isset($_POST['nurse_id']) ? intval($_POST['nurse_id']) : 0;
    $shift_date = isset($_POST['date']) ? $_POST['date'] : '';
    $shift_type = isset($_POST['shift_type']) ? $_POST['shift_type'] : '';
    $ward_assignment = isset($_POST['ward_assignment']) ? $_POST['ward_assignment'] : null;
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : null;
    
    if ($nurse_id <= 0 || empty($shift_date) || empty($shift_type)) {
        throw new Exception('Missing required fields');
    }
    
    // Validate shift type
    $valid_shifts = ['DAY', 'NIGHT', 'OFF'];
    if (!in_array($shift_type, $valid_shifts)) {
        throw new Exception('Invalid shift type');
    }
    
    $conn->begin_transaction();
    
    // Note: In production, you would have a nurse_shifts table
    // For now, we'll update the nurse's ward_assignments JSON
    // and create an activity log entry
    
    // Get current nurse info
    $nurse_sql = "SELECT n.*, u.first_name, u.last_name 
                  FROM nurses n
                  INNER JOIN users u ON n.user_id = u.user_id
                  WHERE n.nurse_id = ?";
    $stmt = $conn->prepare($nurse_sql);
    $stmt->bind_param('i', $nurse_id);
    $stmt->execute();
    $nurse = $stmt->get_result()->fetch_assoc();
    
    if (!$nurse) {
        throw new Exception('Nurse not found');
    }
    
    // Log the shift assignment
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                     new_values, ip_address, user_agent)
                     VALUES (?, 'ASSIGN_SHIFT', 'NURSING', ?, 'SHIFT', ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $user_id = $_SESSION['user_id'];
    $log_data = json_encode([
        'nurse_id' => $nurse_id,
        'nurse_name' => $nurse['first_name'] . ' ' . $nurse['last_name'],
        'date' => $shift_date,
        'shift_type' => $shift_type,
        'ward_assignment' => $ward_assignment,
        'notes' => $notes
    ]);
    $ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $stmt->bind_param('iisss', $user_id, $nurse_id, $log_data, $ip, $user_agent);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to log shift assignment');
    }
    
    // In production, insert into nurse_shifts table:
    /*
    $shift_sql = "INSERT INTO nurse_shifts (nurse_id, shift_date, shift_type, ward_assignment, notes, assigned_by)
                  VALUES (?, ?, ?, ?, ?, ?)
                  ON DUPLICATE KEY UPDATE 
                  shift_type = VALUES(shift_type),
                  ward_assignment = VALUES(ward_assignment),
                  notes = VALUES(notes),
                  assigned_by = VALUES(assigned_by)";
    */
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Shift assignment saved successfully'
    ]);
    
} catch (Exception $e) {
    if ($conn->connect_errno === 0) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>