<?php
// api/patient/messages.php
require_once __DIR__ . '/../middleware.php';
require_once __DIR__ . '/../../layouts/dbconn.php';

global $API_USER;
if (!isset($API_USER)) {
    jsonError('Unauthorized', 401);
}

// Get Patient ID
$user_id = $API_USER['sub'];
$stmt = $conn->prepare("SELECT patient_id FROM patients WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    jsonError('Patient profile not found', 404);
}

$patient = $res->fetch_assoc();
$patient_id = $patient['patient_id'];

// Ensure Table Exists (as seen in source file)
$conn->query("CREATE TABLE IF NOT EXISTS patient_messages (
    message_id INT AUTO_INCREMENT PRIMARY KEY,
    patient_id INT NOT NULL,
    subject VARCHAR(255) NOT NULL,
    message TEXT NOT NULL,
    status ENUM('SENT','READ','REPLIED') DEFAULT 'SENT',
    reply TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // List Messages
    $sql = "SELECT message_id, subject, message, status, reply, created_at FROM patient_messages WHERE patient_id = ? ORDER BY created_at DESC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $messages = [];
    while ($row = $result->fetch_assoc()) {
        $messages[] = $row;
    }

    jsonResponse($messages);

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Send Message
    $input = json_decode(file_get_contents('php://input'), true);

    if (empty($input['subject']) || empty($input['message'])) {
        jsonError('Subject and message are required', 400);
    }

    $subject = $input['subject'];
    $message = $input['message'];

    $stmt = $conn->prepare("INSERT INTO patient_messages (patient_id, subject, message) VALUES (?, ?, ?)");
    $stmt->bind_param("iss", $patient_id, $subject, $message);

    if ($stmt->execute()) {
        jsonResponse(['message' => 'Message sent successfully', 'id' => $conn->insert_id], 201);
    } else {
        jsonError('Failed to send message: ' . $conn->error, 500);
    }

} else {
    jsonError('Method not allowed', 405);
}
?>