<?php
$u=current_user();$isManager=is_admin()||(in_array($u['role'],['company','employee'],true)&&($u['company_type']??'')==='shooting_club');
if(!$isManager){
  $st=db()->prepare('SELECT cm.*,c.name company_name,c.phone company_phone,c.address company_address,c.city company_city,c.state company_state FROM club_members cm JOIN companies c ON c.id=cm.company_id WHERE cm.user_id=? ORDER BY cm.id DESC LIMIT 1');$st->execute([$u['id']]);$member=$st->fetch();
  if(!$member){echo '<div class="notice">O módulo Clube e Associados aparece somente para usuários vinculados por um clube.</div>';return;}
  $ap=db()->prepare('SELECT * FROM club_appointments WHERE company_id=? AND member_id=? ORDER BY scheduled_at DESC');$ap->execute([$member['company_id'],$member['id']]);$memberAppointments=$ap->fetchAll();
  $co=db()->prepare('SELECT * FROM club_courses WHERE company_id=? AND status="open" ORDER BY starts_at');$co->execute([$member['company_id']]);$memberCourses=$co->fetchAll();
  ?>
  <section class="page-intro"><div><span class="mini-label">ÁREA DO ASSOCIADO</span><h2><?= e($member['company_name']) ?></h2><p>Seu vínculo, agenda e cursos disponíveis.</p></div><?php if($member['company_phone']):?><a class="btn btn-accent" target="_blank" href="<?= e(whatsapp_url($member['company_phone'],'Olá, sou associado pelo LinkExpress.')) ?>">WhatsApp do clube</a><?php endif;?></section>
  <div class="grid-2"><section class="panel"><div class="profile-hero"><?php if($member['photo']):?><div class="avatar avatar-has-image"><img src="<?= e(media_url($member['photo'])) ?>" alt=""></div><?php else:?><div class="avatar"><?= e(strtoupper(substr($member['name'],0,1))) ?></div><?php endif;?><div><h3><?= e($member['name']) ?></h3><p><?= e($member['plan_name']?:'Plano não informado') ?> • <?= status_badge($member['status']) ?></p><small>Vencimento: <?= $member['expires_at']?e(date('d/m/Y',strtotime($member['expires_at']))):'não definido' ?></small></div></div><div class="notice" style="margin-top:18px"><?= e($member['company_address'].' • '.$member['company_city'].'/'.$member['company_state']) ?></div></section><section class="panel"><div class="panel-header"><div><h3>Meus agendamentos</h3></div></div><div class="activity-list"><?php foreach($memberAppointments as $a):?><div class="activity"><span class="activity-dot"></span><div><p><?= e(ucfirst(str_replace('_',' ',$a['appointment_type']))) ?></p><small><?= e(date('d/m/Y H:i',strtotime($a['scheduled_at']))) ?> • <?= e($a['status']) ?></small></div></div><?php endforeach;?></div></section></div>
  <section class="panel"><div class="panel-header"><div><h3>Cursos disponíveis</h3></div></div><div class="cards-list"><?php foreach($memberCourses as $c):?><article class="item-card"><div class="item-body"><h3><?= e($c['title']) ?></h3><p><?= e($c['level']?:'Nível não informado') ?></p><small><?= $c['starts_at']?e(date('d/m/Y H:i',strtotime($c['starts_at']))):'Data a definir' ?></small></div></article><?php endforeach;?></div></section>
  <?php return;
}
$companyId=is_admin()?(int)request('company_id',0):(int)$u['company_id'];
if(is_admin()&&$companyId===0){$companyId=(int)db()->query("SELECT id FROM companies WHERE type='shooting_club' ORDER BY id LIMIT 1")->fetchColumn();}
$companies=is_admin()?db()->query("SELECT * FROM companies WHERE type='shooting_club' ORDER BY name")->fetchAll():[];
$members=[];$instructors=[];$appointments=[];$courses=[];$assets=[];$ammo=[];
if($companyId){
 foreach(['members'=>'club_members','instructors'=>'club_instructors','appointments'=>'club_appointments','courses'=>'club_courses','assets'=>'club_assets','ammo'=>'club_ammunition'] as $var=>$table){$st=db()->prepare("SELECT * FROM $table WHERE company_id=? ORDER BY id DESC");$st->execute([$companyId]);$$var=$st->fetchAll();}
}
?>
<div class="page-intro"><div><span class="mini-label">GESTÃO ADMINISTRATIVA</span><h2>Clube e Associados</h2><p>Associados, instrutores, agendamentos, cursos, patrimônio, estoque administrativo e mensalidades.</p></div><?php if(is_admin()):?><form method="get" action="dashboard.php" class="inline-filter"><input type="hidden" name="page" value="club"><select name="company_id" data-auto-submit><option value="0">Selecione um clube</option><?php foreach($companies as $c):?><option value="<?= (int)$c['id'] ?>"<?= selected($companyId,$c['id']) ?>><?= e($c['name']) ?></option><?php endforeach;?></select></form><?php endif;?></div>
<?php if(!$companyId):?><div class="notice">Cadastre uma empresa com o segmento <strong>Clube esportivo de tiro</strong> e selecione-a para acessar este painel.</div><?php else:?>
<div class="stats-grid compact-stats"><article class="stat-card"><span>Associados</span><strong><?= count($members) ?></strong><small>Ativos, inativos e bloqueados</small></article><article class="stat-card"><span>Agendamentos</span><strong><?= count($appointments) ?></strong><small>Reservas e aulas</small></article><article class="stat-card"><span>Instrutores</span><strong><?= count($instructors) ?></strong><small>Equipe cadastrada</small></article><article class="stat-card"><span>Alertas de estoque</span><strong><?= count(array_filter($ammo,fn($a)=>(int)$a['quantity']<=(int)$a['minimum_stock'])) ?></strong><small>Itens no limite mínimo</small></article></div>
<div class="quick-actions club-actions"><button class="quick-action" data-modal-open="#linkMemberModal"><span>🪪</span><b>Associar por ID</b></button><button class="quick-action" data-modal-open="#memberModal"><span>👤</span><b>Novo associado</b></button><button class="quick-action" data-modal-open="#instructorModal"><span>🧑‍🏫</span><b>Novo instrutor</b></button><button class="quick-action" data-modal-open="#appointmentModal"><span>📅</span><b>Novo agendamento</b></button><button class="quick-action" data-modal-open="#courseModal"><span>🎓</span><b>Novo curso</b></button><button class="quick-action" data-modal-open="#assetModal"><span>🗂️</span><b>Item patrimonial</b></button><button class="quick-action" data-modal-open="#ammoModal"><span>📦</span><b>Estoque administrativo</b></button></div>
<div class="grid-2">
<section class="panel"><div class="panel-header"><div><h3>Associados</h3><p>Cadastro, plano, vencimento e situação.</p></div></div><div class="table-wrap"><table><thead><tr><th>Associado</th><th>Plano</th><th>Vencimento</th><th>Status</th></tr></thead><tbody><?php foreach($members as $m):?><tr><td><div class="table-title"><div class="table-thumb"><?php if($m['photo']):?><img src="<?= e(media_url($m['photo'])) ?>" alt=""><?php else:?>👤<?php endif;?></div><div><strong><?= e($m['name']) ?></strong><small><?= e($m['document']) ?></small></div></div></td><td><?= e($m['plan_name']?:'—') ?></td><td><?= $m['expires_at']?e(date('d/m/Y',strtotime($m['expires_at']))):'—' ?></td><td><?= status_badge($m['status']) ?></td></tr><?php endforeach;?></tbody></table></div></section>
<section class="panel"><div class="panel-header"><div><h3>Agenda</h3><p>Reservas, aulas e presença.</p></div></div><div class="activity-list"><?php foreach(array_slice($appointments,0,15) as $a):$memberName='Associado';foreach($members as $m)if((int)$m['id']===(int)$a['member_id'])$memberName=$m['name'];?><div class="activity"><span class="activity-dot"></span><div><p><?= e($memberName) ?> — <?= e(ucfirst(str_replace('_',' ',$a['appointment_type']))) ?></p><small><?= e(date('d/m/Y H:i',strtotime($a['scheduled_at']))) ?> • <?= e($a['status']) ?></small></div></div><?php endforeach;?></div></section>
</div>
<div class="grid-3">
<section class="panel"><div class="panel-header"><div><h3>Cursos</h3></div></div><?php foreach($courses as $c):?><div class="activity"><span class="activity-dot"></span><div><p><?= e($c['title']) ?></p><small><?= e($c['level']?:'Nível não informado') ?> • <?= (int)$c['enrolled'] ?>/<?= (int)$c['capacity'] ?> inscritos</small></div></div><?php endforeach;?></section>
<section class="panel"><div class="panel-header"><div><h3>Patrimônio</h3></div></div><?php foreach($assets as $a):?><div class="activity"><span class="activity-dot"></span><div><p><?= e($a['asset_name']) ?></p><small><?= e($a['category'].' • '.$a['caliber'].' • '.$a['status']) ?></small></div></div><?php endforeach;?></section>
<section class="panel"><div class="panel-header"><div><h3>Estoque administrativo</h3></div></div><?php foreach($ammo as $a):?><div class="activity"><span class="activity-dot <?= (int)$a['quantity']<=(int)$a['minimum_stock']?'danger-dot':'' ?>"></span><div><p><?= e($a['caliber']) ?> — <?= (int)$a['quantity'] ?> unidades</p><small>Mínimo: <?= (int)$a['minimum_stock'] ?><?= (int)$a['quantity']<=(int)$a['minimum_stock']?' • Reposição necessária':'' ?></small></div></div><?php endforeach;?></section>
</div>

