<?php $base = array_filter(['token' => $token]); ?>
<main class="container py-4 py-md-5">
    <div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-3 mb-4">
        <div><span class="badge text-bg-success rounded-pill px-3 py-2 mb-2">Agenda interna</span><h1 class="h3 fw-bold text-cfc-dark mb-1"><i class="bi bi-person-lines-fill"></i> Contatos do sistema</h1><p class="text-muted mb-0"><?= in_array($actorType, ['student','professional'], true) ? 'Os contatos internos são liberados automaticamente quando uma aula é agendada.' : 'Pesquise os contatos do sistema pelo nome.' ?></p></div>
        <a class="btn btn-outline-primary rounded-pill" href="<?= e(url('portal/messages', $base)) ?>"><i class="bi bi-arrow-left"></i> Voltar às mensagens</a>
    </div>

    <div class="card border-0 shadow-soft rounded-4 mb-4"><div class="card-body p-4">
        <form method="get" class="row g-3 align-items-end">
            <input type="hidden" name="r" value="portal/contacts"><?php if ($token !== ''): ?><input type="hidden" name="token" value="<?= e($token) ?>"><?php endif; ?>
            <div class="col-md-9"><label class="form-label">Procurar pelo nome, código ou tipo</label><input name="q" class="form-control form-control-lg" value="<?= e($search) ?>" placeholder="Ex.: João, instrutor ou 123456789"></div>
            <div class="col-md-3"><button class="btn btn-primary rounded-pill w-100 btn-lg"><i class="bi bi-search"></i> Procurar</button></div>
        </form>
    </div></div>

    <div class="card border-0 shadow-soft rounded-4 mb-4"><div class="card-body p-4">
        <div class="d-flex justify-content-between align-items-center gap-2 mb-3"><h2 class="h5 fw-bold mb-0"><i class="bi bi-person-check-fill text-success"></i> Contatos liberados</h2><span class="badge text-bg-light border"><?= count($savedContacts ?? []) ?></span></div>
        <?php if (empty($savedContacts)): ?><div class="alert alert-light border rounded-4 mb-0"><?= in_array($actorType, ['student','professional'], true) ? 'Nenhum contato liberado ainda. O contato aparecerá automaticamente após o agendamento da aula.' : 'Você ainda não salvou nenhum contato.' ?></div><?php else: ?>
            <div class="row g-3">
                <?php foreach ($savedContacts as $contact): ?>
                    <div class="col-md-6 col-xl-4"><div class="border rounded-4 p-3 h-100">
                        <strong class="d-block"><?= e(short_person_name($contact['name'])) ?></strong><small class="text-muted d-block mb-3"><?= e(internal_actor_label($contact['actor_type'])) ?> · <?= e($contact['internal_code'] ?? '---------') ?></small>
                        <div class="d-flex flex-wrap gap-2"><a class="btn btn-sm btn-primary rounded-pill" href="<?= e(url('portal/messages/direct', array_merge($base, ['contact_type' => $contact['actor_type'], 'contact_id' => (int)$contact['id']]))) ?>"><i class="bi bi-chat-dots"></i> Conversar</a><?php if (!in_array($actorType, ['student','professional'], true)): ?><form method="post" action="<?= e(url('portal/contacts/delete')) ?>" onsubmit="return confirm('Remover este contato da sua lista?');"><?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="q" value="<?= e($search) ?>"><input type="hidden" name="contact_type" value="<?= e($contact['actor_type']) ?>"><input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-pill"><i class="bi bi-star"></i> Remover</button></form><?php endif; ?></div>
                    </div></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div></div>

    <div class="card border-0 shadow-soft rounded-4"><div class="card-body p-4">
        <div class="d-flex justify-content-between align-items-center gap-2 mb-3"><h2 class="h5 fw-bold mb-0"><i class="bi bi-people"></i> Contatos disponíveis</h2><span class="badge text-bg-primary"><?= count($contacts ?? []) ?> encontrado(s)</span></div>
        <?php if (empty($contacts)): ?><div class="alert alert-warning rounded-4 mb-0">Nenhum contato encontrado com essa pesquisa.</div><?php else: ?>
            <div class="table-responsive"><table class="table align-middle">
                <thead><tr><th>Nome</th><th>Tipo</th><th>Código</th><th>Contato</th><th class="text-end">Ações</th></tr></thead>
                <tbody><?php foreach ($contacts as $contact): ?><tr>
                    <td><strong><?= e($contact['name']) ?></strong></td>
                    <td><span class="badge text-bg-light border"><?= e(internal_actor_label($contact['actor_type'])) ?></span></td>
                    <td><code><?= e($contact['internal_code'] ?? '---------') ?></code></td>
                    <td><?php if ($actorType === 'admin' && !empty($contact['whatsapp'])): ?><a target="_blank" rel="noopener" href="<?= e(whatsapp_url($contact['whatsapp'], 'Olá '.short_person_name($contact['name']).', tudo bem?')) ?>" class="text-success text-decoration-none"><i class="bi bi-whatsapp"></i> <?= e(format_whatsapp($contact['whatsapp'])) ?></a><?php else: ?><span class="badge text-bg-light border"><i class="bi bi-chat-dots"></i> Contato interno do sistema</span><?php endif; ?></td>
                    <td class="text-end"><div class="d-flex flex-wrap gap-2 justify-content-end"><a class="btn btn-sm btn-primary rounded-pill" href="<?= e(url('portal/messages/direct', array_merge($base, ['contact_type' => $contact['actor_type'], 'contact_id' => (int)$contact['id']]))) ?>"><i class="bi bi-chat-dots"></i> Mensagem</a><?php if (in_array($actorType, ['student','professional'], true)): ?><span class="badge text-bg-success align-self-center"><i class="bi bi-calendar-check"></i> Liberado por agendamento</span><?php elseif (empty($contact['is_saved'])): ?><form method="post" action="<?= e(url('portal/contacts/save')) ?>"><?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="q" value="<?= e($search) ?>"><input type="hidden" name="contact_type" value="<?= e($contact['actor_type']) ?>"><input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>"><button class="btn btn-sm btn-outline-success rounded-pill"><i class="bi bi-star"></i> Salvar</button></form><?php else: ?><span class="badge text-bg-success align-self-center"><i class="bi bi-check2"></i> Salvo</span><?php endif; ?></div></td>
                </tr><?php endforeach; ?></tbody>
            </table></div>
        <?php endif; ?>
    </div></div>
</main>
