<?php
session_start();
if (!isset($_SESSION['staff_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';

$staff_id = $_SESSION['staff_id'];
$staff_name = $_SESSION['staff_name'];

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_message'])) {
    $message = $conn->real_escape_string($_POST['message']);
    $chat_type = $_POST['chat_type'];
    
    if ($chat_type == 'doctor' && isset($_POST['doctor_id'])) {
        $doctor_id = (int)$_POST['doctor_id'];
        
        $stmt = $conn->prepare("INSERT INTO staff_doctor_chat (staff_id, doctor_id, message, sender) VALUES (?, ?, ?, 'staff')");
        $stmt->bind_param("iis", $staff_id, $doctor_id, $message);
        $stmt->execute();
        
        // Notify doctor (create notification)
        $conn->query("INSERT INTO doctor_notifications (doctor_id, title, message, type) 
                      VALUES ($doctor_id, 'New Message from Staff', 'You have a new message from staff: $staff_name', 'info')");
        
        header("Location: chat.php?doctor_id=$doctor_id");
        
    } elseif ($chat_type == 'patient' && isset($_POST['patient_id'])) {
        $patient_id = $_POST['patient_id'];
        
        $stmt = $conn->prepare("INSERT INTO staff_patient_chat (staff_id, patient_id, message, sender) VALUES (?, ?, ?, 'staff')");
        $stmt->bind_param("sis", $staff_id, $patient_id, $message);
        $stmt->execute();
        
        // Notify patient
        $conn->query("INSERT INTO patient_notifications (patient_id, title, message, type) 
                      VALUES ('$patient_id', 'New Message from Hospital Staff', 'You have a new message from our staff. Please log in to reply.', 'info')");
        
        header("Location: chat.php?patient_id=$patient_id");
    }
}
exit();
?>