<?php
require_roles('super_admin');
$segments=db()->query('SELECT * FROM segments ORDER BY sort_order,name')->fetchAll();
$categories=db()->query('SELECT c.*,co.name company_name FROM categories c LEFT JOIN companies co ON co.id=c.company_id ORDER BY c.module,c.sort_order,c.name')->fetchAll();
$companies=db()->query('SELECT id,name FROM companies ORDER BY name')->fetchAll();
$moduleLabels=['products'=>'Produtos','services'=>'Serviços','companies'=>'Empresas','vehicles'=>'Veículos'];
$reservedSlugs=['delivery','market','pharmacy','vehicle_store','rental','moving','taxi','mototaxi','services','shooting_club','clinic','other'];
$segmentRoleOptions=[];foreach(segment_registration_roles() as $r)$segmentRoleOptions[$r]=role_label($r);
?>
<section class="page-intro">
  <div><span class="mini-label">ESTRUTURA DA PLATAFORMA</span><h2>Categorias e segmentos</h2><p>Crie, edite, desative ou apague categorias e segmentos usados nos cadastros da LinkExpress.</p></div>
  <div class="actions"><button class="btn btn-primary" data-modal-open="#segmentModal">+ Segmento</button><button class="btn btn-secondary" data-modal-open="#categoryAdminModal">+ Categoria</button></div>
</section>

