<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/layout.php';  // includes auth + header + sidebar + topbar

$adminId = $_SESSION['admin_user_id'];

// ----------------------
// FEEDBACK MESSAGES
// ----------------------
$successMessage = '';
$errorMessage = '';

if (isset($_GET['bulk'])) {
    if ($_GET['bulk'] === 'read') {
        $successMessage = 'Selected messages marked as read.';
    } elseif ($_GET['bulk'] === 'deleted') {
        $successMessage = 'Selected messages deleted.';
    } elseif ($_GET['bulk'] === 'none') {
        $errorMessage = 'Please select at least one message.';
    } elseif ($_GET['bulk'] === 'invalid') {
        $errorMessage = 'Invalid bulk action.';
    }
}

// Fetch inbox messages
$stmt = $pdo->prepare("
    SELECT m.*, u.username AS sender_name
    FROM messages m
    JOIN admin_users u ON m.sender_id = u.id
    WHERE m.recipient_id = ?
    ORDER BY m.is_pinned DESC, m.sent_at DESC
");
$stmt->execute([$adminId]);
$inboxMessages = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch outbox messages
$stmt = $pdo->prepare("
    SELECT m.*, u.username AS recipient_name
    FROM messages m
    JOIN admin_users u ON m.recipient_id = u.id
    WHERE m.sender_id = ?
    ORDER BY m.sent_at DESC
");
$stmt->execute([$adminId]);
$outboxMessages = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="messages-page">

    <div class="messages-header d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="mb-1">Messages</h1>
            <p class="text-muted mb-0">
                View inbox alerts, replies and Newsdesk updates.
            </p>
        </div>

        <a href="new-message.php" class="btn btn-dark">
            New Message
        </a>
    </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; ?>

    <ul class="nav nav-pills messages-tabs mb-3" id="messagesTab" role="tablist">
        <li class="nav-item" role="presentation">
            <button
                class="nav-link active"
                id="inbox-tab"
                data-bs-toggle="tab"
                data-bs-target="#inbox"
                type="button"
                role="tab"
                aria-controls="inbox"
                aria-selected="true"
            >
                Inbox
                <?php if (!empty($inboxMessages)): ?>
                    <span class="badge rounded-pill ms-1">
                        <?= count($inboxMessages) ?>
                    </span>
                <?php endif; ?>
            </button>
        </li>

        <li class="nav-item" role="presentation">
            <button
                class="nav-link"
                id="outbox-tab"
                data-bs-toggle="tab"
                data-bs-target="#outbox"
                type="button"
                role="tab"
                aria-controls="outbox"
                aria-selected="false"
            >
                Outbox
                <?php if (!empty($outboxMessages)): ?>
                    <span class="badge rounded-pill ms-1">
                        <?= count($outboxMessages) ?>
                    </span>
                <?php endif; ?>
            </button>
        </li>
    </ul>

    <div class="tab-content" id="messagesTabContent">

        <!-- Inbox -->
        <div class="tab-pane fade show active" id="inbox" role="tabpanel" aria-labelledby="inbox-tab">

            <form method="post" action="/admin/bulk-message-action.php">
                <input type="hidden" name="box" value="inbox">

                <div class="messages-toolbar d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
                    <div class="d-flex align-items-center gap-2">
                        <input
                            type="checkbox"
                            class="form-check-input"
                            data-select-all="inbox"
                            aria-label="Select all inbox messages"
                        >

                        <span class="text-muted small">
                            Select all
                        </span>
                    </div>

                    <div class="d-flex gap-2">
                        <select name="bulk_action" class="form-select form-select-sm">
                            <option value="">Bulk actions</option>
                            <option value="mark_read">Mark as read</option>
                            <option value="delete">Delete</option>
                        </select>

                        <button type="submit" class="btn btn-sm btn-dark">
                            Apply
                        </button>
                    </div>
                </div>

                <div class="messages-list">
                    <?php if (empty($inboxMessages)): ?>

                        <div class="messages-empty">
                            <h5>No messages yet</h5>
                            <p class="mb-0">Your inbox is clear.</p>
                        </div>

                    <?php else: ?>

                        <?php foreach ($inboxMessages as $msg): ?>
                            <div class="message-card <?= !$msg['is_read'] ? 'message-card-unread' : '' ?> <?= !empty($msg['is_pinned']) ? 'message-card-pinned' : '' ?>">

                                <div class="message-card-check">
                                    <input
                                        type="checkbox"
                                        class="form-check-input inbox-message-checkbox"
                                        name="message_ids[]"
                                        value="<?= (int)$msg['id'] ?>"
                                        aria-label="Select message <?= (int)$msg['id'] ?>"
                                    >
                                </div>

                                <div
                                    class="message-card-main"
                                    onclick="window.location.href='message.php?id=<?= (int)$msg['id'] ?>'"
                                >
                                    <div class="message-card-top">
                                        <div class="message-card-sender">
                                            <?= htmlspecialchars($msg['sender_name'], ENT_QUOTES, 'UTF-8') ?>
                                        </div>

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

                                    <div class="message-card-subject">
                                        <?php if (!empty($msg['is_pinned'])): ?>
                                            <span class="message-pin">Pinned</span>
                                        <?php endif; ?>

                                        <?= htmlspecialchars($msg['subject'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>

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

                            </div>
                        <?php endforeach; ?>

                    <?php endif; ?>
                </div>
            </form>

        </div>

        <!-- Outbox -->
        <div class="tab-pane fade" id="outbox" role="tabpanel" aria-labelledby="outbox-tab">

            <form method="post" action="/admin/bulk-message-action.php">
                <input type="hidden" name="box" value="outbox">

                <div class="messages-toolbar d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
                    <div class="d-flex align-items-center gap-2">
                        <input
                            type="checkbox"
                            class="form-check-input"
                            data-select-all="outbox"
                            aria-label="Select all outbox messages"
                        >

                        <span class="text-muted small">
                            Select all
                        </span>
                    </div>

                    <div class="d-flex gap-2">
                        <select name="bulk_action" class="form-select form-select-sm">
                            <option value="">Bulk actions</option>
                            <option value="delete">Delete</option>
                        </select>

                        <button type="submit" class="btn btn-sm btn-dark">
                            Apply
                        </button>
                    </div>
                </div>

                <div class="messages-list">
                    <?php if (empty($outboxMessages)): ?>

                        <div class="messages-empty">
                            <h5>No sent messages</h5>
                            <p class="mb-0">Messages you send will appear here.</p>
                        </div>

                    <?php else: ?>

                        <?php foreach ($outboxMessages as $msg): ?>
                            <div class="message-card <?= !empty($msg['is_pinned']) ? 'message-card-pinned' : '' ?>">

                                <div class="message-card-check">
                                    <input
                                        type="checkbox"
                                        class="form-check-input outbox-message-checkbox"
                                        name="message_ids[]"
                                        value="<?= (int)$msg['id'] ?>"
                                        aria-label="Select message <?= (int)$msg['id'] ?>"
                                    >
                                </div>

                                <div
                                    class="message-card-main"
                                    onclick="window.location.href='message.php?id=<?= (int)$msg['id'] ?>'"
                                >
                                    <div class="message-card-top">
                                        <div class="message-card-sender">
                                            To: <?= htmlspecialchars($msg['recipient_name'], ENT_QUOTES, 'UTF-8') ?>
                                        </div>

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

                                    <div class="message-card-subject">
                                        <?php if (!empty($msg['is_pinned'])): ?>
                                            <span class="message-pin">Pinned</span>
                                        <?php endif; ?>

                                        <?= htmlspecialchars($msg['subject'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>

                                    <div class="message-card-meta">
                                        <span class="<?= $msg['is_read'] ? 'message-status-read' : 'message-status-unread' ?>">
                                            <?= $msg['is_read'] ? 'Read by recipient' : 'Unread by recipient' ?>
                                        </span>
                                    </div>
                                </div>

                            </div>
                        <?php endforeach; ?>

                    <?php endif; ?>
                </div>
            </form>

        </div>

    </div>

</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const selectAllBoxes = document.querySelectorAll('[data-select-all]');

    selectAllBoxes.forEach(function (selectAllBox) {
        selectAllBox.addEventListener('change', function () {
            const target = selectAllBox.getAttribute('data-select-all');
            const checkboxes = document.querySelectorAll('.' + target + '-message-checkbox');

            checkboxes.forEach(function (checkbox) {
                checkbox.checked = selectAllBox.checked;
            });
        });
    });
});
</script>