<?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 {
    $handover_type = isset($_POST['handover_type']) ? $_POST['handover_type'] : '';
    $outgoing_nurse = isset($_POST['outgoing_nurse']) ? intval($_POST['outgoing_nurse']) : 0;
    $incoming_nurse = isset($_POST['incoming_nurse']) ? intval($_POST['incoming_nurse']) : 0;
    $patient_updates = isset($_POST['patient_updates']) ? trim($_POST['patient_updates']) : '';
    $pending_tasks = isset($_POST['pending_tasks']) ? trim($_POST['pending_tasks']) : '';
    $critical_notes = isset($_POST['critical_notes']) ? trim($_POST['critical_notes']) : '';
    
    if (empty($handover_type) || $outgoing_nurse <= 0 || $incoming_nurse <= 0 || empty($patient_updates)) {
        throw new Exception('Missing required fields');
    }
    
    if ($outgoing_nurse === $incoming_nurse) {
        throw new Exception('Outgoing and incoming nurses cannot be the same');
    }
    
    $conn->begin_transaction();
    
    // Get nurse names
    $nurse_sql = "SELECT n.nurse_id, CONCAT(u.first_name, ' ', u.last_name) as nurse_name
                  FROM nurses n
                  INNER JOIN users u ON n.user_id = u.user_id
                  WHERE n.nurse_id IN (?, ?)";
    $stmt = $conn->prepare($nurse_sql);
    $stmt->bind_param('ii', $outgoing_nurse, $incoming_nurse);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $nurses = [];
    while ($row = $result->fetch_assoc()) {
        $nurses[$row['nurse_id']] = $row['nurse_name'];
    }
    
    if (count($nurses) < 2) {
        throw new Exception('Invalid nurse selection');
    }
    
    // Log the handover in activity log
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                     new_values, ip_address, user_agent)
                     VALUES (?, 'SHIFT_HANDOVER', 'NURSING', ?, 'HANDOVER', ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $user_id = $_SESSION['user_id'];
    $log_data = json_encode([
        'handover_type' => $handover_type,
        'outgoing_nurse_id' => $outgoing_nurse,
        'outgoing_nurse' => $nurses[$outgoing_nurse],
        'incoming_nurse_id' => $incoming_nurse,
        'incoming_nurse' => $nurses[$incoming_nurse],
        'patient_updates' => $patient_updates,
        'pending_tasks' => $pending_tasks,
        'critical_notes' => $critical_notes,
        'handover_time' => date('Y-m-d H:i:s')
    ]);
    $ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $stmt->bind_param('iisss', $user_id, $outgoing_nurse, $log_data, $ip, $user_agent);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to log shift handover');
    }
    
    $handover_id = $stmt->insert_id;
    
    // In production, you would insert into shift_handovers table:
    /*
    $handover_sql = "INSERT INTO shift_handovers (
                        handover_type, outgoing_nurse_id, incoming_nurse_id,
                        patient_updates, pending_tasks, critical_notes,
                        handover_datetime, recorded_by
                     ) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)";
    */
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Shift handover recorded successfully',
        'handover_id' => $handover_id
    ]);
    
} catch (Exception $e) {
    if ($conn->connect_errno === 0) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>