<?php $title = 'Compose Message'; ?>
<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-white font-weight-bold"><i class="fas fa-edit mr-2"></i>Compose Message</h1>
</div>
<div class="glass-card">
    <form method="POST" action="<?= $baseUrl ?>/messages/send" id="composeForm">
        <div class="form-group">
            <label style="color: rgba(255,255,255,0.7);">Subject</label>
            <input type="text" name="subject" class="form-control glass-input" required>
        </div>
        <div class="form-group">
            <label style="color: rgba(255,255,255,0.7);">Recipients</label>
            <div class="mb-2">
                <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="send_to_all" name="send_to_all" value="1">
                    <label class="custom-control-label" for="send_to_all" style="color: rgba(255,255,255,0.7);">Send to all members</label>
                </div>
            </div>
            <div id="recipient-chips" class="d-flex flex-wrap mb-2"></div>
            <div style="position: relative;">
                <input type="text" id="recipient-search" class="form-control glass-input" placeholder="Search by name or email..." autocomplete="off">
                <div id="search-results" style="position: absolute; top: 100%; left: 0; right: 0; z-index: 1000; background: rgba(15,12,41,0.98); border: 1px solid rgba(78,115,223,0.3); border-radius: 0 0 12px 12px; max-height: 260px; overflow-y: auto; display: none;"></div>
            </div>
            <small style="color: rgba(255,255,255,0.4);">Search for members by name or email and click to add</small>
            <div id="selected-recipients"></div>
        </div>
        <div class="form-group">
            <label style="color: rgba(255,255,255,0.7);">Priority</label>
            <select name="priority" class="form-control glass-input">
                <option value="normal">Normal</option>
                <option value="low">Low</option>
                <option value="high">High</option>
            </select>
        </div>
        <div class="form-group">
            <label style="color: rgba(255,255,255,0.7);">Message</label>
            <textarea name="body" class="form-control glass-input" rows="8" required></textarea>
        </div>
        <div class="text-right">
            <a href="<?= $baseUrl ?>/messages/inbox" class="glass-btn mr-2">Cancel</a>
            <button type="submit" class="glass-btn glass-btn-primary"><i class="fas fa-paper-plane mr-1"></i>Send</button>
        </div>
    </form>
</div>

<style>
#search-results .result-item { padding: 0.6rem 1rem; cursor: pointer; border-bottom: 1px solid rgba(255,255,255,0.05); transition: background 0.2s; }
#search-results .result-item:hover { background: rgba(78,115,223,0.2); }
#search-results .result-item:last-child { border-bottom: none; }
#search-results .result-item strong { color: #fff; }
#search-results .result-item small { color: rgba(255,255,255,0.5); }
.recipient-chip { display: inline-flex; align-items: center; background: rgba(78,115,223,0.2); border: 1px solid rgba(78,115,223,0.3); border-radius: 50px; padding: 0.3rem 0.8rem; margin: 0.25rem; font-size: 0.85rem; color: #fff; }
.recipient-chip .remove-chip { margin-left: 0.5rem; cursor: pointer; color: rgba(255,255,255,0.5); transition: color 0.2s; }
.recipient-chip .remove-chip:hover { color: #e74a3b; }
#send_to_all:checked ~ #recipient-search { opacity: 0.4; pointer-events: none; }
#send_to_all:checked ~ #recipient-chips { display: none; }
</style>

<script>
var selectedUsers = {};

function addUser(id, name, email) {
    if (selectedUsers[id]) return;
    selectedUsers[id] = { name: name, email: email };
    renderChips();
    $('#recipient-search').val('').focus();
    $('#search-results').hide();
}

function removeUser(id) {
    delete selectedUsers[id];
    renderChips();
    $('#recipient-search').focus();
}

function renderChips() {
    var chips = $('#recipient-chips');
    var hidden = $('#selected-recipients');
    chips.empty();
    hidden.empty();
    $.each(selectedUsers, function(id, u) {
        chips.append('<span class="recipient-chip">' + $('<span>').text(u.name).html() + ' <small style="color:rgba(255,255,255,0.4)">' + $('<span>').text(u.email).html() + '</small><span class="remove-chip" data-id="' + id + '"><i class="fas fa-times"></i></span></span>');
        hidden.append('<input type="hidden" name="recipients[]" value="' + id + '">');
    });
    $('.remove-chip').off('click').on('click', function() { removeUser($(this).data('id')); });
}

$(function() {
    var searchInput = $('#recipient-search');
    var results = $('#search-results');
    var timer;

    searchInput.on('input', function() {
        var q = $(this).val();
        if ($('#send_to_all').is(':checked')) { results.hide(); return; }
        clearTimeout(timer);
        if (q.length < 1) { results.hide(); return; }
        timer = setTimeout(function() {
            $.get('<?= $baseUrl ?>/messages/search-users', { q: q }, function(data) {
                if (!data.length) { results.html('<div class="result-item" style="color:rgba(255,255,255,0.4);">No members found</div>').show(); return; }
                var html = '';
                $.each(data, function(i, u) {
                    if (selectedUsers[u.id]) return;
                    html += '<div class="result-item" data-id="' + u.id + '" data-name="' + $('<span>').text(u.name).html() + '" data-email="' + u.email + '">';
                    html += '<strong>' + $('<span>').text(u.name).html() + '</strong><br><small>' + u.email + '</small>';
                    html += '</div>';
                });
                if (!html) { results.html('<div class="result-item" style="color:rgba(255,255,255,0.4);">All matching members already added</div>').show(); return; }
                results.html(html).show();
                results.find('.result-item').on('click', function() {
                    addUser($(this).data('id'), $(this).data('name'), $(this).data('email'));
                    results.hide();
                });
            }, 'json');
        }, 250);
    });

    searchInput.on('blur', function() { setTimeout(function() { results.hide(); }, 200); });
    searchInput.on('focus', function() { if ($(this).val().length > 0 && results.children().length) results.show(); });

    $('#send_to_all').on('change', function() {
        if ($(this).is(':checked')) {
            searchInput.val('').prop('disabled', true);
            selectedUsers = {};
            renderChips();
        } else {
            searchInput.prop('disabled', false).focus();
        }
    });
});
</script>
