<?php
$u=current_user();
if(!is_admin()&&!is_role(['company','employee','courier','motofreight'])){http_response_code(403);exit('Sem permissão.');}
$isCourierClientManager=in_array((string)$u['role'],['courier','motofreight'],true);
$courierCompanies=$isCourierClientManager?courier_linked_companies((int)$u['id']):[];
$companyId=is_admin()?(int)request('company_id',0):($isCourierClientManager?(int)request('company_id',($courierCompanies[0]['id']??0)):resolve_company_id_for_user($u));
if($isCourierClientManager&&!courier_can_register_company_client((int)$u['id'],$companyId)){http_response_code(403);exit('Você não está vinculado a esta empresa.');}
$canManageClients=is_admin()||$isCourierClientManager||$u['role']==='company'||($u['role']==='employee'&&company_member_can_manage_clients($u));
$companies=is_admin()?db()->query("SELECT id,name FROM companies WHERE status='active' ORDER BY name")->fetchAll():$courierCompanies;
if(is_admin()&&!$companyId&&$companies)$companyId=(int)$companies[0]['id'];
$clients=[];$search=trim((string)request('q',''));
if($companyId){
    $sql="SELECT DISTINCT u.*,CASE WHEN u.role='client' AND u.company_id=? THEN 1 ELSE 0 END direct_company_client FROM users u LEFT JOIN delivery_address_permissions dap ON dap.user_id=u.id AND dap.company_id=? AND dap.status='active' AND dap.always_visible=1 WHERE ((u.role='client' AND u.company_id=?) OR dap.id IS NOT NULL)";
    $params=[$companyId,$companyId,$companyId];
    if($search!==''){$like='%'.$search.'%';$digits=only_digits($search);$sql.=" AND (lower(COALESCE(u.name,'')) LIKE lower(?) OR lower(COALESCE(u.email,'')) LIKE lower(?) OR lower(COALESCE(u.username,'')) LIKE lower(?) OR upper(COALESCE(u.public_id,'')) LIKE upper(?)";array_push($params,$like,$like,$like,$like);if($digits!==''){$sql.=" OR COALESCE(u.phone,'') LIKE ?";$params[]='%'.$digits.'%';}$sql.=')';}
    $sql.=' ORDER BY u.name';$q=db()->prepare($sql);$q->execute($params);$clients=$q->fetchAll();
}
$clientCapacity=$companyId?company_capacity_info($companyId,'clients'):['limit'=>0,'used'=>0,'remaining'=>0,'enabled'=>false,'reached'=>true];
$permissionRows=[];try{$sql="SELECT r.*,c.name company_name,t.name target_name,t.public_id target_public_id,t.email target_email,req.name requested_by_name FROM company_edit_permission_requests r JOIN companies c ON c.id=r.company_id JOIN users t ON t.id=r.target_user_id LEFT JOIN users req ON req.id=r.requested_by";$params=[];if(!is_admin()){$sql.=" WHERE r.company_id=?";$params[]=$companyId;}$sql.=" ORDER BY CASE r.status WHEN 'pending' THEN 0 WHEN 'approved' THEN 1 ELSE 2 END,r.id DESC LIMIT 150";$pq=db()->prepare($sql);$pq->execute($params);$permissionRows=$pq->fetchAll();}catch(Throwable $e){}
$inviteUrl=$companyId?company_client_invite_url($companyId):'';
$qrImage=$inviteUrl?'https://api.qrserver.com/v1/create-qr-code/?size=320x320&margin=12&data='.rawurlencode($inviteUrl):'';
?>
<section class="page-intro"><div><span class="mini-label">CARTEIRA DA EMPRESA</span><h2>Clientes da empresa</h2><p>Qualquer usuário ativo pode se vincular como cliente sem perder seu perfil original na plataforma.</p></div><?php if($companyId):?><div class="actions"><span class="status <?= $clientCapacity['reached']?'status-overdue':'status-active' ?>">Clientes: <?= e(company_capacity_text($companyId,'clients')) ?></span><?php if(!$canManageClients):?><button class="btn btn-secondary" type="button" disabled>Somente consulta</button><?php elseif(!$clientCapacity['enabled']):?><button class="btn btn-secondary" type="button" disabled>Cadastro não liberado</button><?php elseif(!$clientCapacity['reached']):?><button class="btn btn-secondary" type="button" data-modal-open="#companyClientQrModal">▦ QR Code</button><button class="btn btn-primary" type="button" data-modal-open="#companyClientModal">+ Cadastrar cliente</button><?php else:?><button class="btn btn-secondary" type="button" disabled>Limite atingido</button><?php endif;?></div><?php endif;?></section>
<?php if(is_admin()||$isCourierClientManager):?><form class="filter-bar" method="get"><input type="hidden" name="page" value="company_clients"><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($companyId):?><form class="filter-bar" method="get"><input type="hidden" name="page" value="company_clients"><?php if(is_admin()):?><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><?php endif;?><div class="form-group" style="flex:1"><label>Pesquisar cliente para criar entrega</label><input class="input" name="q" value="<?= e($search) ?>" placeholder="Nome, ID LinkExpress, e-mail ou WhatsApp"></div><div class="actions"><button class="btn btn-primary">Pesquisar</button><?php if($search!==''):?><a class="btn btn-secondary" href="dashboard.php?page=company_clients<?= is_admin()?'&company_id='.(int)$companyId:'' ?>">Limpar</a><?php endif;?></div></form><?php endif;?>
<section class="panel" id="edit-permissions"><div class="panel-header"><div><h3>🔐 Permissões de edição</h3><p>As solicitações ficam dentro de Clientes da Empresa. A administração vê o nome da empresa e da conta solicitada.</p></div><?php if($permissionRows):?><span class="status <?=count(array_filter($permissionRows,fn($r)=>$r['status']==='pending'))?'status-overdue':'status-active'?>"><?=count(array_filter($permissionRows,fn($r)=>$r['status']==='pending'))?> pendente(s)</span><?php endif;?></div><div class="table-wrap"><table><thead><tr><th>Empresa</th><th>Cliente/funcionário</th><th>Tipo</th><th>Status</th><th>Ações</th></tr></thead><tbody><?php if(!$permissionRows):?><tr><td colspan="5"><div class="empty-state"><strong>Nenhuma solicitação de edição</strong></div></td></tr><?php endif;?><?php foreach($permissionRows as $r):$expired=!empty($r['expires_at'])&&strtotime($r['expires_at'])<time();?><tr><td><strong><?=e($r['company_name'])?></strong><small style="display:block">Solicitado por <?=e($r['requested_by_name']?:'usuário')?></small></td><td><strong><?=e($r['target_name'])?></strong><small style="display:block"><?=e($r['target_public_id']?:'')?> • <?=e($r['target_email']?:'')?></small></td><td><?=e($r['target_type']==='employee'?'Funcionário':'Cliente')?></td><td><?=status_badge($expired&&$r['status']==='approved'?'overdue':$r['status'])?></td><td><div class="actions"><?php if(is_admin()&&$r['status']==='pending'):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="review_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="id" value="<?=(int)$r['id']?>"><button class="btn btn-primary btn-sm" name="decision" value="approved">Aprovar</button><button class="btn btn-danger btn-sm" name="decision" value="rejected">Recusar</button></form><?php elseif(!is_admin()&&$r['status']==='approved'&&!$r['consumed_at']&&!$expired):?><a class="btn btn-primary btn-sm" href="dashboard.php?page=<?=e($r['target_type']==='employee'?'company_team':'company_clients')?>">Editar agora</a><?php endif;?></div></td></tr><?php endforeach;?></tbody></table></div></section>
<section class="panel" id="company-clients-list"><div class="panel-header"><div><h3>Clientes cadastrados pela empresa</h3><p>Clientes vinculados por QR Code entram nesta mesma lista após confirmarem o cadastro e a autorização de endereço.</p></div></div>
<div class="table-wrap"><table><thead><tr><th>Cliente</th><th>ID LinkExpress</th><th>WhatsApp</th><th>Endereço</th><th>Status</th><th>Ações</th></tr></thead><tbody>
<?php if(!$clients):?><tr><td colspan="6"><div class="empty-state"><strong>Nenhum cliente cadastrado</strong>Cadastre manualmente ou gere o QR Code para o cliente entrar pela própria conta.</div></td></tr><?php endif;?>
<?php foreach($clients as $item):?><tr><td><div class="table-title"><?= avatar_html($item,'table-thumb') ?><div><strong><?= e(user_public_name($item)) ?></strong><small style="display:block"><?= e($item['email']) ?> • <?= !empty($item['direct_company_client'])?'Cadastro da empresa':'Vinculado por QR Code' ?></small></div></div></td><td><strong><?= e(public_user_id($item)) ?></strong><button class="btn btn-secondary btn-sm" type="button" data-copy-text="<?= e(public_user_id($item)) ?>">Copiar</button></td><td><?= e(format_phone($item['phone'])) ?></td><td><?= e(short_text(full_user_address($item),70)) ?></td><td><?= status_badge($item['status']) ?></td><td><div class="actions"><a class="btn btn-secondary btn-sm" href="dashboard.php?page=client_profile&id=<?=urlencode(public_user_id($item))?>">Ver perfil</a><?php if(!empty($item['direct_company_client'])):$canEditClient=company_can_edit_linked_user((int)$companyId,(int)$item['id'],'client');$clientEditReq=company_edit_permission_request((int)$companyId,(int)$item['id'],'client');?><?php if($canEditClient):?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#companyClientModal<?= (int)$item['id'] ?>">Editar autorizado</button><?php elseif(!is_admin()&&$canManageClients):?><form method="post" action="actions.php" style="display:inline"><?=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="company_id" value="<?=(int)$companyId?>"><input type="hidden" name="target_type" value="client"><input type="hidden" name="target_user_id" value="<?=(int)$item['id']?>"><button class="btn btn-secondary btn-sm" <?=($clientEditReq&&$clientEditReq['status']==='pending')?'disabled':''?>><?=($clientEditReq&&$clientEditReq['status']==='pending')?'Permissão pendente':'Solicitar edição'?></button></form><?php endif;?><?php else:?><span class="status status-active">QR autorizado</span><?php endif;?><a class="btn btn-primary btn-sm" href="dashboard.php?page=deliveries&company_id=<?= (int)$companyId ?>&client_id=<?= urlencode(public_user_id($item)) ?>">Criar entrega</a><?php if($canManageClients):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="remove_company_client"><input type="hidden" name="return_page" value="company_clients"><input type="hidden" name="company_id" value="<?=(int)$companyId?>"><input type="hidden" name="client_user_id" value="<?=(int)$item['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Remover este usuário da área de clientes da empresa? A conta LinkExpress dele será mantida.">Remover cliente</button></form><?php endif;?></div></td></tr><?php endforeach;?>
</tbody></table></div></section>

