<?php
$activeTab = ($tab ?? 'inbox') === 'sent' ? 'sent' : 'inbox';
$baseParams = array_filter(['token' => $token]);
?>
<main class="container py-4 py-md-5">
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
        <div>
            <span class="badge text-bg-warning text-dark rounded-pill px-3 py-2 mb-2">Painel do Instrutor</span>
            <h1 class="h3 fw-bold text-cfc-dark mb-1"><i class="bi bi-chat-square-text"></i> Mensagens entre instrutores</h1>
            <p class="text-muted mb-0">Envie mensagens e acompanhe as mensagens recebidas e enviadas.</p>
        </div>
        <a class="btn btn-outline-primary rounded-pill" href="<?= e(url('professional/panel', $baseParams)) ?>"><i class="bi bi-arrow-left"></i> Voltar ao painel</a>
    </div>

    <div class="row g-4">
        <div class="col-xl-5">
            <div class="card border-0 shadow-soft rounded-4 h-100">
                <div class="card-body p-4">
                    <h2 class="h5 fw-bold mb-3"><i class="bi bi-send"></i> Mandar nova mensagem</h2>
                    <form method="post" action="<?= e(url('professional/messages/send')) ?>" class="row g-3">
                        <?= CSRF::input() ?>
                        <input type="hidden" name="token" value="<?= e($token) ?>">
                        <div class="col-12">
                            <label class="form-label">Enviar para</label>
                            <select name="recipient_id" class="form-select" required>
                                <option value="">Selecione o instrutor</option>
                                <?php foreach ($messageRecipients as $recipient): ?>
                                    <option value="<?= (int)$recipient['id'] ?>"><?= e($recipient['name']) ?> - <?= e($recipient['type']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12"><label class="form-label">Assunto</label><input name="subject" maxlength="180" class="form-control" required></div>
                        <div class="col-12"><label class="form-label">Mensagem</label><textarea name="message_body" rows="6" maxlength="10000" class="form-control" required></textarea></div>
                        <div class="col-12">
                            <label class="form-label">Senha da mensagem <span class="text-muted">(opcional)</span></label>
                            <input type="password" name="message_password" minlength="4" class="form-control" autocomplete="new-password" placeholder="Quem receber precisará desta senha">
                            <small class="text-muted">Com senha, o conteúdo só aparece depois que o destinatário informar a senha correta.</small>
                        </div>
                        <div class="col-12"><button class="btn btn-primary rounded-pill w-100"><i class="bi bi-send-check"></i> Enviar mensagem</button></div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-xl-7">
            <div class="card border-0 shadow-soft rounded-4 h-100">
                <div class="card-body p-4">
                    <ul class="nav nav-pills nav-fill gap-2 mb-4" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link <?= $activeTab === 'inbox' ? 'active' : '' ?>" href="<?= e(url('professional/messages', array_merge($baseParams, ['tab'=>'inbox']))) ?>">
                                <i class="bi bi-inbox"></i> Recebidas
                                <?php if (!empty($unreadMessages)): ?><span class="badge text-bg-danger ms-1"><?= (int)$unreadMessages ?></span><?php endif; ?>
                            </a>
                        </li>
                        <li class="nav-item"><a class="nav-link <?= $activeTab === 'sent' ? 'active' : '' ?>" href="<?= e(url('professional/messages', array_merge($baseParams, ['tab'=>'sent']))) ?>"><i class="bi bi-send"></i> Enviadas</a></li>
                    </ul>

                    <?php if ($activeTab === 'inbox'): ?>
                        <?php if (empty($inboxMessages)): ?><div class="alert alert-light border rounded-4">Nenhuma mensagem recebida.</div><?php endif; ?>
                        <div class="accordion" id="inboxAccordion">
                            <?php foreach ($inboxMessages as $message): ?>
                                <div class="accordion-item rounded-3 overflow-hidden mb-3 border">
                                    <h2 class="accordion-header">
                                        <button class="accordion-button collapsed py-3" type="button" data-bs-toggle="collapse" data-bs-target="#message-<?= (int)$message['id'] ?>">
                                            <span class="me-2"><?= !empty($message['is_locked']) ? '<i class="bi bi-lock-fill text-warning"></i>' : '<i class="bi bi-envelope-fill text-primary"></i>' ?></span>
                                            <span><strong><?= e($message['subject']) ?></strong><small class="d-block text-muted">De <?= e($message['sender_name']) ?> • <?= e(date('d/m/Y H:i', strtotime($message['created_at']))) ?></small></span>
                                        </button>
                                    </h2>
                                    <div id="message-<?= (int)$message['id'] ?>" class="accordion-collapse collapse" data-bs-parent="#inboxAccordion">
                                        <div class="accordion-body">
                                            <?php if (!empty($message['is_unlocked'])): ?>
                                                <div class="message-body mb-3"><?= nl2br(e($message['message_body'])) ?></div>
                                            <?php else: ?>
                                                <div class="alert alert-warning rounded-3"><i class="bi bi-shield-lock"></i> Esta mensagem está protegida por senha.</div>
                                                <form method="post" action="<?= e(url('professional/messages/unlock')) ?>" class="row g-2 mb-3">
                                                    <?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="message_id" value="<?= (int)$message['id'] ?>">
                                                    <div class="col-sm-8"><input type="password" name="message_password" class="form-control" placeholder="Digite a senha recebida" required></div>
                                                    <div class="col-sm-4"><button class="btn btn-warning w-100"><i class="bi bi-unlock"></i> Abrir</button></div>
                                                </form>
                                            <?php endif; ?>
                                            <form method="post" action="<?= e(url('professional/messages/delete')) ?>" onsubmit="return confirm('Apagar esta mensagem da sua caixa de recebidas?');">
                                                <?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="message_id" value="<?= (int)$message['id'] ?>"><input type="hidden" name="tab" value="inbox">
                                                <button class="btn btn-sm btn-outline-danger rounded-pill"><i class="bi bi-trash"></i> Apagar mensagem</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <?php if (empty($sentMessages)): ?><div class="alert alert-light border rounded-4">Nenhuma mensagem enviada.</div><?php endif; ?>
                        <?php foreach ($sentMessages as $message): ?>
                            <div class="border rounded-4 p-3 mb-3">
                                <div class="d-flex justify-content-between align-items-start gap-2 mb-1">
                                    <strong><?= e($message['subject']) ?></strong>
                                    <?php if (!empty($message['password_hash'])): ?><span class="badge text-bg-warning"><i class="bi bi-lock-fill"></i> Com senha</span><?php endif; ?>
                                </div>
                                <small class="d-block text-muted mb-3">Para <?= e($message['recipient_name']) ?> • <?= e(date('d/m/Y H:i', strtotime($message['created_at']))) ?> • <?= !empty($message['is_read']) ? 'Lida' : 'Ainda não lida' ?></small>
                                <div class="message-body mb-3"><?= nl2br(e($message['message_body'])) ?></div>
                                <form method="post" action="<?= e(url('professional/messages/delete')) ?>" onsubmit="return confirm('Apagar esta mensagem da sua caixa de enviadas? O destinatário continuará com a cópia dele.');">
                                    <?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="message_id" value="<?= (int)$message['id'] ?>"><input type="hidden" name="tab" value="sent">
                                    <button class="btn btn-sm btn-outline-danger rounded-pill"><i class="bi bi-trash"></i> Apagar mensagem</button>
                                </form>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</main>
