<?php
require_roles('super_admin');
$rules=db()->query('SELECT * FROM platform_fee_rules ORDER BY id DESC')->fetchAll();
$roles=notification_role_options();
$segments=db()->query("SELECT slug,name FROM segments WHERE status='active' ORDER BY name")->fetchAll();
$categories=db()->query("SELECT id,name,module FROM categories WHERE status='active' ORDER BY module,name")->fetchAll();
$users=db()->query("SELECT id,name,public_id,role FROM users WHERE role NOT IN ('super_admin','sub_admin') ORDER BY name LIMIT 1000")->fetchAll();
function fee_scope_label_local($r,$roles,$segments,$categories,$users){$type=$r['scope_type'];$v=(string)$r['scope_value'];if($type==='all')return 'Todos os usuários';if($type==='role')return 'Perfil: '.($roles[$v]??role_label($v));if($type==='segment'){foreach($segments as $s)if($s['slug']===$v)return 'Segmento: '.$s['name'];return 'Segmento: '.$v;}if($type==='category'){foreach($categories as $c)if((string)$c['id']===$v)return 'Categoria: '.$c['name'].' ('.$c['module'].')';return 'Categoria #'.$v;}if($type==='user'){foreach($users as $u)if((string)$u['id']===$v)return 'Usuário: '.$u['name'].' ('.$u['public_id'].')';return 'Usuário #'.$v;}return $type.': '.$v;}
?>
<section class="page-intro"><div><span class="mini-label">COBRANÇA DA PLATAFORMA</span><h2>Taxas da Plataforma</h2><p>Defina taxa fixa ou percentual. A regra mais específica vence: usuário → categoria → segmento → perfil → geral.</p></div><button class="btn btn-primary" data-modal-open="#feeModal">+ Nova taxa</button></section>
<section class="panel"><div class="panel-header"><div><h3>Tarifa de saque e pagamento pela plataforma</h3><p>Configure a tarifa de retirada e o link oficial usado pela plataforma nos pagamentos de serviços.</p></div></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="save_financial_fee_settings"><input type="hidden" name="return_page" value="fees"><div class="form-grid"><div class="form-group"><label>Tipo da tarifa de saque</label><select name="withdrawal_fee_type"><option value="fixed"<?= selected(setting('wallet_withdrawal_fee_type','fixed'),'fixed') ?>>Valor fixo</option><option value="percent"<?= selected(setting('wallet_withdrawal_fee_type','fixed'),'percent') ?>>Percentual</option></select></div><div class="form-group"><label>Valor da tarifa</label><input class="input" name="withdrawal_fee_value" inputmode="decimal" value="<?= e(setting('wallet_withdrawal_fee_value','0')) ?>"></div><div class="form-group full"><label>Link da plataforma para pagamentos de serviços</label><input class="input" type="url" name="platform_service_payment_link" value="<?= e(setting('platform_service_payment_link','')) ?>" placeholder="https://..."><small>Este é o link oficial de pagamento da plataforma. Ele pode ser exibido ao cliente após a confirmação do serviço; se não houver Pix configurado, também funciona como fallback global.</small></div></div><div class="form-actions"><button class="btn btn-primary">Salvar configurações financeiras</button></div></form></section>

<section class="panel"><div class="panel-header"><div><h3>Tarifas por tipo de corrida</h3><p>Mototáxi, táxi e motorista particular possuem cálculo e valor mínimo independentes.</p></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_financial_fee_settings"><input type="hidden" name="return_page" value="fees"><input type="hidden" name="withdrawal_fee_type" value="<?=e(setting('wallet_withdrawal_fee_type','fixed'))?>"><input type="hidden" name="withdrawal_fee_value" value="<?=e(setting('wallet_withdrawal_fee_value','0'))?>"><input type="hidden" name="platform_service_payment_link" value="<?=e(setting('platform_service_payment_link',''))?>"><div class="grid-3"><?php foreach(['mototaxi'=>'Mototáxi','taxi'=>'Táxi','private_driver'=>'Motorista particular'] as $slug=>$label):$fare=ride_fare_settings($slug);$prefix='ride_'.$slug.'_';?><article class="item-card"><div class="item-body"><h3><?=e($label)?></h3><div class="form-group"><label>Definição do valor</label><select name="<?=$prefix?>auto_fare_enabled"><option value="0"<?=selected($fare['auto']?'1':'0','0')?>>Motorista informa; cliente aceita</option><option value="1"<?=selected($fare['auto']?'1':'0','1')?>>Cálculo automático</option></select></div><div class="form-group"><label>Preço por km</label><input class="input" name="<?=$prefix?>price_km" inputmode="decimal" value="<?=e((string)$fare['price_km'])?>"></div><div class="form-group"><label>Tarifa inicial</label><input class="input" name="<?=$prefix?>base_fare" inputmode="decimal" value="<?=e((string)$fare['base'])?>"></div><div class="form-group"><label>Valor mínimo</label><input class="input" name="<?=$prefix?>min_fare" inputmode="decimal" value="<?=e((string)$fare['min'])?>"></div></div></article><?php endforeach;?></div><div class="form-actions"><button class="btn btn-primary">Salvar tarifas das corridas</button></div></form></section>

<section class="panel"><div class="notice">A taxa segue a escolha da conta: pode ser acrescentada ao valor do cliente ou descontada do prestador/empresa. A parte da plataforma é registrada separadamente como receita do Administrador Sênior.</div><div class="table-wrap" style="margin-top:14px"><table><thead><tr><th>Aplicação</th><th>Tipo</th><th>Valor</th><th>Status</th><th>Ações</th></tr></thead><tbody><?php if(!$rules):?><tr><td colspan="5"><div class="empty-state"><strong>Nenhuma taxa configurada</strong>Sem regra ativa, nenhuma taxa extra é cobrada.</div></td></tr><?php endif;?><?php foreach($rules as $r):?><tr><td><strong><?= e(fee_scope_label_local($r,$roles,$segments,$categories,$users)) ?></strong></td><td><?= e($r['fee_type']==='percent'?'Percentual':'Valor fixo') ?></td><td><?= $r['fee_type']==='percent'?e(number_format((float)$r['fee_value'],2,',','.')).'%':money($r['fee_value']) ?></td><td><?= status_badge($r['status']) ?></td><td><div class="actions"><button class="btn btn-secondary btn-sm" data-modal-open="#fee<?= (int)$r['id'] ?>">Editar</button><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_fee_rule"><input type="hidden" name="return_page" value="fees"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar esta regra de taxa?">Apagar</button></form></div></td></tr><div class="modal" id="fee<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Editar taxa</h2><button class="close-btn" data-modal-close>×</button></div><?php $feeItem=$r;include __DIR__.'/_fee_form.php';?></div></div><?php endforeach;?></tbody></table></div></section>
<div class="modal" id="feeModal"><div class="modal-card"><div class="modal-head"><h2>Nova taxa</h2><button class="close-btn" data-modal-close>×</button></div><?php $feeItem=['id'=>'','scope_type'=>'all','scope_value'=>'','fee_type'=>'fixed','fee_value'=>'0','status'=>'active'];include __DIR__.'/_fee_form.php';?></div></div>
