<?php
$u=current_user();
if(!is_admin()&&!is_role(['company','employee'])){http_response_code(403);exit('Sem permissão.');}
$companyId=is_admin()?(int)request('company_id',0):resolve_company_id_for_user($u);
$companies=is_admin()?db()->query("SELECT id,name FROM companies WHERE status='active' ORDER BY name")->fetchAll():[];
if(is_admin()&&!$companyId&&$companies)$companyId=(int)$companies[0]['id'];
$company=null;$owner=null;$staff=[];$clinicProfessionals=[];
if($companyId){
    $q=db()->prepare("SELECT c.*,ou.name owner_name,ou.email owner_email,ou.phone owner_phone,ou.public_id owner_public_id FROM companies c LEFT JOIN users ou ON ou.id=c.owner_user_id WHERE c.id=?");$q->execute([$companyId]);$company=$q->fetch();
    if($company&&!empty($company['owner_user_id']))$owner=['id'=>(int)$company['owner_user_id'],'name'=>$company['owner_name'],'email'=>$company['owner_email'],'phone'=>$company['owner_phone'],'public_id'=>$company['owner_public_id']];
    $q=db()->prepare("SELECT * FROM users WHERE company_id=? AND role='employee' ORDER BY CASE company_access_level WHEN 'admin' THEN 0 WHEN 'manager' THEN 1 ELSE 2 END,name");$q->execute([$companyId]);$staff=$q->fetchAll();
    if(company_is_clinic($companyId)){$q=db()->prepare("SELECT p.*,s.name specialty_name,u.email,u.phone,u.public_id FROM clinic_professionals p LEFT JOIN clinic_specialties s ON s.id=p.specialty_id LEFT JOIN users u ON u.id=p.user_id WHERE p.company_id=? ORDER BY p.name");$q->execute([$companyId]);$clinicProfessionals=$q->fetchAll();}
}
$employeeCapacity=$companyId?company_capacity_info($companyId,'employees'):['limit'=>0,'used'=>0,'remaining'=>0,'enabled'=>false,'reached'=>true];
$canManageTeam=is_admin()||(string)($u['role']??'')==='company'||company_member_can_manage_team($u);
?>
<section class="page-intro"><div><span class="mini-label">EQUIPE INTERNA</span><h2>Funcionários</h2><p>Cada empresa possui um responsável e a equipe pode ter profissão/cargo e níveis de controle diferentes. Encerrar vínculo não apaga a conta pessoal.</p></div><?php if($companyId):?><div class="actions"><span class="status <?= $employeeCapacity['reached']?'status-overdue':'status-active' ?>">Funcionários: <?= e(company_capacity_text($companyId,'employees')) ?></span><?php if($canManageTeam&&$employeeCapacity['enabled']&&!$employeeCapacity['reached']):?><button class="btn btn-primary" type="button" data-modal-open="#employeeModal">+ Adicionar funcionário</button><?php endif;?></div><?php endif;?></section>
<?php if(is_admin()):?><form class="filter-bar" method="get"><input type="hidden" name="page" value="company_team"><div class="form-group"><label>Empresa</label><select name="company_id" data-auto-submit><?php foreach($companies as $c):?><option value="<?= (int)$c['id'] ?>"<?= selected($companyId,$c['id']) ?>><?= e($c['name']) ?></option><?php endforeach;?></select></div></form><?php endif;?>
<?php if($owner):?><section class="panel"><div class="panel-header"><div><h3>👑 Responsável pela empresa</h3><p>Conta principal responsável pela administração desta empresa.</p></div></div><article class="item-card"><div class="item-body"><div class="profile-hero"><div class="avatar">👤</div><div><h3><?=e($owner['name']?:'Responsável')?></h3><small><?=e($owner['public_id']?:'')?> • <?=e($owner['email']?:'')?></small></div></div><div class="item-meta"><span class="status status-active">Responsável / controle total</span><?php if($owner['phone']):?><span><?=e(format_phone($owner['phone']))?></span><?php endif;?></div></div></article></section><?php endif;?>
<?php if($clinicProfessionals):?><section class="panel"><div class="panel-header"><div><h3>Equipe clínica</h3><p>Médicos, demais profissionais de saúde e colaboradores vinculados ao atendimento.</p></div></div><div class="cards-list"><?php foreach($clinicProfessionals as $p):?><article class="item-card"><div class="item-body"><h3><?=e($p['name'])?></h3><div class="item-meta"><span>🩺 <?=e($p['professional_type']?:'Profissional')?></span><span><?=e($p['specialty_name']?:'Sem especialidade definida')?></span><?=status_badge($p['status'])?><?php if(!empty($p['email'])):?><span><?=e($p['email'])?></span><?php endif;?></div></div></article><?php endforeach;?></div></section><?php endif;?>
<section class="panel" id="company-team-list"><div class="panel-header"><div><h3>Equipe vinculada</h3><p>Administrador da empresa gerencia a equipe; gerente atua em clientes/operação; funcionário possui acesso operacional.</p></div></div><div class="cards-list"><?php if(!$staff):?><div class="empty-state"><strong>Nenhum funcionário cadastrado</strong></div><?php endif;?><?php foreach($staff as $item):?><article class="item-card"><div class="item-body"><div class="profile-hero"><?= avatar_html($item) ?><div><h3><?= e($item['name']) ?></h3><small><?= e(public_user_id($item)) ?> • <?= e($item['email']) ?></small></div></div><div class="item-meta"><span><?= status_badge($item['status']) ?></span><span><?= e(format_phone($item['phone'])) ?></span><span>💼 <?=e($item['company_position']?:'Profissão/cargo não informado')?></span><span>🔐 <?=e(company_access_level_label((string)($item['company_access_level']??'staff')))?></span></div><div class="actions"><?php $canEditStaff=company_can_edit_linked_user((int)$companyId,(int)$item['id'],'employee');$editReq=company_edit_permission_request((int)$companyId,(int)$item['id'],'employee'); ?><?php if($canManageTeam&&$canEditStaff):?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#employeeModal<?= (int)$item['id'] ?>">Editar autorizado</button><?php elseif($canManageTeam&&!is_admin()):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="request_company_edit_permission"><input type="hidden" name="return_page" value="company_clients"><input type="hidden" name="return_anchor" value="edit-permissions"><input type="hidden" name="target_type" value="employee"><input type="hidden" name="target_user_id" value="<?=(int)$item['id']?>"><button class="btn btn-secondary btn-sm" <?=($editReq&&$editReq['status']==='pending')?'disabled':''?>><?=($editReq&&$editReq['status']==='pending')?'Permissão pendente':'Solicitar edição'?></button></form><?php endif;?><?php if($canManageTeam):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="unlink_company_employee"><input type="hidden" name="return_page" value="company_team"><input type="hidden" name="return_anchor" value="company-team-list"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><button class="btn btn-danger btn-sm" data-confirm="Encerrar o vínculo deste funcionário? A conta dele continuará existindo na plataforma.">Encerrar vínculo</button></form><?php endif;?></div></div></article><?php endforeach;?></div></section>
<?php foreach($staff as $item):if(!$canManageTeam||!company_can_edit_linked_user((int)$companyId,(int)$item['id'],'employee'))continue;?><div class="modal" id="employeeModal<?= (int)$item['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Editar funcionário</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_company_employee"><input type="hidden" name="return_page" value="company_team"><input type="hidden" name="return_anchor" value="company-team-list"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><div class="form-grid"><div class="form-group"><label>Nome</label><input class="input" name="name" value="<?= e($item['name']) ?>" required></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email" value="<?= e($item['email']) ?>" required></div><div class="form-group"><label>WhatsApp</label><input class="input" name="phone" data-phone-mask value="<?= e($item['phone']) ?>"></div><div class="form-group"><label>Profissão / cargo</label><input class="input" name="company_position" value="<?=e($item['company_position']??'')?>" placeholder="Ex.: atendente, entregador, gerente"></div><div class="form-group"><label>Nível de controle</label><select name="company_access_level"><option value="staff"<?=selected($item['company_access_level']??'staff','staff')?>>Funcionário</option><option value="manager"<?=selected($item['company_access_level']??'staff','manager')?>>Gerente</option><option value="admin"<?=selected($item['company_access_level']??'staff','admin')?>>Administrador da empresa</option></select></div><div class="form-group"><label>Status</label><select name="status"><option value="active"<?= selected($item['status'],'active') ?>>Ativo</option><option value="blocked"<?= selected($item['status'],'blocked') ?>>Bloqueado</option></select></div><div class="form-group full"><label>Nova senha</label><input class="input" type="password" name="password" placeholder="Deixe vazio para manter"></div></div><div class="form-actions"><button class="btn btn-primary">Salvar funcionário</button></div></form></div></div><?php endforeach;?>
<?php if($canManageTeam&&$employeeCapacity['enabled']&&!$employeeCapacity['reached']):?><div class="modal" id="employeeModal"><div class="modal-card"><div class="modal-head"><h2>Novo funcionário</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_company_employee"><input type="hidden" name="return_page" value="company_team"><input type="hidden" name="return_anchor" value="company-team-list"><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><div class="form-grid"><div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email" required></div><div class="form-group"><label>WhatsApp</label><input class="input" name="phone" data-phone-mask></div><div class="form-group"><label>Profissão / cargo</label><input class="input" name="company_position" placeholder="Ex.: atendente, auxiliar, gerente"></div><div class="form-group"><label>Nível de controle</label><select name="company_access_level"><option value="staff">Funcionário</option><option value="manager">Gerente</option><option value="admin">Administrador da empresa</option></select></div><div class="form-group"><label>Senha inicial</label><input class="input" name="password" value="123456"></div></div><div class="form-actions"><button class="btn btn-primary">Cadastrar funcionário</button></div></form></div></div><?php endif;?>
