<?php
$u=current_user();
if(is_admin()){
  $q=db()->query('SELECT p.*,u.name payer_name,c.name company_name FROM payments p LEFT JOIN users u ON u.id=p.payer_user_id LEFT JOIN companies c ON c.id=p.company_id ORDER BY p.id DESC');$payments=$q->fetchAll();
}else{
  // Movimentações novas são espelhadas por owner_user_id: quem recebeu vê Ganho e quem pagou vê Gasto.
  // Registros antigos continuam aparecendo quando owner_user_id ainda não existia.
  $q=db()->prepare('SELECT p.*,u.name payer_name,c.name company_name FROM payments p LEFT JOIN users u ON u.id=p.payer_user_id LEFT JOIN companies c ON c.id=p.company_id WHERE p.owner_user_id=? OR (p.owner_user_id IS NULL AND p.payer_user_id=?) ORDER BY p.id DESC');$q->execute([$u['id'],$u['id']]);$payments=$q->fetchAll();
}
$totals=['income'=>0,'expense'=>0,'pending'=>0];
foreach($payments as $p){if($p['status']==='paid'){if(($p['entry_kind']??'')==='expense')$totals['expense']+=(float)$p['amount'];else $totals['income']+=(float)$p['amount'];}elseif($p['status']==='pending')$totals['pending']+=(float)$p['amount'];}
$users=is_admin()?db()->query('SELECT id,name FROM users ORDER BY name')->fetchAll():[];$companies=is_admin()?db()->query('SELECT id,name FROM companies ORDER BY name')->fetchAll():[];
?>
<div class="stats-grid"><article class="stat-card"><div class="stat-top"><span>Ganhos confirmados</span><span class="stat-icon">✅</span></div><strong><?= money($totals['income']) ?></strong><small>Entradas registradas</small></article><article class="stat-card"><div class="stat-top"><span>Gastos confirmados</span><span class="stat-icon">↘</span></div><strong><?= money($totals['expense']) ?></strong><small>Saídas registradas</small></article><article class="stat-card"><div class="stat-top"><span>Pendente</span><span class="stat-icon">⏳</span></div><strong><?= money($totals['pending']) ?></strong><small>Aguardando confirmação</small></article><article class="stat-card"><div class="stat-top"><span>Minha chave Pix</span><span class="stat-icon">◆</span></div><strong style="font-size:1rem"><?= e($u['pix_key']?:'Não cadastrada') ?></strong><small><?= e($u['pix_key_type']?:'Cadastre no Meu Perfil') ?></small></article></div>
<section class="panel"><div class="panel-header"><div><h2>Financeiro</h2><p>Ganhos, gastos e comprovantes gerados automaticamente por pagamentos confirmados.</p></div><button class="btn btn-primary" data-modal-open="#paymentModal">+ Registrar movimentação</button></div><div class="table-wrap"><table><thead><tr><th>Tipo</th><th>Referência</th><th>Valor</th><th>Método</th><th>Status</th><th>Comprovantes</th><th>Ações</th></tr></thead><tbody><?php if(!$payments):?><tr><td colspan="7"><div class="empty-state"><strong>Nenhuma movimentação</strong></div></td></tr><?php endif;foreach($payments as $p):$kind=$p['entry_kind']??'';?><tr><td><span class="<?= $kind==='expense'?'finance-entry-expense':'finance-entry-income' ?>"><?= $kind==='expense'?'Gasto':($kind==='income'?'Ganho':status_label($p['reference_type'])) ?></span></td><td><strong><?= e(status_label($p['reference_type'])) ?></strong><?php if($p['notes']):?><small style="display:block"><?= e(short_text($p['notes'],60)) ?></small><?php endif;?></td><td><?= money($p['amount']) ?></td><td><?= e(status_label($p['method'])) ?></td><td><?= status_badge($p['status']) ?></td><td><div class="actions"><?php if($p['proof']):?><a class="btn btn-secondary btn-sm" href="<?= e(media_url($p['proof'])) ?>" target="_blank">Comprovante enviado</a><?php endif;?><?php if($p['receipt_path']):?><a class="btn btn-accent btn-sm" href="<?= e(generated_receipt_url((string)$p['receipt_path'],(string)$p['reference_type'],(int)$p['reference_id'])) ?>" target="_blank">Comprovante gerado</a><?php endif;?></div></td><td><div class="actions"><?php if(is_admin()):?><button class="btn btn-secondary btn-sm" data-modal-open="#paymentStatus<?= (int)$p['id'] ?>">Atualizar</button><?php endif;?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_payment"><input type="hidden" name="return_page" value="finance"><input type="hidden" name="id" value="<?= (int)$p['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar esta movimentação?">Apagar</button></form></div></td></tr><?php if(is_admin()):?><div class="modal" id="paymentStatus<?= (int)$p['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Atualizar movimentação</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_payment"><input type="hidden" name="return_page" value="finance"><input type="hidden" name="id" value="<?= (int)$p['id'] ?>"><div class="form-group"><label>Status</label><select name="status"><option value="paid">Pago</option><option value="pending">Pendente</option><option value="overdue">Vencido</option><option value="cancelled">Cancelado</option></select></div><div class="form-actions"><button class="btn btn-primary">Salvar</button></div></form></div></div><?php endif;?><?php endforeach;?></tbody></table></div></section>
<div class="modal" id="paymentModal"><div class="modal-card"><div class="modal-head"><h2>Registrar ganho ou gasto</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_payment"><input type="hidden" name="return_page" value="finance"><div class="form-grid"><?php if(is_admin()):?><div class="form-group"><label>Usuário</label><select name="payer_user_id"><option value="">Nenhum</option><?php foreach($users as $x):?><option value="<?= (int)$x['id'] ?>"><?= e($x['name']) ?></option><?php endforeach;?></select></div><div class="form-group"><label>Empresa</label><select name="company_id"><option value="">Nenhuma</option><?php foreach($companies as $x):?><option value="<?= (int)$x['id'] ?>"><?= e($x['name']) ?></option><?php endforeach;?></select></div><?php endif;?><div class="form-group"><label>Tipo</label><select name="reference_type"><option value="income">Ganho</option><option value="expense">Gasto</option><option value="subscription">Mensalidade</option><option value="order">Pedido</option><option value="ride">Corrida</option><option value="service">Serviço</option><option value="vehicle_rental">Locação</option><option value="property_booking">Imóvel/Piscina</option></select></div><div class="form-group"><label>Valor</label><input class="input" name="amount" required></div><div class="form-group"><label>Método</label><select name="method"><option value="pix">Pix</option><option value="card">Cartão</option><option value="cash">Dinheiro</option><option value="boleto">Boleto</option></select></div><div class="form-group"><label>Vencimento</label><input class="input" type="date" name="due_date"></div><div class="form-group full"><label>Comprovante</label><input class="input" type="file" name="proof_file" accept="image/jpeg,image/png,image/webp,application/pdf"></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">Registrar</button></div></form></div></div>
