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

$doctor_id = $_SESSION['doctor_id'];
$doctor_name = $_SESSION['doctor_name'];

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['reply_message'])) {
    $patient_id = $_POST['patient_id'];
    $message = $conn->real_escape_string($_POST['message']);
    
    $stmt = $conn->prepare("INSERT INTO patient_doctor_messages (patient_id, doctor_id, message, sender) VALUES (?, ?, ?, 'doctor')");
    $stmt->bind_param("sis", $patient_id, $doctor_id, $message);
    
    if ($stmt->execute()) {
        // Send notification to patient
        $conn->query("INSERT INTO patient_notifications (patient_id, title, message, type) 
                      VALUES ('$patient_id', 'New Message from Doctor', 'Dr. $doctor_name has replied to your message. Check your chat.', 'info')");
        $_SESSION['success'] = "Reply sent successfully!";
    } else {
        $_SESSION['error'] = "Failed to send reply.";
    }
    $stmt->close();
}

header("Location: patient_messages.php?patient_id=" . $patient_id);
exit();
?>