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

$patient_id = $_SESSION['patient_id'];

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_message'])) {
    $doctor_id = (int)$_POST['doctor_id'];
    $message = $conn->real_escape_string($_POST['message']);
    
    $stmt = $conn->prepare("INSERT INTO patient_doctor_messages (patient_id, doctor_id, message, sender) VALUES (?, ?, ?, 'patient')");
    $stmt->bind_param("sis", $patient_id, $doctor_id, $message);
    
    if ($stmt->execute()) {
        $_SESSION['success'] = "Message sent to doctor successfully!";
        
        // Send notification to doctor
        $conn->query("INSERT INTO doctor_notifications (doctor_id, title, message, type) 
                      VALUES ($doctor_id, 'New Message from Patient', 'You have a new message from a patient. Please check your messages.', 'info')");
    } else {
        $_SESSION['error'] = "Failed to send message. Please try again.";
    }
    $stmt->close();
}

header("Location: dashboard.php");
exit();
?>