<section class="panel">
  <div class="panel-header"><div><h3>Segmentos por perfil</h3><p>Defina quais perfis podem escolher cada segmento no cadastro. O identificador técnico dos segmentos nativos fica protegido para não quebrar os módulos.</p></div></div>
  <div class="table-wrap"><table><thead><tr><th>Ícone</th><th>Nome</th><th>Identificador</th><th>Perfis</th><th>Status</th><th>Ordem</th><th>Ações</th></tr></thead><tbody>
  <?php if(!$segments):?><tr><td colspan="7"><div class="empty-state"><strong>Nenhum segmento cadastrado</strong>Use o botão “+ Segmento” para criar o primeiro.</div></td></tr><?php endif;?>
  <?php foreach($segments as $s):?>
    <tr>
      <td><?= e($s['icon']?:'•') ?></td><td><strong><?= e($s['name']) ?></strong></td><td><code><?= e($s['slug']) ?></code></td><td><small><?= e(implode(', ',array_map('role_label',segment_allowed_roles($s)))) ?></small></td><td><?= status_badge($s['status']) ?></td><td><?= (int)$s['sort_order'] ?></td>
      <td><div class="actions">
        <button class="btn btn-secondary btn-sm" type="button" data-modal-open="#segmentEdit<?= (int)$s['id'] ?>">Editar</button>
        <form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_segment"><input type="hidden" name="return_page" value="segments"><input type="hidden" name="id" value="<?= (int)$s['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar o segmento <?= e($s['name']) ?>? A exclusão será bloqueada se alguma empresa ainda estiver usando este segmento.">Apagar</button></form>
      </div></td>
    </tr>
  <?php endforeach;?>
  </tbody></table></div>
</section>

<section class="panel">
  <div class="panel-header"><div><h3>Categorias cadastradas</h3><p>Ao apagar uma categoria, os produtos e serviços continuam cadastrados e ficam sem categoria até você escolher outra.</p></div></div>
  <div class="table-wrap"><table><thead><tr><th>Categoria</th><th>Módulo</th><th>Empresa</th><th>Status</th><th>Ordem</th><th>Ações</th></tr></thead><tbody>
  <?php if(!$categories):?><tr><td colspan="6"><div class="empty-state"><strong>Nenhuma categoria cadastrada</strong>Use o botão “+ Categoria”.</div></td></tr><?php endif;?>
  <?php foreach($categories as $c):?>
    <tr>
      <td><strong><?= e(($c['icon']?:'•').' '.$c['name']) ?></strong></td><td><?= e($moduleLabels[$c['module']]??$c['module']) ?></td><td><?= e($c['company_name']?:'Global') ?></td><td><?= status_badge($c['status']) ?></td><td><?= (int)$c['sort_order'] ?></td>
      <td><div class="actions"><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#categoryEdit<?= (int)$c['id'] ?>">Editar</button>
        <form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_category"><input type="hidden" name="return_page" value="segments"><input type="hidden" name="id" value="<?= (int)$c['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar a categoria <?= e($c['name']) ?>? Os itens cadastrados serão mantidos sem categoria.">Apagar</button></form>
      </div></td>
    </tr>
  <?php endforeach;?>
  </tbody></table></div>
</section>

<div class="modal" id="segmentModal"><div class="modal-card"><div class="modal-head"><h2>Novo segmento</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_segment"><input type="hidden" name="return_page" value="segments"><div class="form-grid"><div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>Identificador</label><input class="input" name="slug" placeholder="exemplo_segmento" required><small>Use letras, números e _.</small></div><div class="form-group"><label>Ícone</label><input class="input" name="icon" placeholder="🏢"></div><div class="form-group"><label>Ordem</label><input class="input" type="number" name="sort_order" value="0"></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 full"><label>Perfis que podem usar este segmento no cadastro</label><div class="permission-grid"><?php foreach($segmentRoleOptions as $r=>$label):?><label class="check-line"><input type="checkbox" name="allowed_roles[]" value="<?= e($r) ?>"<?= $r==='company'?' checked':'' ?>> <?= e($label) ?></label><?php endforeach;?></div></div></div><div class="form-actions"><button class="btn btn-primary">Salvar segmento</button></div></form></div></div>

<div class="modal" id="categoryAdminModal"><div class="modal-card"><div class="modal-head"><h2>Nova categoria</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_category"><input type="hidden" name="return_page" value="segments"><div class="form-grid"><div class="form-group"><label>Módulo</label><select name="module"><?php foreach($moduleLabels as $value=>$label):?><option value="<?= e($value) ?>"><?= e($label) ?></option><?php endforeach;?></select></div><div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>Ícone</label><input class="input" name="icon"></div><div class="form-group"><label>Ordem</label><input class="input" type="number" name="sort_order" value="0"></div><div class="form-group"><label>Status</label><select name="status"><option value="active">Ativa</option><option value="inactive">Inativa</option></select></div><div class="form-group"><label>Empresa</label><select name="company_id"><option value="0">Global</option><?php foreach($companies as $co):?><option value="<?= (int)$co['id'] ?>"><?= e($co['name']) ?></option><?php endforeach;?></select></div></div><div class="form-actions"><button class="btn btn-primary">Salvar categoria</button></div></form></div></div>

<?php foreach($segments as $s): $isReserved=in_array($s['slug'],$reservedSlugs,true); ?>
<div class="modal" id="segmentEdit<?= (int)$s['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Editar segmento</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_segment"><input type="hidden" name="return_page" value="segments"><input type="hidden" name="id" value="<?= (int)$s['id'] ?>">
    <div class="form-grid">
      <div class="form-group"><label>Nome</label><input class="input" name="name" required value="<?= e($s['name']) ?>"></div>
      <div class="form-group"><label>Identificador</label><input class="input" name="slug" required value="<?= e($s['slug']) ?>" <?= $isReserved?'readonly':'' ?>><?php if($isReserved):?><small>Identificador técnico protegido neste módulo.</small><?php endif;?></div>
      <div class="form-group"><label>Ícone</label><input class="input" name="icon" value="<?= e($s['icon']) ?>"></div>
      <div class="form-group"><label>Ordem</label><input class="input" type="number" name="sort_order" value="<?= (int)$s['sort_order'] ?>"></div>
      <div class="form-group"><label>Status</label><select name="status"><option value="active"<?= selected($s['status'],'active') ?>>Ativo</option><option value="inactive"<?= selected($s['status'],'inactive') ?>>Inativo</option></select></div><div class="form-group full"><label>Perfis relacionados</label><div class="permission-grid"><?php $allowedNow=segment_allowed_roles($s);foreach($segmentRoleOptions as $r=>$label):?><label class="check-line"><input type="checkbox" name="allowed_roles[]" value="<?= e($r) ?>"<?= in_array($r,$allowedNow,true)?' checked':'' ?>> <?= e($label) ?></label><?php endforeach;?></div></div>
    </div><div class="form-actions"><button class="btn btn-primary">Salvar alterações</button></div>
  </form>
</div></div>
<?php endforeach;?>

<?php foreach($categories as $c):?>
<div class="modal" id="categoryEdit<?= (int)$c['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Editar categoria</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_category"><input type="hidden" name="return_page" value="segments"><input type="hidden" name="id" value="<?= (int)$c['id'] ?>">
    <div class="form-grid">
      <div class="form-group"><label>Módulo</label><select name="module"><?php foreach($moduleLabels as $value=>$label):?><option value="<?= e($value) ?>"<?= selected($c['module'],$value) ?>><?= e($label) ?></option><?php endforeach;?></select></div>
      <div class="form-group"><label>Nome</label><input class="input" name="name" required value="<?= e($c['name']) ?>"></div>
      <div class="form-group"><label>Ícone</label><input class="input" name="icon" value="<?= e($c['icon']) ?>"></div>
      <div class="form-group"><label>Ordem</label><input class="input" type="number" name="sort_order" value="<?= (int)$c['sort_order'] ?>"></div>
      <div class="form-group"><label>Status</label><select name="status"><option value="active"<?= selected($c['status'],'active') ?>>Ativa</option><option value="inactive"<?= selected($c['status'],'inactive') ?>>Inativa</option></select></div>
      <div class="form-group"><label>Empresa</label><select name="company_id"><option value="0">Global</option><?php foreach($companies as $co):?><option value="<?= (int)$co['id'] ?>"<?= selected($c['company_id'],$co['id']) ?>><?= e($co['name']) ?></option><?php endforeach;?></select></div>
    </div><div class="form-actions"><button class="btn btn-primary">Salvar alterações</button></div>
  </form>
</div></div>
<?php endforeach;?>
