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

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

$error = '';
$success = '';

$selectedRecipients = [];
$subject = '';
$body = '';
$sendToAll = false;
$isPinned = false;

// Fetch all users except self and system for recipient search
$stmt = $pdo->prepare("
    SELECT id, username
    FROM admin_users
    WHERE id != ?
      AND role != 'System'
    ORDER BY username ASC
");

$stmt->execute([$userId]);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selectedRecipients = $_POST['recipient_ids'] ?? [];
    $subject = trim($_POST['subject'] ?? '');
    $body = trim($_POST['body'] ?? '');

    $sendToAll = $isAdmin && isset($_POST['send_to_all']) && $_POST['send_to_all'] === '1';
    $isPinned = $isAdmin && isset($_POST['is_pinned']) && $_POST['is_pinned'] === '1';

    if (!is_array($selectedRecipients)) {
        $selectedRecipients = [];
    }

    $selectedRecipients = array_values(array_unique(array_filter($selectedRecipients, function ($id) {
        return ctype_digit((string)$id);
    })));

    $selectedRecipients = array_map('intval', $selectedRecipients);

    if ($subject === '' || $body === '') {
        $error = 'Please fill in the subject and message body.';
    }

    if (!$error) {
        try {
            if ($sendToAll) {
                $recipientStmt = $pdo->prepare("
                    SELECT id
                    FROM admin_users
                    WHERE id != ?
                      AND role != 'System'
                ");

                $recipientStmt->execute([$userId]);
                $recipientIds = $recipientStmt->fetchAll(PDO::FETCH_COLUMN);
            } else {
                $recipientIds = $selectedRecipients;
            }

            $recipientIds = array_values(array_unique(array_map('intval', $recipientIds)));

            if (empty($recipientIds)) {
                $error = 'Please select at least one recipient.';
            }

            if (!$isAdmin && count($recipientIds) > 3) {
                $error = 'You can only send a message to up to 3 people at a time.';
            }

            if (!$error) {
                $placeholders = implode(',', array_fill(0, count($recipientIds), '?'));

                $existsStmt = $pdo->prepare("
                    SELECT id
                    FROM admin_users
                    WHERE id IN ($placeholders)
                      AND role != 'System'
                ");

                $existsStmt->execute($recipientIds);
                $validRecipientIds = $existsStmt->fetchAll(PDO::FETCH_COLUMN);

                $validRecipientIds = array_values(array_unique(array_map('intval', $validRecipientIds)));

                if (count($validRecipientIds) !== count($recipientIds)) {
                    $error = 'One or more selected recipients are invalid.';
                }
            }

            if (!$error) {
                $messageStmt = $pdo->prepare("
                    INSERT INTO messages
                    (
                        sender_id,
                        recipient_id,
                        subject,
                        body,
                        parent_message_id,
                        sent_at,
                        is_read,
                        is_pinned
                    )
                    VALUES (?, ?, ?, ?, NULL, NOW(), 0, ?)
                ");

                foreach ($recipientIds as $recipientId) {
                    $messageStmt->execute([
                        $userId,
                        (int)$recipientId,
                        $subject,
                        $body,
                        $isPinned ? 1 : 0
                    ]);
                }

                $success = count($recipientIds) === 1
                    ? 'Message sent successfully!'
                    : 'Messages sent successfully!';

                $selectedRecipients = [];
                $subject = '';
                $body = '';
                $sendToAll = false;
                $isPinned = false;
            }

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

$pageTitle = 'Create New Message';
?>

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

    <div class="message-compose-header d-flex justify-content-between align-items-start gap-3 mb-4">
        <div>
            <h1 class="mb-1">
                <?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?>
            </h1>

            <p class="text-muted mb-0">
                Send Newsdesk updates, direct messages and admin notices.
            </p>
        </div>

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

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

    <form method="post" id="messageForm" novalidate>

        <div class="compose-grid">

            <div class="compose-main-card">

                <div class="compose-section">
                    <div class="compose-section-heading">
                        <h2>Message details</h2>
                        <p>Choose recipients, add a subject and write your message.</p>
                    </div>

<div class="mb-3 recipient-field-wrap">
    <label for="recipientSearch" class="form-label">
        To
    </label>

    <div class="recipient-composer" id="recipientComposer">
        <div class="recipient-pill-list" id="recipientPillList"></div>

        <input
            type="text"
            id="recipientSearch"
            class="recipient-search-input"
            placeholder="Start typing a name..."
            autocomplete="off"
        >
    </div>

    <div class="recipient-suggestions" id="recipientSuggestions"></div>

    <div class="form-text" id="recipientHelpText">
        <?php if ($isAdmin): ?>
            Search and add one or more recipients, or use “Send to all users”.
        <?php else: ?>
            Search and add up to 3 recipients.
        <?php endif; ?>
    </div>

    <div id="recipientHiddenFields"></div>
</div>

                    <div class="mb-3">
                        <label for="subject" class="form-label">
                            Subject
                        </label>

                        <input
                            type="text"
                            id="subject"
                            name="subject"
                            class="form-control"
                            value="<?= htmlspecialchars($subject, ENT_QUOTES, 'UTF-8') ?>"
                            required
                        >
                    </div>

                    <div class="mb-0">
                        <label for="body" class="form-label">
                            Message Body
                        </label>

                        <textarea
                            id="body"
                            name="body"
                            class="form-control"
                            rows="10"
                        ><?= htmlspecialchars($body, ENT_QUOTES, 'UTF-8') ?></textarea>
                    </div>
                </div>

            </div>

            <aside class="compose-side-card">

                <?php if ($isAdmin): ?>
                    <div class="compose-admin-box mb-3">
                        <div class="compose-section-heading mb-3">
                            <h2>Admin options</h2>
                            <p>Send wider notices or pin important messages.</p>
                        </div>

                        <div class="form-check compose-check mb-3">
                            <input
                                class="form-check-input"
                                type="checkbox"
                                name="send_to_all"
                                id="send_to_all"
                                value="1"
                                <?= $sendToAll ? 'checked' : '' ?>
                            >

                            <label class="form-check-label" for="send_to_all">
                                <strong>Send to all users</strong>
                                <span>
                                    Sends one message to every Newsdesk user except yourself and the system account.
                                </span>
                            </label>
                        </div>

                        <div class="form-check compose-check">
                            <input
                                class="form-check-input"
                                type="checkbox"
                                name="is_pinned"
                                id="is_pinned"
                                value="1"
                                <?= $isPinned ? 'checked' : '' ?>
                            >

                            <label class="form-check-label" for="is_pinned">
                                <strong>Pin to inbox</strong>
                                <span>
                                    Keeps this message above normal inbox messages for recipients.
                                </span>
                            </label>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="compose-send-summary">
                </div>

                <div class="compose-actions">
                    <button type="submit" class="btn btn-dark">
                        Send Message
                    </button>

                    <a href="/admin/messages" class="btn btn-outline-secondary">
                        Cancel
                    </a>
                </div>

            </aside>

        </div>

    </form>

</div>

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

<script>
if (typeof tinymce !== 'undefined') {
    tinymce.init({
        selector: '#body',
        height: 420,
        menubar: false,
        plugins: 'lists link',
        toolbar: 'undo redo | bold italic | bullist numlist | link',
        branding: false
    });
}

const availableRecipients = <?= json_encode(array_map(function ($user) {
    return [
        'id' => (int)$user['id'],
        'username' => $user['username'],
    ];
}, $users), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;

document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('messageForm');
    const recipientComposer = document.getElementById('recipientComposer');
    const recipientSearch = document.getElementById('recipientSearch');
    const recipientSuggestions = document.getElementById('recipientSuggestions');
    const recipientPillList = document.getElementById('recipientPillList');
    const recipientHiddenFields = document.getElementById('recipientHiddenFields');
    const recipientHelpText = document.getElementById('recipientHelpText');
    const sendToAllCheckbox = document.getElementById('send_to_all');
    const isAdmin = <?= $isAdmin ? 'true' : 'false' ?>;

    let selectedRecipients = <?= json_encode(array_values(array_map('intval', $selectedRecipients))) ?>;

    function renderRecipients() {
        recipientPillList.innerHTML = '';
        recipientHiddenFields.innerHTML = '';

        selectedRecipients.forEach(function (recipientId) {
            const user = availableRecipients.find(function (item) {
                return item.id === recipientId;
            });

            if (!user) {
                return;
            }

            const pill = document.createElement('span');
            pill.className = 'recipient-pill';

            const name = document.createElement('span');
            name.textContent = user.username;

            const remove = document.createElement('button');
            remove.type = 'button';
            remove.innerHTML = '&times;';
            remove.setAttribute('aria-label', 'Remove ' + user.username);

            remove.addEventListener('click', function () {
                selectedRecipients = selectedRecipients.filter(function (id) {
                    return id !== recipientId;
                });

                renderRecipients();
                renderSuggestions();
            });

            pill.appendChild(name);
            pill.appendChild(remove);
            recipientPillList.appendChild(pill);

            const hidden = document.createElement('input');
            hidden.type = 'hidden';
            hidden.name = 'recipient_ids[]';
            hidden.value = recipientId;

            recipientHiddenFields.appendChild(hidden);
        });

        if (!isAdmin && selectedRecipients.length >= 3) {
            recipientHelpText.classList.add('recipient-limit-warning');
            recipientHelpText.textContent = 'Recipient limit reached. You can message up to 3 people at once.';
        } else {
            recipientHelpText.classList.remove('recipient-limit-warning');
            recipientHelpText.textContent = isAdmin
                ? 'Search and add one or more recipients, or use “Send to all users”.'
                : 'Search and add up to 3 recipients.';
        }
    }

    function renderSuggestions() {
        const query = recipientSearch.value.trim().toLowerCase();

        recipientSuggestions.innerHTML = '';

        if (!query || recipientSearch.disabled) {
            recipientSuggestions.classList.remove('is-visible');
            return;
        }

        const matches = availableRecipients
            .filter(function (user) {
                return !selectedRecipients.includes(user.id);
            })
            .filter(function (user) {
                return user.username.toLowerCase().includes(query);
            })
            .slice(0, 8);

        if (matches.length === 0) {
            const empty = document.createElement('div');
            empty.className = 'recipient-suggestion';
            empty.innerHTML = '<span class="recipient-suggestion-meta">No matching users found</span>';

            recipientSuggestions.appendChild(empty);
            recipientSuggestions.classList.add('is-visible');
            return;
        }

        matches.forEach(function (user) {
            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'recipient-suggestion';

            const name = document.createElement('span');
            name.className = 'recipient-suggestion-name';
            name.textContent = user.username;

            const meta = document.createElement('span');
            meta.className = 'recipient-suggestion-meta';
            meta.textContent = 'Add recipient';

            button.appendChild(name);
            button.appendChild(meta);

            button.addEventListener('mousedown', function (event) {
                event.preventDefault();
                addRecipient(user.id);
            });

            recipientSuggestions.appendChild(button);
        });

        recipientSuggestions.classList.add('is-visible');
    }

    function addRecipient(userId) {
        if (!isAdmin && selectedRecipients.length >= 3) {
            alert('You can only send a message to up to 3 people at a time.');
            return;
        }

        if (!selectedRecipients.includes(userId)) {
            selectedRecipients.push(userId);
        }

        recipientSearch.value = '';
        recipientSuggestions.classList.remove('is-visible');
        renderRecipients();
    }

    function updateRecipientState() {
        const sendToAll = sendToAllCheckbox && sendToAllCheckbox.checked;

        if (sendToAll) {
            selectedRecipients = [];
            recipientSearch.value = '';
            recipientSearch.disabled = true;
            recipientComposer.classList.add('is-disabled');
            recipientSuggestions.classList.remove('is-visible');
        } else {
            recipientSearch.disabled = false;
            recipientComposer.classList.remove('is-disabled');
        }

        renderRecipients();
    }

    recipientComposer.addEventListener('click', function () {
        if (!recipientSearch.disabled) {
            recipientSearch.focus();
        }
    });

    recipientSearch.addEventListener('input', renderSuggestions);

    recipientSearch.addEventListener('keydown', function (event) {
        if (event.key === 'Enter') {
            const firstButton = recipientSuggestions.querySelector('button.recipient-suggestion');

            if (firstButton) {
                event.preventDefault();
                firstButton.dispatchEvent(new MouseEvent('mousedown'));
            }
        }

        if (event.key === 'Backspace' && recipientSearch.value === '' && selectedRecipients.length > 0) {
            selectedRecipients.pop();
            renderRecipients();
        }
    });

    document.addEventListener('click', function (event) {
        if (
            !recipientComposer.contains(event.target) &&
            !recipientSuggestions.contains(event.target)
        ) {
            recipientSuggestions.classList.remove('is-visible');
        }
    });

    if (sendToAllCheckbox) {
        sendToAllCheckbox.addEventListener('change', updateRecipientState);
    }

    updateRecipientState();

    form.addEventListener('submit', function (event) {
        const subject = document.getElementById('subject').value.trim();
        const editor = typeof tinymce !== 'undefined' ? tinymce.get('body') : null;
        const bodyText = editor
            ? editor.getContent({ format: 'text' }).trim()
            : document.getElementById('body').value.trim();

        const sendToAll = sendToAllCheckbox && sendToAllCheckbox.checked;

        if (!sendToAll && selectedRecipients.length === 0) {
            alert('Please select at least one recipient.');
            event.preventDefault();
            return;
        }

        if (!isAdmin && selectedRecipients.length > 3) {
            alert('You can only send a message to up to 3 people at a time.');
            event.preventDefault();
            return;
        }

        if (!subject) {
            alert('Please enter a subject.');
            event.preventDefault();
            return;
        }

        if (!bodyText) {
            alert('Please enter a message.');
            event.preventDefault();
        }
    });
});
</script>

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