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

$userId = (int)($_SESSION['admin_user_id'] ?? 0);
$userRole = $_SESSION['admin_role'] ?? '';

$messageId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($messageId <= 0) {
    die('Invalid message ID.');
}

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

// ----------------------
// DELETE MESSAGE
// ----------------------
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) &&
    $_POST['action'] === 'delete_message'
) {
    try {
        $deleteStmt = $pdo->prepare("
            DELETE FROM messages
            WHERE id = ?
              AND (recipient_id = ? OR sender_id = ?)
            LIMIT 1
        ");

        $deleteStmt->execute([
            $messageId,
            $userId,
            $userId
        ]);

        header('Location: /admin/messages?bulk=deleted');
        exit;

    } catch (Exception $e) {
        $errorMessage = 'Could not delete this message.';
    }
}

// ----------------------
// PIN / UNPIN MESSAGE - ADMIN ONLY
// ----------------------
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) &&
    in_array($_POST['action'], ['pin_message', 'unpin_message'], true)
) {
    if ($userRole !== 'Admin') {
        $errorMessage = 'You do not have permission to pin messages.';
    } else {
        try {
            $newPinnedStatus = $_POST['action'] === 'pin_message' ? 1 : 0;

            $pinStmt = $pdo->prepare("
                UPDATE messages
                SET is_pinned = ?
                WHERE id = ?
            ");

            $pinStmt->execute([
                $newPinnedStatus,
                $messageId
            ]);

            $successMessage = $newPinnedStatus ? 'Message pinned.' : 'Message unpinned.';

        } catch (Exception $e) {
            $errorMessage = 'Could not update pinned status.';
        }
    }
}

// ----------------------
// HANDLE REPLY FORM SUBMISSION
// ----------------------
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) &&
    $_POST['action'] === 'send_reply'
) {
    $parentId = (int)($_POST['parent_message_id'] ?? 0);
    $recipientId = (int)($_POST['recipient_id'] ?? 0);
    $content = trim($_POST['content'] ?? '');

    if ($content === '') {
        $errorMessage = 'Reply content cannot be empty.';
    } else {
        try {
            $origStmt = $pdo->prepare("
                SELECT subject
                FROM messages
                WHERE id = ?
                  AND (recipient_id = ? OR sender_id = ?)
                LIMIT 1
            ");

            $origStmt->execute([
                $parentId,
                $userId,
                $userId
            ]);

            $origMsg = $origStmt->fetch(PDO::FETCH_ASSOC);

            if (!$origMsg) {
                $errorMessage = 'Original message not found.';
            } else {
                $replySubject = str_starts_with($origMsg['subject'], 'Re:')
                    ? $origMsg['subject']
                    : 'Re: ' . $origMsg['subject'];

                $stmt = $pdo->prepare("
                    INSERT INTO messages
                    (
                        sender_id,
                        recipient_id,
                        subject,
                        body,
                        parent_message_id,
                        sent_at,
                        is_read,
                        is_pinned
                    )
                    VALUES (?, ?, ?, ?, ?, NOW(), 0, 0)
                ");

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

                $successMessage = 'Message sent successfully!';
                $_POST = [];
            }

        } catch (Exception $e) {
            $errorMessage = 'Error sending message.';
        }
    }
}

// ----------------------
// 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 = ?)
    LIMIT 1
");

$stmt->execute([
    $messageId,
    $userId,
    $userId
]);

$message = $stmt->fetch(PDO::FETCH_ASSOC);

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

// ----------------------
// MARK AS READ
// ----------------------
if ((int)$message['recipient_id'] === $userId && !(int)$message['is_read']) {
    $update = $pdo->prepare("
        UPDATE messages
        SET is_read = 1
        WHERE id = ?
          AND recipient_id = ?
    ");

    $update->execute([
        $messageId,
        $userId
    ]);

    $message['is_read'] = 1;
}

$isFromCurrentUser = (int)$message['sender_id'] === $userId;
$isFromSystem = strtolower($message['sender_name']) === 'system';

$otherPerson = $isFromCurrentUser ? $message['recipient_name'] : $message['sender_name'];
$messageDirection = $isFromCurrentUser ? 'Sent message' : 'Received message';
?>

<div class="message-view-page">

    <div class="message-view-header">
        <div>
            <a href="/admin/messages" class="message-back-link">
                ← Back to messages
            </a>

            <div class="message-title-row">
                <h1>
                    <?= htmlspecialchars($message['subject'], ENT_QUOTES, 'UTF-8') ?>
                </h1>

                <div class="message-badges">
                    <?php if (!empty($message['is_pinned'])): ?>
                        <span class="message-badge message-badge-pinned">
                            Pinned
                        </span>
                    <?php endif; ?>

                    <span class="message-badge <?= $message['is_read'] ? 'message-badge-read' : 'message-badge-unread' ?>">
                        <?= $message['is_read'] ? 'Read' : 'Unread' ?>
                    </span>
                </div>
            </div>

            <p class="message-subtitle">
                <?= htmlspecialchars($messageDirection, ENT_QUOTES, 'UTF-8') ?>
                <?= $isFromCurrentUser ? 'to' : 'from' ?>
                <strong><?= htmlspecialchars($otherPerson, ENT_QUOTES, 'UTF-8') ?></strong>
            </p>
        </div>
    </div>

    <?php if ($successMessage): ?>
        <div class="alert alert-success">
            <?= htmlspecialchars($successMessage, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>

    <?php if ($errorMessage): ?>
        <div class="alert alert-danger">
            <?= htmlspecialchars($errorMessage, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>

    <div class="message-view-grid">

        <main class="message-main-panel">

            <article class="message-card-full <?= !empty($message['is_pinned']) ? 'message-card-full-pinned' : '' ?>">

                <div class="message-card-topline">
                    <div class="message-avatar">
                        <?= htmlspecialchars(strtoupper(substr($message['sender_name'], 0, 1)), ENT_QUOTES, 'UTF-8') ?>
                    </div>

                    <div class="message-meta-main">
                        <div class="message-meta-line">
                            <strong>From</strong>
                            <span><?= htmlspecialchars($message['sender_name'], ENT_QUOTES, 'UTF-8') ?></span>
                        </div>

                        <div class="message-meta-line">
                            <strong>To</strong>
                            <span><?= htmlspecialchars($message['recipient_name'], ENT_QUOTES, 'UTF-8') ?></span>
                        </div>
                    </div>

                    <div class="message-date-pill">
                        <?= htmlspecialchars(date('d M Y, H:i', strtotime($message['sent_at'])), ENT_QUOTES, 'UTF-8') ?>
                    </div>
                </div>

                <div class="message-body-content">
                    <?= $message['body'] ?>
                </div>

            </article>

<?php if (!$isFromSystem): ?>

    <section class="reply-panel">
        <div class="reply-panel-heading">
            <div>
                <h2>Reply</h2>
                <p>
                    Your reply will be sent to
                    <strong><?= htmlspecialchars($message['sender_name'], ENT_QUOTES, 'UTF-8') ?></strong>.
                </p>
            </div>
        </div>

        <form method="post" action="" id="replyForm">
            <input type="hidden" name="action" value="send_reply">
            <input type="hidden" name="parent_message_id" value="<?= (int)$messageId ?>">
            <input type="hidden" name="recipient_id" value="<?= (int)$message['sender_id'] ?>">

            <textarea id="replyContent" name="content"><?= htmlspecialchars($_POST['content'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>

            <button type="submit" class="btn btn-dark mt-3">
                Send Reply
            </button>
        </form>
    </section>

<?php else: ?>

    <section class="reply-panel reply-panel-disabled">
        <div class="reply-panel-heading mb-0">
            <h2>System notice</h2>
            <p class="mb-0">
                This message was sent by the system, so replies are not available.
            </p>
        </div>
    </section>

<?php endif; ?>

        </main>

        <aside class="message-side-panel">

            <div class="message-action-card">
                <h2>Actions</h2>

                <div class="message-action-list">

                    <?php if ($userRole === 'Admin'): ?>
                        <?php if (!empty($message['is_pinned'])): ?>
                            <form method="post">
                                <input type="hidden" name="action" value="unpin_message">

                                <button type="submit" class="btn btn-outline-warning w-100">
                                    Unpin message
                                </button>
                            </form>
                        <?php else: ?>
                            <form method="post">
                                <input type="hidden" name="action" value="pin_message">

                                <button type="submit" class="btn btn-warning w-100">
                                    Pin message
                                </button>
                            </form>
                        <?php endif; ?>
                    <?php endif; ?>

                    <form
                        method="post"
                        onsubmit="return confirm('Delete this message? This cannot be undone.');"
                    >
                        <input type="hidden" name="action" value="delete_message">

                        <button type="submit" class="btn btn-outline-danger w-100">
                            Delete message
                        </button>
                    </form>

                    <a href="/admin/new-message.php" class="btn btn-outline-secondary w-100">
                        New message
                    </a>

                    <a href="/admin/messages" class="btn btn-outline-secondary w-100">
                        Back to inbox
                    </a>

                </div>
            </div>

            <div class="message-details-card">
                <h2>Message details</h2>

                <dl>
                    <div>
                        <dt>Status</dt>
                        <dd><?= $message['is_read'] ? 'Read' : 'Unread' ?></dd>
                    </div>

                    <div>
                        <dt>Sent</dt>
                        <dd><?= htmlspecialchars(date('d M Y, H:i', strtotime($message['sent_at'])), ENT_QUOTES, 'UTF-8') ?></dd>
                    </div>

                    <div>
                        <dt>From</dt>
                        <dd><?= htmlspecialchars($message['sender_name'], ENT_QUOTES, 'UTF-8') ?></dd>
                    </div>

                    <div>
                        <dt>To</dt>
                        <dd><?= htmlspecialchars($message['recipient_name'], ENT_QUOTES, 'UTF-8') ?></dd>
                    </div>

                    <?php if (!empty($message['is_pinned'])): ?>
                        <div>
                            <dt>Pinned</dt>
                            <dd>Yes</dd>
                        </div>
                    <?php endif; ?>
                </dl>
            </div>

        </aside>

    </div>

</div>

<script src="https://cdn.tiny.cloud/1/w4vz3wunp3pewnc7bavv3u16ollglu4nimw1v7tfm35g302r/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>

<script>
if (document.getElementById('replyContent')) {
    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
    });
}

const replyForm = document.getElementById('replyForm');

if (replyForm) {
    replyForm.addEventListener('submit', function(e) {
        const editor = tinymce.get('replyContent');

        if (!editor) {
            return;
        }

        const contentText = editor.getContent({ format: 'text' }).trim();

        if (!contentText) {
            alert('Reply content is required.');
            editor.focus();
            e.preventDefault();
        }
    });
}
</script>

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