<?php
$me=current_user();

function subscription_charge_for_row(array $sub): ?array {
    if (empty($sub['user_id'])) return null;
    $q=db()->prepare("SELECT ch.*,iu.name issuer_name FROM charges ch LEFT JOIN users iu ON iu.id=ch.issuer_user_id WHERE ch.subscription_id=? ORDER BY ch.id DESC LIMIT 1");
    $q->execute([(int)$sub['id']]);
    $row=$q->fetch();
    if($row) return $row;
    $q=db()->prepare("SELECT ch.*,iu.name issuer_name FROM charges ch LEFT JOIN users iu ON iu.id=ch.issuer_user_id WHERE ch.user_id=? AND ch.blocks_access=1 AND (lower(ch.description) LIKE '%mensalidade%' OR lower(ch.description) LIKE '%renova%') ORDER BY ch.id DESC LIMIT 1");
    $q->execute([(int)$sub['user_id']]);
    $row=$q->fetch();
    return $row?:null;
}

if(is_admin()){
    // V2.8.50 — o Administrador Sênior pode emitir mensalidade também para contas administrativas.
    // Se o administrador logado possuir cobrança própria, ela aparece no topo com a mesma forma de pagamento/comprovante dos demais usuários.
    $ownAdminChargeQ=db()->prepare("SELECT ch.*,iu.name issuer_name FROM charges ch LEFT JOIN users iu ON iu.id=ch.issuer_user_id WHERE ch.user_id=? AND ch.blocks_access=1 AND (ch.subscription_id IS NOT NULL OR lower(ch.description) LIKE '%mensalidade%' OR lower(ch.description) LIKE '%renova%') ORDER BY ch.id DESC LIMIT 10");
    $ownAdminChargeQ->execute([(int)$me['id']]);$ownAdminCharges=$ownAdminChargeQ->fetchAll();
    $subs=db()->query("SELECT s.*,p.name plan_name,p.duration_days,u.name user_name,u.public_id,u.email user_email,u.status user_status,u.subscription_expires_at,u.blacklisted,c.name company_name FROM subscriptions s JOIN plans p ON p.id=s.plan_id LEFT JOIN users u ON u.id=s.user_id LEFT JOIN companies c ON c.id=s.company_id ORDER BY CASE WHEN s.end_date IS NULL OR s.end_date='' THEN 1 ELSE 0 END, date(s.end_date) ASC, s.id DESC")->fetchAll();
    $plans=db()->query("SELECT * FROM plans WHERE status='active' ORDER BY price")->fetchAll();
    $userRoleFilter=is_role('sub_admin')?"role NOT IN ('super_admin','sub_admin')":"1=1";
    $users=db()->query("SELECT id,name,role,public_id,company_id FROM users WHERE $userRoleFilter ORDER BY name")->fetchAll();
    $companies=db()->query('SELECT id,name,owner_user_id FROM companies ORDER BY name')->fetchAll();
    foreach($companies as &$company){
        $billing=company_billing_user((int)$company['id']);
        $company['billing_user_id']=$billing['id']??0;
        $company['billing_user_name']=$billing['name']??'';
        $company['billing_user_public_id']=$billing['public_id']??'';
    }
    unset($company);
    $monthlyPix=(string)setting('pix_key','');
    $monthlyLink=(string)setting('subscription_payment_link','');
    $quickLinks=db()->query("SELECT pl.id,pl.owner_user_id,pl.title,pl.url,pl.pix_key,pl.plan_id,p.name plan_name,u.name owner_name FROM payment_links pl JOIN users u ON u.id=pl.owner_user_id LEFT JOIN plans p ON p.id=pl.plan_id WHERE pl.status='active' AND COALESCE(pl.url,'')<>'' AND pl.link_kind='subscription_plan' AND u.role='super_admin' ORDER BY p.price,p.name,pl.title,pl.id DESC")->fetchAll();
    $planRequestAdminFilter=is_role('sub_admin')?" AND u.role NOT IN ('super_admin','sub_admin')":'';
    $planRequests=db()->query("SELECT pr.*,u.name user_name,u.public_id,c.name company_name,p.name plan_name,p.price,p.duration_days FROM plan_requests pr JOIN users u ON u.id=pr.user_id JOIN plans p ON p.id=pr.target_plan_id LEFT JOIN companies c ON c.id=pr.company_id WHERE 1=1 $planRequestAdminFilter ORDER BY CASE pr.status WHEN 'pending' THEN 0 ELSE 1 END,pr.id DESC LIMIT 100")->fetchAll();
?>
<?php if(!empty($ownAdminCharges)):?>
<section class="panel admin-own-subscription"><div class="panel-header"><div><h3>💳 Minha mensalidade administrativa</h3><p>Conta administrativa com cobrança emitida pelo Administrador Sênior. O pagamento segue a mesma sistemática dos demais usuários.</p></div></div>
<?php foreach($ownAdminCharges as $ch):?><article class="item-card" style="margin-bottom:12px"><div class="item-body"><div class="service-title-line"><h3><?= e($ch['description']) ?></h3><?= status_badge($ch['status']) ?></div><p>Vencimento: <?= $ch['due_date']?e(date('d/m/Y',strtotime($ch['due_date']))):'não informado' ?> • Valor: <strong><?= money($ch['amount']) ?></strong></p><div class="actions"><?php if($ch['payment_link']):?><a class="btn btn-primary btn-sm" target="_blank" rel="noopener" href="<?= e($ch['payment_link']) ?>">Acessar link de pagamento</a><?php endif;?><?php if($ch['pix_key_snapshot']):?><button type="button" class="btn btn-accent btn-sm" data-copy-text="<?= e($ch['pix_key_snapshot']) ?>">Copiar Pix</button><?php endif;?><?php if(in_array($ch['status'],['pending','overdue','rejected'],true)):?><button class="btn btn-secondary btn-sm" data-modal-open="#adminOwnProof<?= (int)$ch['id'] ?>">Enviar comprovante</button><?php endif;?><?php if($ch['proof']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(media_url($ch['proof'])) ?>">Ver comprovante</a><?php endif;?></div></div></article>
<?php if(in_array($ch['status'],['pending','overdue','rejected'],true)):?><div class="modal" id="adminOwnProof<?= (int)$ch['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Enviar comprovante</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="send_charge_proof"><input type="hidden" name="return_page" value="subscriptions"><input type="hidden" name="id" value="<?= (int)$ch['id'] ?>"><div class="form-group"><label>Imagem ou PDF do pagamento</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 comprovante</button></div></form></div></div><?php endif;?>
<?php endforeach;?></section>
<?php endif;?>
<section class="page-intro"><div><span class="mini-label">ADMINISTRAÇÃO</span><h2>Mensalidades</h2><p>Cobrança, Pix, comprovantes, aprovação, edição, exclusão e renovação de acesso em um só lugar.</p></div><button class="btn btn-primary" data-modal-open="#subscriptionModal">+ Registrar mensalidade</button></section>
<section class="panel"><div class="panel-header"><div><h3>Solicitações de planos</h3><p>Pedidos feitos no cadastro ou pelo próprio usuário para adicionar/trocar de plano.</p></div></div><div class="table-wrap"><table><thead><tr><th>Usuário</th><th>Empresa</th><th>Pedido</th><th>Plano</th><th>Status</th><th>Ação</th></tr></thead><tbody><?php if(!$planRequests):?><tr><td colspan="6"><div class="empty-state"><strong>Nenhuma solicitação</strong></div></td></tr><?php endif;?><?php foreach($planRequests as $pr):?><tr><td><strong><?= e($pr['user_name']) ?></strong><small style="display:block"><?= e($pr['public_id']) ?></small></td><td><?= e($pr['company_name']?:'—') ?></td><td><?= e($pr['request_type']==='initial'?'No cadastro':($pr['request_type']==='change'?'Alteração':'Adição')) ?></td><td><?= e($pr['plan_name']) ?><small style="display:block"><?= money($pr['price']) ?> / <?= (int)$pr['duration_days'] ?> dias</small></td><td><?= status_badge($pr['status']) ?></td><td><?php if($pr['status']==='pending'):?><button class="btn btn-primary btn-sm" data-modal-open="#planRequest<?= (int)$pr['id'] ?>">Analisar</button><?php else:?><span class="muted"><?= $pr['reviewed_at']?e(date('d/m/Y H:i',strtotime($pr['reviewed_at']))):'—' ?></span><?php endif;?></td></tr><?php if($pr['status']==='pending'):?><div class="modal" id="planRequest<?= (int)$pr['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Analisar solicitação</h2><button class="close-btn" data-modal-close>×</button></div><div class="notice"><strong><?= e($pr['user_name']) ?></strong> solicitou <strong><?= e($pr['plan_name']) ?></strong> — <?= money($pr['price']) ?>.</div><form method="post" action="actions.php" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="review_plan_request"><input type="hidden" name="return_page" value="subscriptions"><input type="hidden" name="id" value="<?= (int)$pr['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-primary" name="decision" value="approved">Aprovar e gerar mensalidade</button></div></form></div></div><?php endif;?><?php endforeach;?></tbody></table></div></section>
<section class="panel"><div class="panel-header"><div><h3>Pagamento das mensalidades por plano</h3><p>Cada plano pode ter um ou vários links próprios. Ao criar novos planos, eles aparecem automaticamente aqui.</p></div><?php if(is_super_admin()):?><button class="btn btn-primary btn-sm" data-modal-open="#subscriptionPaymentLinkModal">+ Link para um plano</button><?php endif;?></div><div class="cards-list"><?php foreach($plans as $plan):$links=array_values(array_filter($quickLinks,static fn($l)=>(int)$l['plan_id']===(int)$plan['id']));?><article class="item-card"><div class="item-body"><h3><?= e($plan['name']) ?> — <?= money($plan['price']) ?></h3><?php if(!$links):?><p>Nenhum link específico. <?= $monthlyLink?'Será usado o link padrão como fallback.':'Cadastre um link para este plano.' ?></p><?php endif;?><?php foreach($links as $l):?><div class="plan-payment-link-row"><strong><?= e($l['title']) ?></strong><small style="word-break:break-all"><?= e($l['url']) ?></small><div class="actions"><a class="btn btn-primary btn-sm" target="_blank" rel="noopener" href="<?= e($l['url']) ?>">Acessar</a><?php if(is_super_admin()):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_payment_link"><input type="hidden" name="return_page" value="subscriptions"><input type="hidden" name="id" value="<?= (int)$l['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar este link do plano?">Apagar</button></form><?php endif;?></div></div><?php endforeach;?></div></article><?php endforeach;?></div></section>
<?php if(is_super_admin()):?><div class="modal" id="subscriptionPaymentLinkModal"><div class="modal-card"><div class="modal-head"><h2>Novo link de plano</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="subscriptions"><div class="form-grid"><div class="form-group full"><label>Plano</label><select name="plan_id" required><?php foreach($plans as $p):?><option value="<?= (int)$p['id'] ?>"><?= e($p['name']) ?> — <?= money($p['price']) ?></option><?php endforeach;?></select></div><div class="form-group full"><label>Nome do link</label><input class="input" name="title" placeholder="Ex.: Mercado Pago - Essencial" required></div><div class="form-group full"><label>URL de pagamento</label><input class="input" type="url" name="url" placeholder="https://..." required></div><div class="form-group full"><label>Pix vinculado (opcional)</label><input class="input" name="pix_key" value="<?= e($monthlyPix) ?>"></div></div><div class="form-actions"><button class="btn btn-primary">Salvar link do plano</button></div></form></div></div><?php endif;?>
<section class="panel"><div class="panel-header"><div><h3>Mensalidades registradas</h3><p>Você pode cobrar um usuário diretamente ou escolher apenas a empresa. Ao selecionar a empresa, o responsável é preenchido automaticamente.</p></div></div><div class="table-wrap"><table><thead><tr><th>Assinante</th><th>Plano</th><th>Período</th><th>Valor</th><th>Cobrança</th><th>Comprovante</th><th>Acesso</th><th>Ações</th></tr></thead><tbody>
<?php if(!$subs):?><tr><td colspan="8"><div class="empty-state"><strong>Nenhuma mensalidade</strong></div></td></tr><?php endif;?>
<?php foreach($subs as $s):$ch=subscription_charge_for_row($s);$uid=(int)($s['user_id']??0);?>
<tr>
<td><strong><?= e($s['company_name']?:$s['user_name']?:'Não informado') ?></strong><?php if($s['company_name']&&$s['user_name']):?><small style="display:block">Responsável: <?= e($s['user_name']) ?></small><?php endif;?><?php if($s['public_id']):?><small style="display:block"><?= e($s['public_id']) ?></small><?php endif;?></td>
<td><?= e($s['plan_name']) ?></td>
<td><?= e(date('d/m/Y',strtotime($s['start_date'])).' até '.date('d/m/Y',strtotime($s['end_date']))) ?><?php if(!empty($s['recurring_enabled'])):?><small style="display:block;margin-top:5px">🔁 A cada 30 dias<?php if(!empty($s['next_billing_date'])):?> • próxima <?= e(date('d/m/Y',strtotime($s['next_billing_date']))) ?><?php endif;?></small><?php endif;?></td>
<td><?= money($s['amount']) ?></td>
<td><?php if($ch):?><?= status_badge($ch['status']) ?><div class="actions" style="margin-top:8px;flex-wrap:wrap"><?php if($ch['payment_link']):?><a class="btn btn-primary btn-sm" target="_blank" rel="noopener" href="<?= e($ch['payment_link']) ?>">Link pagamento</a><?php endif;?><?php if($ch['pix_key_snapshot']):?><button type="button" class="btn btn-secondary btn-sm" data-copy-text="<?= e($ch['pix_key_snapshot']) ?>">Copiar Pix</button><?php endif;?></div><?php else:?><span class="muted">Sem cobrança vinculada</span><?php endif;?></td>
<td><?php if($ch&&$ch['proof']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(media_url($ch['proof'])) ?>">Acessar Comprovante</a><?php else:?><span class="muted">—</span><?php endif;?></td>
<td><?php if($uid):?><?= !empty($s['blacklisted'])?'<span class="badge badge-danger">Lista negra</span>':status_badge($s['user_status']) ?><small style="display:block;margin-top:6px">Até <?= $s['subscription_expires_at']?e(date('d/m/Y',strtotime($s['subscription_expires_at']))):'—' ?></small><?php else:?>—<?php endif;?></td>
<td><div class="actions" style="flex-wrap:wrap">
<button class="btn btn-secondary btn-sm" data-modal-open="#editSub<?= (int)$s['id'] ?>">Editar</button>
<?php if($uid):?><button class="btn btn-primary btn-sm" data-modal-open="#renewSub<?= (int)$s['id'] ?>">Renovar usuário</button><form method="post" action="actions.php" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="release_subscription_access"><input type="hidden" name="return_page" value="subscriptions"><input type="hidden" name="user_id" value="<?= $uid ?>"><input type="hidden" name="days" value="7"><button class="btn btn-secondary btn-sm" data-confirm="Liberar acesso temporário por 7 dias?">Liberar 7 dias</button></form><?php endif;?>
<?php if($ch):?><button class="btn btn-secondary btn-sm" data-modal-open="#reviewSubCharge<?= (int)$ch['id'] ?>">Analisar pagamento</button><?php endif;?>
<form method="post" action="actions.php" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="delete_subscription"><input type="hidden" name="return_page" value="subscriptions"><input type="hidden" name="id" value="<?= (int)$s['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar esta mensalidade? A cobrança vinculada será removida, mas lançamentos já contabilizados no Financeiro serão preservados.">Apagar</button></form>
</div></td>
</tr>
<?php endforeach;?></tbody></table></div></section>

<div class="modal" id="subscriptionModal"><div class="modal-card"><div class="modal-head"><h2>Registrar mensalidade</h2><button class="close-btn" data-modal-close>×</button></div>
<form method="post" action="actions.php" class="subscription-form"><?= csrf_field() ?><input type="hidden" name="action" value="save_subscription"><input type="hidden" name="return_page" value="subscriptions"><input type="hidden" name="id" value="0">
<div class="form-grid">
<div class="form-group"><label>Empresa (opcional)</label><select name="company_id" data-sub-company><option value="">Nenhuma — cobrar usuário</option><?php foreach($companies as $x):?><option value="<?= (int)$x['id'] ?>" data-billing-user-id="<?= (int)$x['billing_user_id'] ?>" data-billing-user-name="<?= e($x['billing_user_name']) ?>"><?= e($x['name']) ?></option><?php endforeach;?></select><small data-billing-preview>Ao escolher uma empresa, o responsável será selecionado automaticamente.</small></div>
<div class="form-group"><label>Usuário responsável</label><select name="user_id" data-sub-user><option value="">Selecione</option><?php foreach($users as $x):?><option value="<?= (int)$x['id'] ?>"><?= e($x['name'].' — '.role_label($x['role']).' — '.$x['public_id']) ?></option><?php endforeach;?></select></div>
<div class="form-group"><label>Plano</label><select name="plan_id" required data-sub-plan><?php foreach($plans as $x):?><option value="<?= (int)$x['id'] ?>" data-price="<?= e($x['price']) ?>"><?= e($x['name']).' — '.money($x['price']) ?></option><?php endforeach;?></select></div>
<div class="form-group"><label>Valor</label><input class="input" name="amount" data-sub-amount></div>
<div class="form-group"><label>Início do plano</label><input class="input" type="date" name="start_date" value="<?= today() ?>"></div>
<div class="form-group"><label>Data de pagamento / 1º vencimento</label><input class="input" type="date" name="payment_date" value="<?= today() ?>" required><small>Esta será a data da primeira cobrança.</small></div>
<?php if(is_super_admin()):?><div class="form-group full"><label>Link de pagamento deste plano</label><select name="payment_link_id" data-sub-payment-link><option value="">Usar link padrão da plataforma<?= $monthlyLink?' — '.e($monthlyLink):'' ?></option><?php foreach($quickLinks as $l):?><option value="<?= (int)$l['id'] ?>" data-plan-id="<?= (int)$l['plan_id'] ?>" data-url="<?= e($l['url']??'') ?>"><?= e($l['title'].($l['owner_name']?' — '.$l['owner_name']:'')) ?></option><?php endforeach;?></select><small data-payment-link-preview><?= $monthlyLink?'Padrão: '.e($monthlyLink):'Nenhum link padrão configurado. Cadastre links rápidos em Cobranças.' ?></small><div class="actions" style="margin-top:8px"><a class="btn btn-secondary btn-sm" href="dashboard.php?page=charges">Gerenciar links rápidos</a></div></div><?php else:?><div class="form-group full"><div class="notice">🔒 O Administrador pode registrar/renovar a mensalidade, mas não pode enviar links de pagamento.</div></div><?php endif;?>
<div class="form-group"><label>Método</label><select name="payment_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>Status</label><select name="status"><option value="pending">Pendente — enviar cobrança</option><option value="overdue">Vencida — bloquear até comprovante</option><option value="active">Ativa</option><option value="cancelled">Cancelada</option></select></div>
<div class="form-group full"><label class="check-line"><input type="checkbox" name="recurring_enabled" value="1" checked> 🔁 Gerar cobrança recorrente automaticamente a cada 30 dias</label><small>O usuário receberá uma nova cobrança mensal automaticamente, sempre com o link de pagamento escolhido.</small></div>
<div class="form-group"><label>Fim do plano (opcional)</label><input class="input" type="date" name="end_date"></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" type="submit">Registrar</button></div></form></div></div>

<?php foreach($subs as $s): $uid=(int)($s['user_id']??0); $ch=subscription_charge_for_row($s); $paymentDate=(string)($s['billing_anchor_date']??''); if($paymentDate==='')$paymentDate=(string)($ch['due_date']??$s['start_date']); ?>
<div class="modal" id="editSub<?= (int)$s['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Editar mensalidade</h2><button class="close-btn" data-modal-close>×</button></div>
<form method="post" action="actions.php" class="subscription-form"><?= csrf_field() ?><input type="hidden" name="action" value="save_subscription"><input type="hidden" name="return_page" value="subscriptions"><input type="hidden" name="id" value="<?= (int)$s['id'] ?>">
<div class="form-grid">
<div class="form-group"><label>Empresa (opcional)</label><select name="company_id" data-sub-company><option value="">Nenhuma — cobrar usuário</option><?php foreach($companies as $x):?><option value="<?= (int)$x['id'] ?>" data-billing-user-id="<?= (int)$x['billing_user_id'] ?>" data-billing-user-name="<?= e($x['billing_user_name']) ?>"<?= selected($s['company_id'],$x['id']) ?>><?= e($x['name']) ?></option><?php endforeach;?></select><small data-billing-preview></small></div>
<div class="form-group"><label>Usuário responsável</label><select name="user_id" data-sub-user><option value="">Selecione</option><?php foreach($users as $x):?><option value="<?= (int)$x['id'] ?>"<?= selected($s['user_id'],$x['id']) ?>><?= e($x['name'].' — '.role_label($x['role']).' — '.$x['public_id']) ?></option><?php endforeach;?></select></div>
<div class="form-group"><label>Plano</label><select name="plan_id" required data-sub-plan><?php foreach($plans as $x):?><option value="<?= (int)$x['id'] ?>" data-price="<?= e($x['price']) ?>"<?= selected($s['plan_id'],$x['id']) ?>><?= e($x['name']).' — '.money($x['price']) ?></option><?php endforeach;?></select></div>
<div class="form-group"><label>Valor</label><input class="input" name="amount" data-sub-amount value="<?= e(number_format((float)$s['amount'],2,',','')) ?>"></div>
<div class="form-group"><label>Início do plano</label><input class="input" type="date" name="start_date" value="<?= e($s['start_date']) ?>"></div>
<div class="form-group"><label>Data de pagamento / vencimento</label><input class="input" type="date" name="payment_date" value="<?= e($paymentDate) ?>" required><?php if(!empty($s['next_billing_date'])):?><small>Próxima cobrança programada: <?= e(date('d/m/Y',strtotime($s['next_billing_date']))) ?></small><?php endif;?></div>
<?php if(is_super_admin()):?><div class="form-group full"><label>Link de pagamento deste plano</label><select name="payment_link_id" data-sub-payment-link><option value="">Usar link padrão da plataforma<?= $monthlyLink?' — '.e($monthlyLink):'' ?></option><?php foreach($quickLinks as $l):?><option value="<?= (int)$l['id'] ?>" data-plan-id="<?= (int)$l['plan_id'] ?>" data-url="<?= e($l['url']??'') ?>"<?= selected($s['payment_link_id']??0,$l['id']) ?>><?= e($l['title'].($l['owner_name']?' — '.$l['owner_name']:'')) ?></option><?php endforeach;?></select><small data-payment-link-preview><?= !empty($s['payment_link'])?'Atual: '.e($s['payment_link']):($monthlyLink?'Padrão: '.e($monthlyLink):'Nenhum link configurado.') ?></small><div class="actions" style="margin-top:8px"><a class="btn btn-secondary btn-sm" href="dashboard.php?page=charges">Gerenciar links rápidos</a></div></div><?php else:?><div class="form-group full"><div class="notice">🔒 O Administrador pode registrar/renovar a mensalidade, mas não pode enviar links de pagamento.</div></div><?php endif;?>
<div class="form-group"><label>Método</label><select name="payment_method"><option value="pix"<?= selected($s['payment_method'],'pix') ?>>Pix</option><option value="card"<?= selected($s['payment_method'],'card') ?>>Cartão</option><option value="cash"<?= selected($s['payment_method'],'cash') ?>>Dinheiro</option><option value="boleto"<?= selected($s['payment_method'],'boleto') ?>>Boleto</option></select></div>
<div class="form-group"><label>Status</label><select name="status"><option value="pending"<?= selected($s['status'],'pending') ?>>Pendente — enviar cobrança</option><option value="overdue"<?= selected($s['status'],'overdue') ?>>Vencida — bloquear até comprovante</option><option value="proof_sent"<?= selected($s['status'],'proof_sent') ?>>Comprovante enviado</option><option value="active"<?= selected($s['status'],'active') ?>>Ativa</option><option value="cancelled"<?= selected($s['status'],'cancelled') ?>>Cancelada</option></select></div>
<div class="form-group full"><label class="check-line"><input type="checkbox" name="recurring_enabled" value="1"<?= !empty($s['recurring_enabled'])?' checked':'' ?>> 🔁 Cobrança recorrente automática a cada 30 dias</label><small>As próximas cobranças usarão automaticamente este mesmo link de pagamento.</small></div>
<div class="form-group"><label>Fim do plano</label><input class="input" type="date" name="end_date" value="<?= e($s['end_date']) ?>"></div>
<div class="form-group full"><label>Observações</label><textarea name="notes"><?= e($s['notes']??'') ?></textarea></div>
</div><div class="form-actions"><button class="btn btn-primary">Salvar alterações</button></div></form></div></div>
<?php if($uid):?><div class="modal" id="renewSub<?= (int)$s['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Renovar usuário</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="renew_user"><input type="hidden" name="return_page" value="subscriptions"><input type="hidden" name="id" value="<?= $uid ?>"><div class="form-group"><label>Quantidade de dias</label><input class="input" type="number" name="days" min="1" max="3650" value="30"></div><p class="notice">A renovação manual libera a conta e encerra cobranças obrigatórias pendentes sem registrar pagamento.</p><div class="form-actions"><button class="btn btn-primary">Renovar acesso</button></div></form></div></div><?php endif;?>
<?php if($ch):?><div class="modal" id="reviewSubCharge<?= (int)$ch['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Analisar mensalidade</h2><button class="close-btn" data-modal-close>×</button></div><div class="stack-sm"><strong><?= money($ch['amount']) ?></strong><?php if($ch['proof']):?><a class="btn btn-secondary" target="_blank" href="<?= e(media_url($ch['proof'])) ?>">Acessar comprovante enviado</a><?php endif;?></div><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="subscriptions"><input type="hidden" name="id" value="<?= (int)$ch['id'] ?>"><div class="form-group"><label>Decisão</label><select name="status"><option value="paid">Aprovar pagamento e renovar 30 dias</option><option value="rejected">Recusar comprovante</option><option value="pending">Voltar para pendente</option><option value="overdue">Marcar vencida</option></select></div><div class="form-group"><label>Observação</label><textarea name="admin_notes"><?= e($ch['admin_notes']??'') ?></textarea></div><label class="check-line"><input type="checkbox" name="blacklist_user" value="1"> Se recusado por irregularidade, bloquear e colocar o usuário na lista negra</label><div class="form-actions"><button class="btn btn-primary">Confirmar decisão</button></div></form></div></div><?php endif;?>
<?php endforeach;?>
<script>
(function(){
  document.querySelectorAll('.subscription-form').forEach(function(form){
    var company=form.querySelector('[data-sub-company]');
    var user=form.querySelector('[data-sub-user]');
    var preview=form.querySelector('[data-billing-preview]');
    var plan=form.querySelector('[data-sub-plan]');
    var amount=form.querySelector('[data-sub-amount]');
    var paymentLink=form.querySelector('[data-sub-payment-link]');
    var paymentPreview=form.querySelector('[data-payment-link-preview]');
    function syncCompany(){
      if(!company||!user)return;
      var opt=company.options[company.selectedIndex];
      var uid=opt&&opt.dataset?opt.dataset.billingUserId:'';
      var uname=opt&&opt.dataset?opt.dataset.billingUserName:'';
      if(company.value){
        if(uid&&uid!=='0') user.value=uid;
        user.disabled=true;
        if(preview) preview.textContent=uid&&uid!=='0' ? 'Responsável automático: '+uname : 'Esta empresa ainda não possui usuário responsável vinculado.';
      }else{
        user.disabled=false;
        if(preview) preview.textContent='Selecione diretamente o usuário que será cobrado.';
      }
    }
    if(company){company.addEventListener('change',syncCompany);syncCompany();}
    function syncPlanLinks(){if(!plan||!paymentLink)return;var pid=plan.value;Array.from(paymentLink.options).forEach(function(o){if(!o.value)return;o.hidden=!!(o.dataset.planId&&o.dataset.planId!==pid);});var selected=paymentLink.options[paymentLink.selectedIndex];if(selected&&selected.hidden)paymentLink.value='';} if(plan&&amount){plan.addEventListener('change',function(){if(!amount.value.trim()){var o=plan.options[plan.selectedIndex];amount.value=o&&o.dataset?String(o.dataset.price||'').replace('.',','):'';}syncPlanLinks();});}syncPlanLinks();
    if(paymentLink&&paymentPreview){paymentLink.addEventListener('change',function(){var o=paymentLink.options[paymentLink.selectedIndex];if(o&&o.value){paymentPreview.textContent=o.dataset.url?'Selecionado: '+o.dataset.url:'Link rápido selecionado.';}});}
    form.addEventListener('submit',function(){if(user)user.disabled=false;});
  });
})();
</script>
<?php
}else{
    ensure_subscription_charge_for_user($me);
    $q=db()->prepare("SELECT s.*,p.name plan_name,p.duration_days FROM subscriptions s JOIN plans p ON p.id=s.plan_id WHERE s.user_id=? ORDER BY s.id DESC");$q->execute([(int)$me['id']]);$subs=$q->fetchAll();
    $q=db()->prepare("SELECT ch.*,iu.name issuer_name FROM charges ch LEFT JOIN users iu ON iu.id=ch.issuer_user_id WHERE ch.user_id=? AND ch.blocks_access=1 AND (ch.subscription_id IS NOT NULL OR lower(ch.description) LIKE '%mensalidade%' OR lower(ch.description) LIKE '%renova%') ORDER BY ch.id DESC");$q->execute([(int)$me['id']]);$monthlyCharges=$q->fetchAll();
    $restricted=account_restricted($me);
    $availablePlans=db()->query("SELECT id,name,price,duration_days,features_json FROM plans WHERE status='active' ORDER BY price,name")->fetchAll();
    $rq=db()->prepare("SELECT pr.*,p.name plan_name,p.price FROM plan_requests pr JOIN plans p ON p.id=pr.target_plan_id WHERE pr.user_id=? ORDER BY pr.id DESC LIMIT 20");$rq->execute([(int)$me['id']]);$myPlanRequests=$rq->fetchAll();
?>
<section class="page-intro"><div><span class="mini-label"><?= $restricted?'PAGAMENTO NECESSÁRIO':'MINHA ASSINATURA' ?></span><h2>Mensalidade</h2><p>Consulte vencimento, Pix/link de pagamento e envie seu comprovante diretamente por aqui.</p></div></section>
<?php if($restricted):?><div class="alert alert-error"><strong>Acesso aguardando regularização.</strong><br>Enquanto a mensalidade não for regularizada, esta é a área disponível para pagamento. Envie o comprovante abaixo; após o envio, o acesso é liberado enquanto o administrador analisa.</div><?php endif;?>
<?php foreach($monthlyCharges as $ch):?>
<section class="panel"><div class="panel-header"><div><h3><?= e($ch['description']) ?></h3><p>Vencimento: <?= $ch['due_date']?e(date('d/m/Y',strtotime($ch['due_date']))):'não informado' ?></p></div><?= status_badge($ch['status']) ?></div>
<div class="metric-grid compact"><div class="metric-card"><span>Valor</span><strong><?= money($ch['amount']) ?></strong></div><div class="metric-card"><span>Situação</span><strong><?= e(status_label($ch['status'])) ?></strong></div></div>
<div class="panel" style="margin-top:14px"><h4>Formas de pagamento</h4><div class="actions" style="margin-top:12px;flex-wrap:wrap"><?php if($ch['payment_link']):?><a class="btn btn-primary" target="_blank" rel="noopener" href="<?= e($ch['payment_link']) ?>">Acessar link de pagamento</a><?php endif;?><?php if($ch['pix_key_snapshot']):?><button type="button" class="btn btn-accent" data-copy-text="<?= e($ch['pix_key_snapshot']) ?>">Copiar Pix</button><span class="notice" style="word-break:break-all">Pix: <?= e($ch['pix_key_snapshot']) ?></span><?php endif;?><?php if(!$ch['payment_link']&&!$ch['pix_key_snapshot']):?><span class="notice">O administrador ainda não configurou link ou Pix para esta mensalidade.</span><?php endif;?></div></div>
<?php if($ch['proof']):?><div class="notice" style="margin-top:14px"><strong>Comprovante enviado.</strong> <a target="_blank" href="<?= e(media_url($ch['proof'])) ?>">Acessar arquivo</a><?php if($ch['status']==='proof_sent'):?><br>Seu acesso está liberado enquanto o administrador faz a análise.<?php endif;?></div><?php endif;?>
<div class="actions" style="margin-top:16px"><?php if(in_array($ch['status'],['pending','overdue','rejected'],true)):?><button class="btn btn-primary" data-modal-open="#subProof<?= (int)$ch['id'] ?>"><?= $ch['proof']?'Enviar novo comprovante':'Enviar comprovante' ?></button><?php elseif($ch['status']==='paid'&&$ch['receipt_path']):?><a class="btn btn-secondary" target="_blank" href="<?= e(generated_receipt_url((string)$ch['receipt_path'],'charge',(int)$ch['id'])) ?>">Acessar Recibo</a><?php endif;?></div></section>
<div class="modal" id="subProof<?= (int)$ch['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Enviar comprovante</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="send_charge_proof"><input type="hidden" name="return_page" value="subscriptions"><input type="hidden" name="id" value="<?= (int)$ch['id'] ?>"><div class="form-group"><label>Imagem ou PDF do pagamento</label><input class="input" type="file" name="proof_file" accept="image/jpeg,image/png,image/webp,application/pdf" required></div><div class="notice">Assim que enviar, o sistema libera seu acesso enquanto o administrador confere o pagamento. Se houver irregularidade, o acesso poderá ser bloqueado novamente.</div><div class="form-actions"><button class="btn btn-primary">Enviar comprovante</button></div></form></div></div>
<?php endforeach;?>
<section class="panel"><div class="panel-header"><div><h3>Solicitar plano</h3><p>Peça a adição ou troca de plano. O administrador precisa aprovar antes de gerar a mensalidade.</p></div><button class="btn btn-primary" data-modal-open="#requestPlanModal">Solicitar plano</button></div><?php if($myPlanRequests):?><div class="table-wrap"><table><thead><tr><th>Plano</th><th>Tipo</th><th>Status</th><th>Data</th></tr></thead><tbody><?php foreach($myPlanRequests as $pr):?><tr><td><?= e($pr['plan_name']) ?> • <?= money($pr['price']) ?></td><td><?= e($pr['request_type']==='initial'?'Cadastro':($pr['request_type']==='change'?'Alteração':'Adição')) ?></td><td><?= status_badge($pr['status']) ?></td><td><?= e(date('d/m/Y H:i',strtotime($pr['created_at']))) ?></td></tr><?php endforeach;?></tbody></table></div><?php endif;?></section>
<div class="modal" id="requestPlanModal"><div class="modal-card"><div class="modal-head"><h2>Solicitar plano</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="submit_plan_request"><input type="hidden" name="return_page" value="subscriptions"><div class="form-group"><label>Plano desejado</label><select name="plan_id" required><?php foreach($availablePlans as $plan):?><option value="<?= (int)$plan['id'] ?>"><?= e($plan['name']) ?> — <?= money($plan['price']) ?> / <?= (int)$plan['duration_days'] ?> dias</option><?php endforeach;?></select></div><div class="form-group"><label>Observação (opcional)</label><textarea name="notes" placeholder="Ex.: Quero trocar para este plano na próxima renovação."></textarea></div><div class="form-actions"><button class="btn btn-primary">Enviar solicitação</button></div></form></div></div>
<section class="panel"><div class="panel-header"><div><h3>Histórico de mensalidades</h3></div></div><div class="table-wrap"><table><thead><tr><th>Plano</th><th>Período</th><th>Valor</th><th>Status</th></tr></thead><tbody><?php if(!$subs):?><tr><td colspan="4"><div class="empty-state"><strong>Nenhuma mensalidade registrada</strong></div></td></tr><?php endif;foreach($subs as $s):?><tr><td><?= e($s['plan_name']) ?><?php if(!empty($s['recurring_enabled'])):?><small style="display:block">🔁 cobrança automática a cada 30 dias</small><?php endif;?></td><td><?= e(date('d/m/Y',strtotime($s['start_date'])).' até '.date('d/m/Y',strtotime($s['end_date']))) ?><?php if(!empty($s['next_billing_date'])):?><small style="display:block">Próxima: <?= e(date('d/m/Y',strtotime($s['next_billing_date']))) ?></small><?php endif;?></td><td><?= money($s['amount']) ?></td><td><?= status_badge($s['status']) ?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php } ?>