<?php if($companyId&&$canManageClients&&$clientCapacity['enabled']&&!$clientCapacity['reached']):?><div class="modal" id="companyClientQrModal"><div class="modal-card" style="width:min(560px,100%)"><div class="modal-head"><h2>Cadastrar cliente por QR Code</h2><button class="close-btn" type="button" data-modal-close>×</button></div><div class="notice"><strong>Como funciona</strong><br>O cliente aponta a câmera do celular para o QR Code. A plataforma abre a página da empresa e pede a confirmação do cadastro. Se ele ainda não tiver conta, poderá criar uma e o vínculo será concluído automaticamente.</div><div style="display:grid;place-items:center;padding:22px 0"><img src="<?= e($qrImage) ?>" alt="QR Code para cadastro de cliente" width="320" height="320" style="width:min(320px,90vw);height:auto;background:#fff;padding:10px;border-radius:18px"></div><div class="form-group"><label>Link do convite</label><div class="inline-filter"><input class="input" value="<?= e($inviteUrl) ?>" readonly><button class="btn btn-secondary" type="button" data-copy-text="<?= e($inviteUrl) ?>">Copiar link</button></div></div><div class="form-actions"><a class="btn btn-primary" href="<?= e($inviteUrl) ?>" target="_blank" rel="noopener">Acessar Convite</a></div></div></div><?php endif;?>

