<?php
$u=current_user();
if(!is_admin()&&!wallet_enabled_for_user($u)){http_response_code(403);echo '<div class="alert alert-warning">A carteira ainda não foi liberada pelo administrador.</div>';return;}
if(is_admin()){
    $walletAdminFilter=is_role('sub_admin')?" WHERE u.role NOT IN ('super_admin','sub_admin')":'';
    $wallets=db()->query("SELECT wa.*,u.name,u.public_id,u.role,u.pix_key,u.wallet_enabled FROM wallet_accounts wa JOIN users u ON u.id=wa.user_id".$walletAdminFilter." ORDER BY wa.balance DESC,u.name")->fetchAll();
    $requestAdminFilter=is_role('sub_admin')?" WHERE u.role NOT IN ('super_admin','sub_admin')":'';
    $requests=db()->query("SELECT wr.*,u.name,u.public_id,u.role FROM withdrawal_requests wr JOIN users u ON u.id=wr.user_id".$requestAdminFilter." ORDER BY CASE wr.status WHEN 'pending' THEN 0 ELSE 1 END,wr.id DESC LIMIT 300")->fetchAll();
    if(is_role('sub_admin')){
        $totalBalance=(float)db()->query("SELECT COALESCE(SUM(wa.balance),0) FROM wallet_accounts wa JOIN users u ON u.id=wa.user_id WHERE u.role NOT IN ('super_admin','sub_admin')")->fetchColumn();
        $pendingAmount=(float)db()->query("SELECT COALESCE(SUM(wr.amount),0) FROM withdrawal_requests wr JOIN users u ON u.id=wr.user_id WHERE wr.status='pending' AND u.role NOT IN ('super_admin','sub_admin')")->fetchColumn();
        $pendingCount=(int)db()->query("SELECT COUNT(*) FROM withdrawal_requests wr JOIN users u ON u.id=wr.user_id WHERE wr.status='pending' AND u.role NOT IN ('super_admin','sub_admin')")->fetchColumn();
    }else{
        $totalBalance=(float)db()->query('SELECT COALESCE(SUM(balance),0) FROM wallet_accounts')->fetchColumn();
        $pendingAmount=(float)db()->query("SELECT COALESCE(SUM(amount),0) FROM withdrawal_requests WHERE status='pending'")->fetchColumn();
        $pendingCount=(int)db()->query("SELECT COUNT(*) FROM withdrawal_requests WHERE status='pending'")->fetchColumn();
    }
}else{
    $account=wallet_account((int)$u['id']);$pendingAmount=wallet_pending_withdrawals((int)$u['id']);$available=wallet_available_balance((int)$u['id']);
    $q=db()->prepare('SELECT * FROM wallet_transactions WHERE user_id=? ORDER BY id DESC LIMIT 200');$q->execute([(int)$u['id']]);$transactions=$q->fetchAll();
    $q=db()->prepare('SELECT * FROM withdrawal_requests WHERE user_id=? ORDER BY id DESC LIMIT 100');$q->execute([(int)$u['id']]);$requests=$q->fetchAll();
}
?>
<section class="page-intro"><div><span class="mini-label">CARTEIRA DIGITAL</span><h2><?= is_admin()?'Carteiras e retiradas':'Minha Carteira' ?></h2><p><?= is_admin()?'Acompanhe saldos das vendas e aprove ou recuse solicitações de retirada.':'Cada pagamento confirmado soma automaticamente na carteira. Para receber, solicite a retirada ao administrador.' ?></p></div></section>
<?php if(is_admin()):?>
<div class="stats-grid"><article class="stat-card"><div class="stat-top"><span>Saldo nas carteiras</span><span class="stat-icon">👛</span></div><strong><?= money($totalBalance) ?></strong><small>Total acumulado pelos usuários</small></article><article class="stat-card"><div class="stat-top"><span>Retiradas pendentes</span><span class="stat-icon">⏳</span></div><strong><?= money($pendingAmount) ?></strong><small><?= $pendingCount ?> solicitação(ões)</small></article></div>
<section class="panel"><div class="panel-header"><div><h3>Solicitações de retirada</h3><p>Ao aprovar, o valor é debitado do saldo da carteira.</p></div></div><div class="table-wrap"><table><thead><tr><th>Usuário</th><th>Valor</th><th>Taxa</th><th>Líquido</th><th>Pix</th><th>Solicitado</th><th>Status</th><th>Ação</th></tr></thead><tbody><?php if(!$requests):?><tr><td colspan="8"><div class="empty-state"><strong>Nenhuma retirada</strong></div></td></tr><?php endif;?><?php foreach($requests as $r):?><tr><td><strong><?= e($r['name']) ?></strong><small style="display:block"><?= e($r['public_id'].' • '.role_label($r['role'])) ?></small></td><td><?= money($r['amount']) ?></td><td><?= money((float)($r['fee_amount']??0)) ?></td><td><strong><?= money((float)($r['payout_amount']?:$r['amount'])) ?></strong></td><td><?= e($r['pix_key']?:'—') ?></td><td><?= e(date('d/m/Y H:i',strtotime($r['created_at']))) ?></td><td><?= status_badge($r['status']) ?></td><td><?php if($r['status']==='pending'):?><button class="btn btn-primary btn-sm" data-modal-open="#withdraw<?= (int)$r['id'] ?>">Analisar</button><?php else:?><span class="muted"><?= e($r['admin_notes']?:'Analisada') ?></span><?php endif;?></td></tr><?php if($r['status']==='pending'):?><div class="modal" id="withdraw<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Analisar retirada</h2><button class="close-btn" data-modal-close>×</button></div><div class="notice"><strong><?= e($r['name']) ?></strong><br>Valor solicitado: <?= money($r['amount']) ?><br>Taxa de saque: <?= money((float)($r['fee_amount']??0)) ?><br><strong>Valor líquido: <?= money((float)($r['payout_amount']?:$r['amount'])) ?></strong><br>Pix: <?= e($r['pix_key']) ?></div><form method="post" action="actions.php" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="review_wallet_withdrawal"><input type="hidden" name="return_page" value="wallet"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><div class="form-group"><label>Observação</label><textarea name="admin_notes"></textarea></div><div class="form-actions"><button class="btn btn-danger" name="decision" value="rejected">Recusar</button><button class="btn btn-accent" name="decision" value="approved" data-confirm="Confirmar que esta retirada foi paga ao usuário?">Aprovar retirada</button></div></form></div></div><?php endif;?><?php endforeach;?></tbody></table></div></section>
<section class="panel"><div class="panel-header"><div><h3>Saldos dos usuários</h3><p>A carteira só aparece para o usuário quando a liberação estiver marcada em Usuários.</p></div></div><div class="table-wrap"><table><thead><tr><th>Usuário</th><th>Perfil</th><th>Liberada</th><th>Saldo</th><th>Total ganho</th><th>Retirado</th></tr></thead><tbody><?php if(!$wallets):?><tr><td colspan="6"><div class="empty-state"><strong>Nenhuma movimentação ainda</strong></div></td></tr><?php endif;?><?php foreach($wallets as $w):?><tr><td><strong><?= e($w['name']) ?></strong><small style="display:block"><?= e($w['public_id']) ?></small></td><td><?= e(role_label($w['role'])) ?></td><td><?= (int)$w['wallet_enabled']===1?'<span class="status status-active">Liberada</span>':'<span class="status status-inactive">Oculta</span>' ?></td><td><?= money($w['balance']) ?></td><td><?= money($w['total_earned']) ?></td><td><?= money($w['total_withdrawn']) ?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php else:?>
<div class="stats-grid"><article class="stat-card"><div class="stat-top"><span>Saldo atual</span><span class="stat-icon">👛</span></div><strong><?= money($account['balance']) ?></strong><small>Total disponível na carteira</small></article><article class="stat-card"><div class="stat-top"><span>Disponível para retirar</span><span class="stat-icon">💸</span></div><strong><?= money($available) ?></strong><small>Descontando solicitações pendentes</small></article><article class="stat-card"><div class="stat-top"><span>Total recebido</span><span class="stat-icon">↗</span></div><strong><?= money($account['total_earned']) ?></strong><small>Vendas e serviços confirmados</small></article><article class="stat-card"><div class="stat-top"><span>Total retirado</span><span class="stat-icon">✓</span></div><strong><?= money($account['total_withdrawn']) ?></strong><small>Retiradas já aprovadas</small></article></div>
<?php $simRule=platform_fee_rule_for((int)$u['id']);$withdrawType=(string)setting('wallet_withdrawal_fee_type','fixed');$withdrawValue=(float)setting('wallet_withdrawal_fee_value','0');$feePayer=fee_payer_preference_for_user($u);?>
<section class="panel"><div class="panel-header"><div><h3>🧮 Simulador de taxas</h3><p>Veja antes de cobrar ou retirar quanto a plataforma desconta/adiciona.</p></div></div><div class="form-grid fee-simulator" data-fee-simulator data-tx-type="<?= e($simRule['fee_type']??'fixed') ?>" data-tx-value="<?= e($simRule['fee_value']??0) ?>" data-tx-enabled="<?= platform_billing_mode_for_user($u)==='transaction'?1:0 ?>" data-fee-payer="<?= e($feePayer) ?>" data-withdraw-type="<?= e($withdrawType) ?>" data-withdraw-value="<?= e($withdrawValue) ?>"><div class="form-group"><label>Simular valor</label><input class="input" inputmode="decimal" value="100,00" data-fee-sim-amount></div><div class="notice full" data-fee-sim-result>Digite um valor para simular.</div></div></section>
<section class="panel"><div class="panel-header"><div><h3>Solicitar retirada</h3><p>O administrador receberá sua solicitação e fará a análise.</p></div></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="request_wallet_withdrawal"><input type="hidden" name="return_page" value="wallet"><div class="form-grid"><div class="form-group"><label>Valor da retirada</label><input class="input" name="amount" inputmode="decimal" placeholder="0,00" required><small>Mínimo: <?= money((float)setting('wallet_min_withdrawal','10')) ?></small></div><div class="form-group"><label>Chave Pix para receber</label><input class="input" name="pix_key" value="<?= e($u['pix_key']??'') ?>" required></div></div><div class="form-actions"><button class="btn btn-primary">Solicitar retirada</button></div></form></section>
<section class="panel"><div class="panel-header"><div><h3>Movimentações da carteira</h3></div></div><div class="table-wrap"><table><thead><tr><th>Data</th><th>Tipo</th><th>Descrição</th><th>Valor</th></tr></thead><tbody><?php if(!$transactions):?><tr><td colspan="4"><div class="empty-state"><strong>Nenhuma movimentação</strong></div></td></tr><?php endif;?><?php foreach($transactions as $t):?><tr><td><?= e(date('d/m/Y H:i',strtotime($t['created_at']))) ?></td><td><?= e($t['kind']==='sale'?'Venda recebida':'Retirada') ?></td><td><?= e($t['description']?:($t['source_type'].' #'.$t['source_id'])) ?></td><td><strong><?= ($t['amount']>=0?'+ ':'').money($t['amount']) ?></strong></td></tr><?php endforeach;?></tbody></table></div></section>
<section class="panel"><div class="panel-header"><div><h3>Minhas solicitações</h3></div></div><div class="table-wrap"><table><thead><tr><th>Data</th><th>Valor</th><th>Taxa</th><th>Líquido</th><th>Pix</th><th>Status</th><th>Observação</th></tr></thead><tbody><?php if(!$requests):?><tr><td colspan="7"><div class="empty-state"><strong>Nenhuma retirada solicitada</strong></div></td></tr><?php endif;?><?php foreach($requests as $r):?><tr><td><?= e(date('d/m/Y H:i',strtotime($r['created_at']))) ?></td><td><?= money($r['amount']) ?></td><td><?= money((float)($r['fee_amount']??0)) ?></td><td><?= money((float)($r['payout_amount']?:$r['amount'])) ?></td><td><?= e($r['pix_key']) ?></td><td><?= status_badge($r['status']) ?></td><td><?= e($r['admin_notes']?:'—') ?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php endif;?>
