<?php
$isTermsAdmin=is_admin();
if($isTermsAdmin){
    $terms=db()->query('SELECT t.*,(SELECT COUNT(*) FROM term_acceptances a WHERE a.term_id=t.id) acceptance_count FROM platform_terms t ORDER BY t.sort_order,t.id')->fetchAll();
}else{
    $terms=active_platform_terms();
}
?>
<section class="page-intro"><div><span class="mini-label">REGRAS DA PLATAFORMA</span><h2>Termos e Políticas</h2><p><?= $isTermsAdmin?'Crie, publique e atualize os documentos da plataforma. Os usuários visualizam somente os documentos ativos.':'Consulte os Termos de Uso, a Política de Privacidade e demais documentos atualmente publicados pela plataforma.' ?></p></div><?php if($isTermsAdmin):?><div class="actions"><a class="btn btn-secondary" target="_blank" rel="noopener" href="<?= e(url('terms.php')) ?>">Ver página pública</a><button class="btn btn-primary" data-modal-open="#termModal">+ Novo documento</button></div><?php endif;?></section>

<?php if(!$isTermsAdmin):?>
<section class="terms-reader-grid">
  <?php if(!$terms):?><div class="panel"><div class="empty-state"><strong>Nenhum documento publicado</strong><span>O administrador ainda não publicou Termos e Políticas ativos.</span></div></div><?php endif;?>
  <?php foreach($terms as $term):?><article class="panel policy-document" id="term-<?= (int)$term['id'] ?>"><div class="panel-header"><div><h3><?= e($term['title']) ?></h3><p>Versão <?= (int)$term['version'] ?> • Atualizado em <?= e(date('d/m/Y H:i',strtotime($term['updated_at']))) ?></p></div><?= !empty($term['required'])?'<span class="status status-active">Obrigatório</span>':'' ?></div><div class="policy-content"><?= nl2br(e($term['content'])) ?></div></article><?php endforeach;?>
</section>
<?php else:?>
<section class="panel"><div class="panel-header"><div><h3>Documentos cadastrados</h3><p>Ative um documento para que ele apareça aos usuários e na página pública.</p></div></div><div class="table-wrap"><table><thead><tr><th>Documento</th><th>Versão</th><th>Obrigatório</th><th>Status</th><th>Aceites</th><th>Ordem</th><th>Ações</th></tr></thead><tbody>
<?php if(!$terms):?><tr><td colspan="7"><div class="empty-state"><strong>Nenhum termo cadastrado</strong></div></td></tr><?php endif;?>
<?php foreach($terms as $term):?><tr><td><strong><?= e($term['title']) ?></strong><small style="display:block"><?= e(short_text($term['content'],90)) ?></small></td><td>v<?= (int)$term['version'] ?></td><td><?= !empty($term['required'])?'Sim':'Não' ?></td><td><?= status_badge($term['status']) ?></td><td><?= (int)$term['acceptance_count'] ?></td><td><?= (int)$term['sort_order'] ?></td><td><div class="actions"><button class="btn btn-secondary btn-sm" data-modal-open="#termEdit<?= (int)$term['id'] ?>">Editar</button><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_platform_term"><input type="hidden" name="return_page" value="terms_policies"><input type="hidden" name="id" value="<?= (int)$term['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Remover este documento? Se já houver aceites, ele será apenas desativado.">Apagar</button></form></div></td></tr><?php endforeach;?>
</tbody></table></div></section>

<div class="modal" id="termModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Novo termo ou política</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="save_platform_term"><input type="hidden" name="return_page" value="terms_policies"><div class="form-grid"><div class="form-group full"><label>Título</label><input class="input" name="title" required placeholder="Ex.: Política de Privacidade"></div><div class="form-group full"><label>Conteúdo</label><textarea name="content" rows="16" required></textarea></div><div class="form-group"><label>Obrigatório no cadastro</label><select name="required"><option value="1">Sim</option><option value="0">Não</option></select></div><div class="form-group"><label>Status</label><select name="status"><option value="active">Ativo</option><option value="inactive">Inativo</option></select></div><div class="form-group"><label>Ordem</label><input class="input" type="number" name="sort_order" value="0"></div></div><div class="form-actions"><button class="btn btn-primary">Publicar documento</button></div></form></div></div>
<?php foreach($terms as $term):?><div class="modal" id="termEdit<?= (int)$term['id'] ?>"><div class="modal-card modal-large"><div class="modal-head"><h2>Editar documento</h2><button class="close-btn" type="button" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="save_platform_term"><input type="hidden" name="return_page" value="terms_policies"><input type="hidden" name="id" value="<?= (int)$term['id'] ?>"><div class="notice">Se o título ou conteúdo mudar, a versão será aumentada automaticamente. Os aceites antigos permanecem registrados.</div><div class="form-grid" style="margin-top:14px"><div class="form-group full"><label>Título</label><input class="input" name="title" value="<?= e($term['title']) ?>" required></div><div class="form-group full"><label>Conteúdo</label><textarea name="content" rows="16" required><?= e($term['content']) ?></textarea></div><div class="form-group"><label>Obrigatório</label><select name="required"><option value="1"<?= selected($term['required'],1) ?>>Sim</option><option value="0"<?= selected($term['required'],0) ?>>Não</option></select></div><div class="form-group"><label>Status</label><select name="status"><option value="active"<?= selected($term['status'],'active') ?>>Ativo</option><option value="inactive"<?= selected($term['status'],'inactive') ?>>Inativo</option></select></div><div class="form-group"><label>Ordem</label><input class="input" type="number" name="sort_order" value="<?= (int)$term['sort_order'] ?>"></div></div><div class="form-actions"><button class="btn btn-primary">Salvar alterações</button></div></form></div></div><?php endforeach;?>
<?php endif;?>
