<?php
session_start();
include('../../../includes/config.php');
header('Content-Type: text/html; charset=utf-8');

if (!isset($_SESSION['user_id']) || !isset($_GET['recipient_id'])) {
    http_response_code(400);
    echo "Invalid request";
    exit;
}

$recipient_id = intval($_GET['recipient_id']);

// Fetch recipient user info
$stmt = $conn->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
$stmt->bind_param("i", $recipient_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    http_response_code(404);
    echo "User not found";
    exit;
}

$recipient = $result->fetch_assoc();
?>

<div id="messageModal" class="modal glass" role="dialog" aria-modal="true" aria-labelledby="modalTitle" aria-describedby="modalDesc" style="display:block;">
    <button class="close" aria-label="Close message modal" onclick="document.getElementById('messageModal').remove();">&times;</button>
    <h3 id="modalTitle">Message <?= htmlspecialchars($recipient['first_name'] . ' ' . $recipient['last_name']) ?></h3>
    <form id="messageForm">
        <input type="hidden" name="receiver_id" id="receiverId" value="<?= $recipient_id ?>" />
        <label for="subject">Subject:</label>
        <input type="text" id="subject" name="subject" required maxlength="100" />
        <label for="messageBody">Message:</label>
        <textarea id="messageBody" name="message" required maxlength="1000"></textarea>
        <button type="submit" class="btn btn-primary">Send Message</button>
    </form>
    <div id="messageStatus" role="alert" class="message-status" style="margin-top: 12px;"></div>
</div>

<script>
document.getElementById("messageForm").addEventListener("submit", function (e) {
    e.preventDefault();
    const status = document.getElementById("messageStatus");
    status.textContent = "Sending...";

    const formData = new FormData(this);

    fetch("../../processes/send_message.php", {
        method: "POST",
        body: formData,
        credentials: "same-origin"
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            status.style.color = "green";
            status.textContent = "Message sent successfully!";
            setTimeout(() => {
                const modal = document.getElementById("messageModal");
                if (modal) modal.remove();
            }, 1500);
        } else {
            status.style.color = "red";
            status.textContent = data.message || "Failed to send message.";
        }
    })
    .catch(err => {
        status.style.color = "red";
        status.textContent = "Error sending message.";
    });
});
</script>