<?php foreach($clients as $item):if(empty($item['direct_company_client'])||!company_can_edit_linked_user((int)$companyId,(int)$item['id'],'client'))continue;?>
<div class="modal" id="companyClientModal<?= (int)$item['id'] ?>"><div class="modal-card modal-large"><div class="modal-head"><h2>Editar cliente</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_client"><input type="hidden" name="return_page" value="company_clients"><input type="hidden" name="return_anchor" value="company-clients-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>Número da casa</label><input class="input" name="home_number" value="<?= e($item['home_number']??'') ?>"></div>
<div class="form-group full"><label>Endereço residencial</label><div class="inline-filter"><input class="input" name="home_address" value="<?= e($item['home_address']??'') ?>" data-address-autocomplete data-lat-field="home_lat" data-lng-field="home_lng"><button class="btn btn-secondary" type="button" data-geolocate-form data-address-field="home_address" data-lat-field="home_lat" data-lng-field="home_lng">📍 Localizar</button></div><input type="hidden" name="home_lat" value="<?= e($item['home_lat']??'') ?>"><input type="hidden" name="home_lng" value="<?= e($item['home_lng']??'') ?>"></div>
<div class="form-group"><label>Cidade</label><input class="input" name="city" value="<?= e($item['city']??'') ?>"></div><div class="form-group"><label>Estado</label><input class="input" name="state" maxlength="2" data-state-mask value="<?= e($item['state']??'') ?>"></div><div class="form-group full"><label>Nova senha (opcional)</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 cliente</button></div></form></div></div>
<?php endforeach;?>

<?php if($canManageClients&&$clientCapacity['enabled']&&!$clientCapacity['reached']):?><div class="modal" id="companyClientModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Novo cliente da empresa</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_client"><input type="hidden" name="return_page" value="company_clients"><input type="hidden" name="return_anchor" value="company-clients-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>Número da casa</label><input class="input" name="home_number"></div>
<div class="form-group full"><label>Endereço residencial</label><div class="inline-filter"><input class="input" name="home_address" data-address-autocomplete data-lat-field="home_lat" data-lng-field="home_lng" required><button class="btn btn-secondary" type="button" data-geolocate-form data-address-field="home_address" data-lat-field="home_lat" data-lng-field="home_lng">📍 Localizar</button></div><input type="hidden" name="home_lat"><input type="hidden" name="home_lng"></div>
<div class="form-group"><label>Cidade</label><input class="input" name="city"></div><div class="form-group"><label>Estado</label><input class="input" name="state" maxlength="2" data-state-mask></div><div class="form-group full"><label>Senha inicial</label><input class="input" name="password" value="123456"></div>
</div><div class="notice">O cadastro será feito em nome da empresa selecionada. Alterações posteriores continuam dependendo da autorização da administração da plataforma.</div><div class="form-actions"><button class="btn btn-primary">Cadastrar cliente</button></div></form></div></div>
<?php endif;?>