<div class="modal" id="linkMemberModal"><div class="modal-card"><div class="modal-head"><h2>Associar usuário pelo ID</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="link_club_member_by_id"><input type="hidden" name="return_page" value="club"><?php if(is_admin()):?><input type="hidden" name="company_id" value="<?= $companyId ?>"><?php endif;?><div class="form-grid"><div class="form-group full"><label>ID LinkExpress do usuário</label><input class="input" name="public_id" data-user-id-preview placeholder="LXU-AB7K-9Q2M" required><small data-user-preview-output>Digite o ID para confirmar somente o nome.</small></div><div class="form-group"><label>Plano</label><input class="input" name="plan_name"></div><div class="form-group"><label>Vencimento</label><input class="input" type="date" name="expires_at"></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Associar usuário</button></div></form></div></div>
<div class="modal" id="memberModal"><div class="modal-card"><div class="modal-head"><h2>Novo associado</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php" enctype="multipart/form-data"><?= csrf_field() ?><input type="hidden" name="action" value="save_club_member"><input type="hidden" name="return_page" value="club"><?php if(is_admin()):?><input type="hidden" name="company_id" value="<?= $companyId ?>"><?php endif;?><div class="form-grid"><div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>CPF</label><input class="input" name="document" data-document-mask required></div><div class="form-group"><label>Telefone</label><input class="input" name="phone"></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email"></div><div class="form-group"><label>Plano</label><input class="input" name="plan_name"></div><div class="form-group"><label>Vencimento</label><input class="input" type="date" name="expires_at"></div><div class="form-group"><label>Status</label><select name="status"><option value="active">Ativo</option><option value="inactive">Inativo</option><option value="blocked">Bloqueado</option></select></div><div class="form-group"><label>Foto</label><input class="input" type="file" name="photo_file" accept="image/jpeg,image/png,image/webp"></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Salvar associado</button></div></form></div></div>
<div class="modal" id="instructorModal"><div class="modal-card"><div class="modal-head"><h2>Novo instrutor</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_club_instructor"><input type="hidden" name="return_page" value="club"><?php if(is_admin()):?><input type="hidden" name="company_id" value="<?= $companyId ?>"><?php endif;?><div class="form-grid"><div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>Status</label><select name="status"><option value="available">Disponível</option><option value="busy">Ocupado</option><option value="inactive">Inativo</option></select></div><div class="form-group full"><label>Especialidades</label><input class="input" name="specialties"></div><div class="form-group full"><label>Certificações</label><textarea name="certifications"></textarea></div><div class="form-group"><label>Telefone</label><input class="input" name="phone"></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email"></div></div><div class="form-actions"><button class="btn btn-primary">Salvar instrutor</button></div></form></div></div>
<div class="modal" id="appointmentModal"><div class="modal-card"><div class="modal-head"><h2>Novo agendamento</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_club_appointment"><input type="hidden" name="return_page" value="club"><?php if(is_admin()):?><input type="hidden" name="company_id" value="<?= $companyId ?>"><?php endif;?><div class="form-grid"><div class="form-group"><label>Associado</label><select name="member_id"><?php foreach($members as $m):?><option value="<?= (int)$m['id'] ?>"><?= e($m['name']) ?></option><?php endforeach;?></select></div><div class="form-group"><label>Instrutor</label><select name="instructor_id"><option value="">Sem instrutor</option><?php foreach($instructors as $i):?><option value="<?= (int)$i['id'] ?>"><?= e($i['name']) ?></option><?php endforeach;?></select></div><div class="form-group"><label>Tipo</label><select name="appointment_type"><option value="range">Reserva de estande</option><option value="class">Aula</option><option value="course">Curso</option><option value="visit">Visita</option></select></div><div class="form-group"><label>Data e horário</label><input class="input" type="datetime-local" name="scheduled_at" required></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Salvar agendamento</button></div></form></div></div>
<div class="modal" id="courseModal"><div class="modal-card"><div class="modal-head"><h2>Novo curso</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_club_course"><input type="hidden" name="return_page" value="club"><?php if(is_admin()):?><input type="hidden" name="company_id" value="<?= $companyId ?>"><?php endif;?><div class="form-grid"><div class="form-group"><label>Título</label><input class="input" name="title" required></div><div class="form-group"><label>Nível</label><select name="level"><option>Básico</option><option>Avançado</option><option>Reciclagem</option><option>Treinamento</option></select></div><div class="form-group"><label>Instrutor</label><select name="instructor_id"><option value="">A definir</option><?php foreach($instructors as $i):?><option value="<?= (int)$i['id'] ?>"><?= e($i['name']) ?></option><?php endforeach;?></select></div><div class="form-group"><label>Início</label><input class="input" type="datetime-local" name="starts_at"></div><div class="form-group"><label>Capacidade</label><input class="input" type="number" name="capacity"></div><div class="form-group"><label>Inscritos</label><input class="input" type="number" name="enrolled"></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Salvar curso</button></div></form></div></div>
<div class="modal" id="assetModal"><div class="modal-card"><div class="modal-head"><h2>Item patrimonial</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_club_asset"><input type="hidden" name="return_page" value="club"><?php if(is_admin()):?><input type="hidden" name="company_id" value="<?= $companyId ?>"><?php endif;?><div class="form-grid"><div class="form-group"><label>Categoria</label><input class="input" name="category" placeholder="Equipamento, acessório..."></div><div class="form-group"><label>Nome do item</label><input class="input" name="asset_name" required></div><div class="form-group"><label>Calibre/Especificação</label><input class="input" name="caliber"></div><div class="form-group"><label>Nº patrimônio</label><input class="input" name="patrimony_number"></div><div class="form-group"><label>Status</label><select name="status"><option value="available">Disponível</option><option value="maintenance">Manutenção</option><option value="unavailable">Indisponível</option></select></div><div class="form-group"><label>Próxima manutenção</label><input class="input" type="date" name="maintenance_at"></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Salvar item</button></div></form></div></div>
<div class="modal" id="ammoModal"><div class="modal-card"><div class="modal-head"><h2>Controle de estoque administrativo</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_club_ammunition"><input type="hidden" name="return_page" value="club"><?php if(is_admin()):?><input type="hidden" name="company_id" value="<?= $companyId ?>"><?php endif;?><div class="form-grid"><div class="form-group"><label>Calibre/Referência</label><input class="input" name="caliber" required></div><div class="form-group"><label>Quantidade</label><input class="input" type="number" name="quantity" min="0"></div><div class="form-group"><label>Estoque mínimo</label><input class="input" type="number" name="minimum_stock" min="0"></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="notice">Este módulo registra estoque e alertas administrativos. Não realiza venda, compra ou orientação de uso.</div><div class="form-actions"><button class="btn btn-primary">Salvar estoque</button></div></form></div></div>
<?php endif;?>
