<?php
require_once __DIR__ . '/../config.php'; 
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/layout.php';  

// Check user logged in
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header('Location: /login.php');
    exit;
}

$userId = $_SESSION['admin_user_id'];
$messageId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($messageId <= 0) {
    die('Invalid message ID.');
}

$successMessage = '';
$errorMessage = '';

// Handle reply form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['content'], $_POST['parent_message_id'], $_POST['recipient_id'])) {
    $parentId = (int)$_POST['parent_message_id'];
    $recipientId = (int)$_POST['recipient_id'];
    $content = trim($_POST['content']);

    if ($content === '') {
        $errorMessage = 'Reply content cannot be empty.';
    } else {
        try {
            // Insert reply message
            $stmt = $pdo->prepare("INSERT INTO messages (sender_id, recipient_id, subject, body, parent_message_id, sent_at, is_read) VALUES (?, ?, ?, ?, ?, NOW(), 0)");

            // For reply subject, you could prefix "Re: " or keep same as original message subject - 
            // We'll fetch original subject below to reuse here after message fetch.
            // So first just store content, and we will update subject after fetching original message.
            
            // We'll fetch original message first:
            $origStmt = $pdo->prepare("SELECT subject FROM messages WHERE id = ?");
            $origStmt->execute([$parentId]);
            $origMsg = $origStmt->fetch(PDO::FETCH_ASSOC);
            if (!$origMsg) {
                die('Original message not found.');
            }
            $replySubject = 'Re: ' . $origMsg['subject'];

            $stmt->execute([$userId, $recipientId, $replySubject, $content, $parentId]);

            $successMessage = 'Message sent successfully!';
            // Clear POST data to prevent reprocessing on refresh
            $_POST = [];
        } catch (Exception $e) {
            $errorMessage = 'Error sending message: ' . $e->getMessage();
        }
    }
}

// Fetch message for viewing
$stmt = $pdo->prepare("SELECT m.*, 
    sender.username AS sender_name, 
    recipient.username AS recipient_name 
    FROM messages m
    JOIN admin_users sender ON m.sender_id = sender.id
    JOIN admin_users recipient ON m.recipient_id = recipient.id
    WHERE m.id = ? AND (m.recipient_id = ? OR m.sender_id = ?)
");
$stmt->execute([$messageId, $userId, $userId]);
$message = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$message) {
    die('Message not found or access denied.');
}

// Mark as read if unread and current user is recipient
if ($message['recipient_id'] == $userId && !$message['is_read']) {
    $update = $pdo->prepare("UPDATE messages SET is_read = 1 WHERE id = ?");
    $update->execute([$messageId]);
    $message['is_read'] = 1;
}

$pageTitle = htmlspecialchars($message['subject']);
require_once __DIR__ . '/includes/header.php';
?>

<h1><?= htmlspecialchars($message['subject']) ?></h1>

<div class="card mb-4 <?= !$message['is_read'] && $message['recipient_id'] == $userId ? 'border-warning' : '' ?>">
    <div class="card-header">
        From: <?= htmlspecialchars($message['sender_name']) ?> <br>
        To: <?= htmlspecialchars($message['recipient_name']) ?> <br>
        Sent: <?= htmlspecialchars($message['sent_at']) ?>
    </div>
<div class="card-body">
    <p><?= $message['body'] ?></p>
</div>
</div>

<?php if ($successMessage): ?>
    <div class="alert alert-success"><?= htmlspecialchars($successMessage) ?></div>
<?php endif; ?>
<?php if ($errorMessage): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($errorMessage) ?></div>
<?php endif; ?>

<h3>Reply</h3>
<form method="post" action="">
    <input type="hidden" name="parent_message_id" value="<?= $messageId ?>">
    <input type="hidden" name="recipient_id" value="<?= $message['sender_id'] ?>">
    <textarea id="replyContent" name="content"><?= htmlspecialchars($_POST['content'] ?? '') ?></textarea>
    <button type="submit" class="btn btn-primary mt-2">Send Reply</button>
</form>

<script src="https://cdn.tiny.cloud/1/w4vz3wunp3pewnc7bavv3u16ollglu4nimw1v7tfm35g302r/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: '#replyContent',
    height: 300,
    menubar: false,
    plugins: 'lists link image table',
    toolbar: 'undo redo | bold italic | bullist numlist | link image | removeformat',
    branding: false
  });

  document.getElementById('postForm').addEventListener('submit', function(e) {
    const contentText = tinymce.get('content').getContent({ format: 'text' }).trim();
    if (!contentText) {
      alert('Content is required.');
      tinymce.get('content').focus();
      e.preventDefault();
    }
  });
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
