<?php
$u=current_user();
$canBillClients=client_billing_enabled_for_user($u);
$canUsePix=pix_billing_enabled_for_user($u);
if(is_admin()){
  if(is_role('sub_admin'))$charges=db()->query("SELECT ch.*,ru.name user_name,ru.email,ru.phone user_phone,ru.telegram user_telegram,iu.name issuer_name FROM charges ch JOIN users ru ON ru.id=ch.user_id LEFT JOIN users iu ON iu.id=ch.issuer_user_id WHERE ru.role NOT IN ('super_admin','sub_admin') AND (iu.role IS NULL OR iu.role NOT IN ('super_admin','sub_admin')) ORDER BY ch.id DESC")->fetchAll();
  else $charges=db()->query('SELECT ch.*,ru.name user_name,ru.email,ru.phone user_phone,ru.telegram user_telegram,iu.name issuer_name FROM charges ch JOIN users ru ON ru.id=ch.user_id LEFT JOIN users iu ON iu.id=ch.issuer_user_id ORDER BY ch.id DESC')->fetchAll();
  $chargeUsers=db()->query("SELECT id,name,email,public_id FROM users WHERE role NOT IN ('super_admin','sub_admin') ORDER BY name")->fetchAll();
}else{
  $q=db()->prepare('SELECT ch.*,ru.name user_name,ru.email,ru.phone user_phone,ru.telegram user_telegram,iu.name issuer_name FROM charges ch JOIN users ru ON ru.id=ch.user_id LEFT JOIN users iu ON iu.id=ch.issuer_user_id WHERE ch.user_id=? OR ch.issuer_user_id=? ORDER BY ch.id DESC');$q->execute([$u['id'],$u['id']]);$charges=$q->fetchAll();$chargeUsers=[];
}
$q=db()->prepare('SELECT * FROM payment_links WHERE owner_user_id=? ORDER BY id DESC');$q->execute([$u['id']]);$links=$q->fetchAll();
$canManagePaymentLinks=$canBillClients&&!is_role('sub_admin');
$q=db()->prepare('SELECT cb.*,cu.name,cu.public_id,cu.phone,cu.telegram FROM contact_book cb JOIN users cu ON cu.id=cb.contact_user_id WHERE cb.owner_user_id=? ORDER BY cu.name');$q->execute([$u['id']]);$contacts=$q->fetchAll();
$restricted=account_restricted($u);
?>
<section class="page-intro"><div><span class="mini-label"><?= $restricted?'ACESSO LIMITADO':'COBRANÇAS ENTRE USUÁRIOS' ?></span><h2>Cobranças e links de pagamento</h2><p><?= is_admin()?'O administrador pode cobrar qualquer usuário ativo.':($canBillClients?'Você pode cobrar os clientes permitidos para sua conta.':'Você continua vendo cobranças recebidas, mas o envio de cobranças depende de liberação do administrador.') ?></p></div><?php if($canBillClients):?><div class="actions"><?php if($canManagePaymentLinks):?><button class="btn btn-secondary" data-modal-open="#paymentLinkModal">+ Link de cobrança</button><?php endif;?><button class="btn btn-primary" data-modal-open="#chargeModal">+ Enviar cobrança</button></div><?php endif;?></section>
<?php if($restricted):?><div class="alert alert-error restricted-alert">Regularize a cobrança obrigatória para liberar os demais módulos. Ao enviar o comprovante, o acesso é liberado provisoriamente enquanto o Admin analisa.</div><?php elseif(!empty($u['provisional_access_until'])&&$u['provisional_access_until']>=now()):?><div class="alert alert-warning">Acesso provisório liberado até <?= e(date('d/m/Y H:i',strtotime($u['provisional_access_until']))) ?> enquanto o comprovante é analisado.</div><?php endif;?>
<?php if(!$canBillClients&&!is_admin()):?><div class="notice" style="margin-bottom:18px"><strong>🔒 Sistema de cobrança não liberado.</strong> O administrador pode habilitar esta função no seu cadastro. Suas cobranças recebidas continuam disponíveis normalmente.</div><?php endif;?>
<?php if($canManagePaymentLinks):?><section class="panel"><div class="panel-header"><div><h3>Meus links rápidos</h3><p>Use no envio pela plataforma, WhatsApp ou Telegram. Pix só fica disponível quando liberado pelo administrador.</p></div></div><div class="cards-list"><?php if(!$links):?><div class="empty-state"><strong>Nenhum link salvo</strong>Cadastre uma URL de pagamento<?= $canUsePix?' ou chave Pix':'' ?>.</div><?php endif;foreach($links as $l):?><article class="item-card"><div class="item-body"><h3><?= e($l['title']) ?></h3><p><?= e($l['url']?:($canUsePix&&$l['pix_key']?'Pix: '.$l['pix_key']:'Forma de pagamento cadastrada')) ?></p><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_payment_link"><input type="hidden" name="return_page" value="charges"><input type="hidden" name="id" value="<?= (int)$l['id'] ?>"><button class="btn btn-danger btn-sm">Apagar</button></form></div></article><?php endforeach;?></div></section><?php endif;?>
<section class="panel"><div class="panel-header"><div><h3>Cobranças recebidas e enviadas</h3></div></div><div class="table-wrap"><table><thead><tr><th>De/Para</th><th>Descrição</th><th>Valor</th><th>Vencimento</th><th>Status</th><th>Pagamento</th><th>Ação</th></tr></thead><tbody>
<?php if(!$charges):?><tr><td colspan="7"><div class="empty-state"><strong>Nenhuma cobrança</strong></div></td></tr><?php endif;?>
<?php foreach($charges as $ch):$received=(int)$ch['user_id']===(int)$u['id'];$issuerId=(int)($ch['issuer_user_id']??0);$chargePay=$issuerId>0?calculate_platform_fee($issuerId,(float)$ch['amount'],'charge',(int)$ch['id']):['base'=>(float)$ch['amount'],'fee'=>0,'total'=>(float)$ch['amount'],'client_total'=>(float)$ch['amount'],'recipient_net'=>(float)$ch['amount'],'fee_payer'=>'client'];?>
<tr><td><strong><?= e($received?($ch['issuer_name']?:'Administrador'):$ch['user_name']) ?></strong><small style="display:block"><?= $received?'Recebida':'Enviada' ?></small></td><td><?= e($ch['description']) ?></td><td><strong><?= money($chargePay['total']) ?></strong><?php if($chargePay['fee']>0):?><small style="display:block">Base <?= money($chargePay['base']) ?> • taxa <?= money($chargePay['fee']) ?> paga por <?= ($chargePay['fee_payer']??'client')==='provider'?'prestador/empresa':'cliente' ?></small><?php endif;?></td><td><?= $ch['due_date']?e(date('d/m/Y',strtotime($ch['due_date']))):'—' ?></td><td><?= status_badge($ch['status']) ?></td><td><?php if($ch['payment_link']):?><a class="btn btn-primary btn-sm" target="_blank" rel="noopener" href="<?= e($ch['payment_link']) ?>">Acessar Pagamento</a><?php elseif($ch['pix_key_snapshot']):?><span class="notice"><strong>Pix:</strong> <span class="pix-value"><?= e($ch['pix_key_snapshot']) ?></span> <button type="button" class="btn btn-accent btn-sm" data-copy-text="<?= e($ch['pix_key_snapshot']) ?>">📋 Copiar Pix</button></span><?php else:?><span class="muted">Contato direto</span><?php endif;?></td><td><div class="actions"><?php if($received&&in_array($ch['status'],['pending','overdue','rejected'],true)):?><button class="btn btn-secondary btn-sm" data-modal-open="#proof<?= (int)$ch['id'] ?>">Enviar comprovante</button><?php endif;?><?php if(is_admin()||(!$received&&(int)$ch['issuer_user_id']===(int)$u['id'])):?><button class="btn btn-secondary btn-sm" data-modal-open="#reviewCharge<?= (int)$ch['id'] ?>">Analisar</button><?php endif;?><?php if(is_admin()):?><form method="post" action="actions.php" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="delete_charge"><input type="hidden" name="return_page" value="charges"><input type="hidden" name="id" value="<?= (int)$ch['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar esta cobrança definitivamente?">Apagar</button></form><?php endif;?></div></td></tr>
<?php if($received):?><div class="modal" id="proof<?= (int)$ch['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Enviar comprovante</h2><button class="close-btn" data-modal-close>×</button></div><div class="notice"><strong>Valor base:</strong> <?= money($chargePay['base']) ?><?php if($chargePay['fee']>0):?><br><strong>Taxa da plataforma:</strong> <?= money($chargePay['fee']) ?><?php endif;?><br><strong>Total a pagar:</strong> <?= money($chargePay['total']) ?><?php if(($chargePay['fee_payer']??'client')==='provider'&&$chargePay['fee']>0):?><br><small>Líquido do recebedor após taxa: <?= money($chargePay['recipient_net']) ?></small><?php endif;?></div><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="send_charge_proof"><input type="hidden" name="return_page" value="charges"><input type="hidden" name="id" value="<?= (int)$ch['id'] ?>"><div class="form-group"><label>Imagem ou PDF</label><input class="input" type="file" name="proof_file" accept="image/jpeg,image/png,image/webp,application/pdf" required></div><div class="form-actions"><button class="btn btn-primary">Enviar</button></div></form></div></div><?php endif;?>
<?php if(is_admin()||(!$received&&(int)$ch['issuer_user_id']===(int)$u['id'])):?><div class="modal" id="reviewCharge<?= (int)$ch['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Analisar cobrança</h2><button class="close-btn" data-modal-close>×</button></div><?php if($ch['proof']):?><a class="btn btn-secondary" target="_blank" href="<?= e(media_url($ch['proof'])) ?>">Acessar Comprovante</a><?php endif;?><form method="post" action="actions.php" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="update_charge"><input type="hidden" name="return_page" value="charges"><input type="hidden" name="id" value="<?= (int)$ch['id'] ?>"><div class="form-group"><label>Status</label><select name="status"><option value="paid">Pagamento aprovado</option><option value="rejected">Comprovante recusado</option><option value="pending">Pendente</option><option value="overdue">Vencida</option></select></div><div class="form-group"><label>Observação</label><textarea name="admin_notes"><?= e($ch['admin_notes']) ?></textarea></div><?php if(is_admin()&&(int)$ch['blocks_access']===1):?><label class="check-line"><input type="checkbox" name="blacklist_user" value="1"> Se o comprovante for recusado, bloquear e colocar o usuário na lista negra</label><?php endif;?><div class="form-actions"><button class="btn btn-primary">Salvar</button></div></form></div></div><?php endif;?>
<?php endforeach;?></tbody></table></div></section>
<?php
$receiptCutoff=date('Y-m-d H:i:s',strtotime('-3 months'));
$oldReceiptCount=0;
if(is_admin()){
    if(is_role('sub_admin')){
        $receiptRows=db()->query("SELECT r.*,pu.name payer_name,ru.name recipient_name FROM receipts r LEFT JOIN users pu ON pu.id=r.payer_user_id LEFT JOIN users ru ON ru.id=r.recipient_user_id WHERE (pu.role IS NULL OR pu.role NOT IN ('super_admin','sub_admin')) AND (ru.role IS NULL OR ru.role NOT IN ('super_admin','sub_admin')) ORDER BY r.id DESC LIMIT 200")->fetchAll();
        $oc=db()->prepare("SELECT COUNT(*) FROM receipts r LEFT JOIN users pu ON pu.id=r.payer_user_id LEFT JOIN users ru ON ru.id=r.recipient_user_id WHERE r.created_at<=? AND (pu.role IS NULL OR pu.role NOT IN ('super_admin','sub_admin')) AND (ru.role IS NULL OR ru.role NOT IN ('super_admin','sub_admin'))");$oc->execute([$receiptCutoff]);$oldReceiptCount=(int)$oc->fetchColumn();
    }else{
        $receiptRows=db()->query("SELECT r.*,pu.name payer_name,ru.name recipient_name FROM receipts r LEFT JOIN users pu ON pu.id=r.payer_user_id LEFT JOIN users ru ON ru.id=r.recipient_user_id ORDER BY r.id DESC LIMIT 200")->fetchAll();
        $oc=db()->prepare('SELECT COUNT(*) FROM receipts WHERE created_at<=?');$oc->execute([$receiptCutoff]);$oldReceiptCount=(int)$oc->fetchColumn();
    }
}else{
    $rr=db()->prepare("SELECT r.*,pu.name payer_name,ru.name recipient_name FROM receipts r LEFT JOIN users pu ON pu.id=r.payer_user_id LEFT JOIN users ru ON ru.id=r.recipient_user_id WHERE r.payer_user_id=? OR r.recipient_user_id=? ORDER BY r.id DESC LIMIT 100");$rr->execute([$u['id'],$u['id']]);$receiptRows=$rr->fetchAll();
}
?>
<section class="panel"><div class="panel-header"><div><h3>📁 Pasta de comprovantes</h3><p>Recibos PNG gerados automaticamente em cobranças, vendas, serviços, corridas e locações confirmadas.</p><?php if(is_admin()):?><small><?= $oldReceiptCount ?> comprovante(s) registrado(s) com 3 meses ou mais.</small><?php endif;?></div><?php if(is_admin()):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_old_receipts"><input type="hidden" name="return_page" value="charges"><button class="btn btn-danger btn-sm" data-confirm="Apagar todos os comprovantes gerados com 3 meses ou mais? Os registros de cobrança e financeiro serão mantidos, mas os PNGs antigos serão removidos.">🗑 Apagar comprovantes +3 meses</button></form><?php endif;?></div><div class="cards-list"><?php if(!$receiptRows):?><div class="empty-state"><strong>Nenhum comprovante gerado</strong>Quando um pagamento for confirmado, o recibo aparecerá aqui automaticamente.</div><?php endif;foreach($receiptRows as $rc):$receiptUrl=generated_receipt_url((string)$rc['receipt_path'],(string)$rc['source_type'],(int)$rc['source_id']);?><article class="item-card"><div class="item-body"><h3><?= e(status_label($rc['source_type'])) ?> #<?= (int)$rc['source_id'] ?></h3><p><?= e($rc['description']) ?> • <?= money($rc['amount']) ?></p><small><?= e(($rc['payer_name']?:'Pagador').' → '.($rc['recipient_name']?:'Recebedor')) ?></small><div class="actions" style="margin-top:12px"><?php if($receiptUrl):?><a class="btn btn-primary btn-sm" target="_blank" href="<?= e($receiptUrl) ?>">Acessar Comprovante</a><?php endif;?></div></div></article><?php endforeach;?></div></section>
<?php if($canBillClients):?>
<?php if($canManagePaymentLinks):?><div class="modal" id="paymentLinkModal"><div class="modal-card"><div class="modal-head"><h2>Novo link de cobrança</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_payment_link"><input type="hidden" name="return_page" value="charges"><div class="form-grid"><div class="form-group full"><label>Título</label><input class="input" name="title" placeholder="Pagamento de serviços" required></div><div class="form-group full"><label>Link de pagamento</label><input class="input" type="url" name="url" placeholder="https://..."></div><?php if($canUsePix):?><div class="form-group full"><label>Ou chave Pix</label><input class="input" name="pix_key" value="<?= e($u['pix_key']??'') ?>"></div><?php else:?><div class="form-group full"><div class="notice">🔒 Pix não liberado pelo administrador. Você pode cadastrar apenas uma URL de pagamento.</div></div><?php endif;?></div><div class="form-actions"><button class="btn btn-primary">Salvar</button></div></form></div></div><?php endif;?>
<div class="modal" id="chargeModal"><div class="modal-card"><div class="modal-head"><h2>Enviar cobrança</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_charge"><input type="hidden" name="return_page" value="charges"><div class="form-grid"><?php if(is_admin()):?><div class="form-group full"><label>Usuário</label><select name="user_id"><option value="">Escolha ou use o ID abaixo</option><?php foreach($chargeUsers as $cu):?><option value="<?= (int)$cu['id'] ?>"><?= e($cu['name'].' — '.$cu['public_id']) ?></option><?php endforeach;?></select></div><?php endif;?><div class="form-group full"><label>ID LinkExpress do destinatário</label><input class="input" name="recipient_public_id" data-user-id-preview data-user-preview-purpose="charge" placeholder="LXU-AB7K-9Q2M"><small data-user-preview-output><?= is_admin()?'Digite o ID para confirmar somente o nome.':'Digite o ID. O nome só aparecerá se for cliente cadastrado pela sua empresa ou já tiver utilizado seus serviços.' ?></small></div><div class="form-group"><label>Valor base</label><input class="input" name="amount" required></div><div class="form-group"><label>Vencimento</label><input class="input" type="date" name="due_date"></div><div class="form-group"><label>Forma de cobrança</label><select name="payment_method"><?php if($canUsePix):?><option value="pix">Pix</option><?php endif;?><?php if(!is_role('sub_admin')):?><option value="link">Link / outro meio</option><?php endif;?><option value="card">Cartão</option><option value="cash">Dinheiro</option></select></div><div class="form-group full"><label>Descrição</label><input class="input" name="description" required></div><?php if(!is_role('sub_admin')):?><div class="form-group"><label>Link salvo</label><select name="payment_link_id"><option value="">Usar perfil/link manual</option><?php foreach($links as $l):?><option value="<?= (int)$l['id'] ?>"><?= e($l['title']) ?></option><?php endforeach;?></select></div><div class="form-group"><label>Link manual</label><input class="input" type="url" name="payment_link"></div><?php else:?><div class="form-group full"><div class="notice">🔒 Administrador pode registrar cobranças, mas não pode anexar nem enviar links de pagamento.</div></div><?php endif;?><?php if(is_admin()):?><div class="form-group"><label>Bloquear acesso se não pagar?</label><select name="blocks_access"><option value="0">Não</option><option value="1">Sim</option></select></div><?php endif;?></div><div class="notice" style="margin-top:12px">Se houver uma taxa ativa para seu perfil, segmento, categoria ou conta, ela será somada automaticamente ao valor apresentado ao cliente.</div><div class="form-actions"><button class="btn btn-primary">Enviar cobrança</button></div></form></div></div>
<?php endif;?>
<?php if($contacts&&$canBillClients):?><section class="panel"><div class="panel-header"><div><h3>Envio rápido para contatos</h3><p>Use WhatsApp ou Telegram para compartilhar suas cobranças.</p></div></div><div class="cards-list"><?php foreach($contacts as $c):?><article class="item-card"><div class="item-body"><h3><?= e($c['name']) ?></h3><small><?= e($c['public_id']) ?></small><div class="actions" style="margin-top:12px"><?php if($c['phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($c['phone'],'Olá! Tenho uma cobrança para você na LinkExpress. Acesse sua área de Cobranças.')) ?>">WhatsApp</a><?php endif;?><?php if($c['telegram']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(telegram_url($c['telegram'])) ?>">Telegram</a><?php endif;?></div></div></article><?php endforeach;?></div></section><?php endif;?>
