<?php
declare(strict_types=1);
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;
use App\Core\FinanceEngine;
use App\Core\WalletService;

Auth::requireRole(['affiliate','customer','admin','staff'], 'public/login.php');
$panelType = 'affiliate';
$title = $panelTitle ?? 'Marketing Member Module';
$pageTitle = $title . ' | Affiliate Panel';
$slug = basename($_SERVER['SCRIPT_NAME'], '.php');
$uid = (int)Auth::id();
$errors = [];

$member = Database::safeFetchOne(
    'SELECT am.*,u.name,u.email,u.phone FROM affiliate_members am LEFT JOIN users u ON u.id=am.user_id WHERE am.user_id=? LIMIT 1',
    [$uid]
);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) {
        $errors[] = 'Invalid security token.';
    } else {
        try {
            $action = (string)($_POST['_action'] ?? '');
            if (!$member && in_array($action, ['save_landing','save_social'], true)) {
                throw new RuntimeException('Activate an E-Dealer plan before editing affiliate content.');
            }
            if ($action === 'save_landing' && $member) {
                Database::execute(
                    'UPDATE affiliate_members SET landing_title=?,landing_bio=?,landing_banner=?,landing_image=?,contact_info=?,updated_at=NOW() WHERE id=?',
                    [
                        trim((string)($_POST['landing_title'] ?? '')),
                        trim((string)($_POST['landing_bio'] ?? '')),
                        trim((string)($_POST['landing_banner'] ?? '')),
                        trim((string)($_POST['landing_image'] ?? '')),
                        trim((string)($_POST['contact_info'] ?? '')),
                        $member['id'],
                    ]
                );
            } elseif ($action === 'save_social' && $member) {
                $social = [
                    'facebook' => trim((string)($_POST['facebook'] ?? '')),
                    'whatsapp' => trim((string)($_POST['whatsapp'] ?? '')),
                    'instagram' => trim((string)($_POST['instagram'] ?? '')),
                    'youtube' => trim((string)($_POST['youtube'] ?? '')),
                ];
                Database::execute('UPDATE affiliate_members SET social_json=?,updated_at=NOW() WHERE id=?', [json_encode($social, JSON_UNESCAPED_SLASHES), $member['id']]);
            }
            set_flash('success', 'Saved successfully.');
            redirect('member/' . basename($_SERVER['SCRIPT_NAME']));
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

$member = Database::safeFetchOne(
    'SELECT am.*,u.name,u.email,u.phone FROM affiliate_members am LEFT JOIN users u ON u.id=am.user_id WHERE am.user_id=? LIMIT 1',
    [$uid]
);
$memberId = (int)($member['id'] ?? 0);
$rankCode = (string)($member['rank_code'] ?? 'IBO');
$totalPsa = (float)($member['total_psa'] ?? 0);
$commissionBalance = WalletService::balance($uid, 'commission');
$teamCount = $memberId ? db_count('affiliate_tree', 'ancestor_id=? AND level_no>0', [$memberId]) : 0;
$currentPlan = $memberId ? Database::safeFetchOne(
    'SELECT amp.*,ap.name plan_name,ap.code plan_code,ap.product_limit,ap.price,ap.affiliate_percent FROM affiliate_member_plans amp JOIN affiliate_plans ap ON ap.id=amp.plan_id WHERE amp.affiliate_member_id=? AND amp.status="active" AND (amp.ends_at IS NULL OR amp.ends_at>=CURDATE()) ORDER BY amp.id DESC LIMIT 1',
    [$memberId]
) : null;
$selectedCount = $memberId ? db_count('affiliate_products', 'affiliate_member_id=?', [$memberId]) : 0;
$psa = FinanceEngine::calculatePsa(500, 5000);

require_once ROOT_PATH . '/app/Layouts/panel_header.php';
?>
<div class="d-flex justify-content-between align-items-start flex-wrap gap-3 mb-3">
  <div><h1 class="h3 mb-1"><?= e($title) ?></h1><p class="text-muted mb-0"><?= e($panelDescription ?? 'Affiliate marketing member workspace.') ?></p></div>
  <a class="btn btn-primary" href="<?= url('member/products.php') ?>">Select Products</a>
</div>
<?php if ($m=flash('success')): ?><div class="alert alert-success"><?= e($m) ?></div><?php endif; ?>
<?php foreach ($errors as $er): ?><div class="alert alert-danger"><?= e($er) ?></div><?php endforeach; ?>
<?php if (!$member): ?><div class="alert alert-info">Your affiliate profile is not active yet. Choose a plan to create and activate it.</div><?php endif; ?>
<div class="row g-3 mb-4">
  <div class="col-md-3"><div class="stat-tile"><div class="small text-muted">Rank</div><strong><?= e($rankCode) ?></strong></div></div>
  <div class="col-md-3"><div class="stat-tile"><div class="small text-muted">Total PSA</div><strong><?= money($totalPsa) ?></strong></div></div>
  <div class="col-md-3"><div class="stat-tile"><div class="small text-muted">Commission Wallet</div><strong><?= money($commissionBalance) ?></strong></div></div>
  <div class="col-md-3"><div class="stat-tile"><div class="small text-muted">Team</div><strong><?= number_format($teamCount) ?> Members</strong></div></div>
</div>

<?php if ($slug === 'index'): $recent=Database::safeFetchAll('SELECT * FROM affiliate_statements WHERE affiliate_member_id=? ORDER BY id DESC LIMIT 8',[$memberId]); ?>
<div class="row g-4"><div class="col-lg-8"><div class="card module-card"><div class="card-header bg-white"><strong>Recent statements</strong></div><div class="table-responsive"><table class="table mb-0"><thead><tr><th>Period</th><th>Sales</th><th>PSA</th><th>Royalty</th><th>Status</th></tr></thead><tbody><?php if(!$recent): ?><?= table_empty(5,'No affiliate statement has been generated yet.') ?><?php endif; ?><?php foreach($recent as $r): ?><tr><td><?= e(($r['period_start']??'').' – '.($r['period_end']??'')) ?></td><td><?= money($r['total_sales']??0) ?></td><td><?= money($r['total_psa']??0) ?></td><td><?= money($r['total_royalty']??0) ?></td><td><?= badge($r['status']??'pending') ?></td></tr><?php endforeach; ?></tbody></table></div></div></div><div class="col-lg-4"><div class="card module-card"><div class="card-body"><h5>Membership</h5><?php if($currentPlan): ?><p class="mb-1"><strong><?= e($currentPlan['plan_name']) ?></strong></p><p class="small text-muted">Valid through <?= e($currentPlan['ends_at']??'') ?></p><p>Products: <?= $selectedCount ?> / <?= (int)$currentPlan['product_limit'] ?></p><div class="progress mb-3"><div class="progress-bar" style="width:<?= min(100,round($selectedCount/max(1,(int)$currentPlan['product_limit'])*100)) ?>%"></div></div><?php else: ?><p class="text-muted">No active plan.</p><?php endif; ?><div class="d-grid gap-2"><a class="btn btn-primary" href="<?= url('member/plans.php') ?>">View Plans</a><a class="btn btn-outline-primary" href="<?= url('member/landing.php') ?>">Edit Landing Page</a></div></div></div></div></div>

<?php elseif ($slug === 'plans'): $plans=Database::safeFetchAll('SELECT * FROM affiliate_plans WHERE status="active" ORDER BY price'); ?>
<div class="row g-4"><?php foreach($plans as $p): ?><div class="col-md-4"><div class="card module-card h-100"><div class="card-body d-flex flex-column"><h4><?= e($p['name']) ?></h4><h3><?= money($p['price']) ?></h3><p class="text-muted">Up to <?= (int)$p['product_limit'] ?> products · Affiliate share <?= e($p['affiliate_percent']) ?>%</p><ul><li>Leader <?= e($p['leader_percent']) ?>%</li><li>Mentor <?= e($p['mentor_percent']) ?>%</li><li>CM <?= e($p['cm_percent']) ?>%</li></ul><button class="btn <?= ($currentPlan&&$currentPlan['plan_id']==$p['id'])?'btn-success':'btn-primary' ?> mt-auto plan-buy" data-id="<?= (int)$p['id'] ?>" <?= ($currentPlan&&$currentPlan['plan_id']==$p['id'])?'disabled':'' ?>><?= ($currentPlan&&$currentPlan['plan_id']==$p['id'])?'Active':'Activate from Purchase Wallet' ?></button></div></div></div><?php endforeach; ?></div><div id="planMsg" class="mt-3"></div>
<script>document.querySelectorAll('.plan-buy').forEach(b=>b.addEventListener('click',()=>{b.disabled=true;fetch('<?= url('api/affiliate-plan.php') ?>',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({csrf_token:'<?= e(csrf_token()) ?>',plan_id:b.dataset.id})}).then(r=>r.json()).then(x=>{document.getElementById('planMsg').innerHTML='<div class="alert alert-'+(x.ok?'success':'danger')+'">'+x.message+'</div>';if(x.ok)location.reload();else b.disabled=false;});}));</script>

<?php elseif ($slug === 'products'): $products=Database::safeFetchAll('SELECT p.*,c.name category_name,CASE WHEN ap.id IS NULL THEN 0 ELSE 1 END selected FROM products p LEFT JOIN categories c ON c.id=p.category_id LEFT JOIN affiliate_products ap ON ap.product_id=p.id AND ap.affiliate_member_id=? WHERE p.status="published" ORDER BY p.id DESC LIMIT 200',[$memberId]);$limit=(int)($currentPlan['product_limit']??0); ?>
<div class="card module-card"><div class="card-header bg-white d-flex justify-content-between"><strong>Affiliate shop products</strong><span><?= $selectedCount ?> / <?= $limit ?: 0 ?> selected</span></div><div class="table-responsive"><table class="table mb-0"><thead><tr><th>Product</th><th>Category</th><th>Price</th><th>PSA estimate</th><th></th></tr></thead><tbody><?php if(!$products): ?><?= table_empty(5,'No published products.') ?><?php endif; ?><?php foreach($products as $p): $estimate=FinanceEngine::calculatePsa((float)$p['purchase_price'],(float)($p['sale_price']?:$p['regular_price'])); ?><tr><td><strong><?= e($p['name']) ?></strong><div class="small text-muted"><?= e($p['sku']) ?></div></td><td><?= e($p['category_name']??'') ?></td><td><?= money($p['sale_price']?:$p['regular_price']) ?></td><td><?= money($estimate['marketing_psa']) ?></td><td><button class="btn btn-sm <?= $p['selected']?'btn-outline-danger':'btn-outline-primary' ?> product-toggle" data-id="<?= (int)$p['id'] ?>" data-action="<?= $p['selected']?'remove':'add' ?>"><?= $p['selected']?'Remove':'Add' ?></button></td></tr><?php endforeach; ?></tbody></table></div></div><div id="productMsg" class="mt-3"></div>
<script>document.querySelectorAll('.product-toggle').forEach(b=>b.addEventListener('click',()=>{b.disabled=true;fetch('<?= url('api/member-product-select.php') ?>',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({csrf_token:'<?= e(csrf_token()) ?>',product_id:b.dataset.id,action:b.dataset.action})}).then(r=>r.json()).then(x=>{document.getElementById('productMsg').innerHTML='<div class="alert alert-'+(x.ok?'success':'danger')+'">'+x.message+'</div>';if(x.ok)location.reload();else b.disabled=false;});}));</script>

<?php elseif ($slug === 'team'): $team=$memberId?Database::safeFetchAll('SELECT at.level_no,am.referral_code,am.rank_code,am.total_psa,u.name,u.email FROM affiliate_tree at JOIN affiliate_members am ON am.id=at.descendant_id LEFT JOIN users u ON u.id=am.user_id WHERE at.ancestor_id=? AND at.level_no>0 ORDER BY at.level_no,am.id LIMIT 500',[$memberId]):[];$byLevel=[];foreach($team as $t){$byLevel[(int)$t['level_no']][]=$t;} ?>
<div class="row g-4"><div class="col-lg-8"><div class="card module-card"><div class="card-header bg-white"><strong>Team members</strong></div><div class="table-responsive"><table class="table mb-0"><thead><tr><th>Level</th><th>Name</th><th>Referral</th><th>Rank</th><th>PSA</th></tr></thead><tbody><?php if(!$team): ?><?= table_empty(5,'No team members yet.') ?><?php endif; ?><?php foreach($team as $t): ?><tr><td><?= (int)$t['level_no'] ?></td><td><?= e($t['name']??'Member') ?><div class="small text-muted"><?= e($t['email']??'') ?></div></td><td><?= e($t['referral_code']) ?></td><td><?= badge($t['rank_code']) ?></td><td><?= money($t['total_psa']) ?></td></tr><?php endforeach; ?></tbody></table></div></div></div><div class="col-lg-4"><div class="card module-card"><div class="card-body"><h5>Level summary</h5><?php if(!$byLevel): ?><p class="text-muted">No downline records.</p><?php endif; ?><?php foreach($byLevel as $level=>$rows): ?><div class="d-flex justify-content-between border-bottom py-2"><span>Level <?= $level ?></span><strong><?= count($rows) ?></strong></div><?php endforeach; ?></div></div></div></div>

<?php elseif ($slug === 'wallets' || $slug === 'withdraw'): $wallets=Database::safeFetchAll('SELECT * FROM wallets WHERE user_id=? ORDER BY wallet_type',[$uid]);$tx=Database::safeFetchAll('SELECT * FROM wallet_transactions WHERE user_id=? ORDER BY id DESC LIMIT 100',[$uid]);$req=Database::safeFetchAll('SELECT * FROM withdraw_requests WHERE user_id=? ORDER BY id DESC LIMIT 50',[$uid]); ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card mb-4"><div class="card-body"><h5>Wallet balances</h5><?php if(!$wallets): ?><p class="text-muted">No wallets yet.</p><?php endif; ?><?php foreach($wallets as $w): ?><div class="d-flex justify-content-between border-bottom py-2"><span><?= e(ucwords(str_replace('_',' ',$w['wallet_type']))) ?></span><strong><?= money($w['balance']) ?></strong></div><?php endforeach; ?></div></div><?php if($slug==='withdraw'): ?><div class="card module-card"><div class="card-body"><h5>Withdrawal request</h5><form id="memberWithdraw"><input class="form-control mb-2" name="amount" type="number" min="1" step="0.01" placeholder="Amount" required><select class="form-select mb-2" name="wallet_type"><option value="commission">Commission</option><option value="royalty">Royalty</option><option value="cash">Cash</option></select><select class="form-select mb-2" name="method"><option>bKash</option><option>Nagad</option><option>Bank</option></select><input class="form-control mb-2" name="account_details" placeholder="Account or bank details" required><input class="form-control mb-3" type="password" name="pin" placeholder="Transaction PIN"><button class="btn btn-primary">Submit request</button></form><div id="withdrawMsg" class="mt-2"></div></div></div><?php endif; ?></div><div class="col-lg-7"><div class="card module-card"><div class="card-header bg-white"><strong><?= $slug==='withdraw'?'Withdrawal history':'Wallet transactions' ?></strong></div><div class="table-responsive"><table class="table mb-0"><thead><tr><?php if($slug==='withdraw'): ?><th>Date</th><th>Gross</th><th>Fee</th><th>Net</th><th>Status</th><?php else: ?><th>Date</th><th>Wallet</th><th>Type</th><th>Amount</th><?php endif; ?></tr></thead><tbody><?php if($slug==='withdraw'): foreach($req as $r): ?><tr><td><?= e($r['created_at']) ?></td><td><?= money($r['amount']) ?></td><td><?= money($r['fee']) ?></td><td><?= money($r['net_amount']) ?></td><td><?= badge($r['status']) ?></td></tr><?php endforeach; else: foreach($tx as $r): ?><tr><td><?= e($r['created_at']) ?></td><td><?= e($r['wallet_type']) ?></td><td><?= badge($r['transaction_type']) ?></td><td><?= money($r['amount']) ?></td></tr><?php endforeach; endif; ?></tbody></table></div></div></div></div>
<?php if($slug==='withdraw'): ?><script>document.getElementById('memberWithdraw').addEventListener('submit',function(e){e.preventDefault();const d=new FormData(this);d.append('csrf_token','<?= e(csrf_token()) ?>');fetch('<?= url('api/withdraw-request.php') ?>',{method:'POST',body:d}).then(r=>r.json()).then(x=>{document.getElementById('withdrawMsg').innerHTML='<div class="alert alert-'+(x.ok?'success':'danger')+'">'+x.message+'</div>';if(x.ok)location.reload();});});</script><?php endif; ?>

<?php elseif ($slug === 'landing' || $slug === 'shop'): $ref=(string)($member['referral_code']??'');$publicLink=url('landing/member.php?ref='.urlencode($ref)); ?>
<div class="row g-4"><div class="col-lg-8"><div class="card module-card"><div class="card-body"><h5>Public affiliate page</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="save_landing"><label class="form-label">Page title</label><input class="form-control mb-3" name="landing_title" value="<?= e($member['landing_title']??'') ?>"><label class="form-label">Biography / offer</label><textarea class="form-control mb-3" rows="5" name="landing_bio"><?= e($member['landing_bio']??'') ?></textarea><label class="form-label">Banner image URL/path</label><input class="form-control mb-3" name="landing_banner" value="<?= e($member['landing_banner']??'') ?>"><label class="form-label">Profile image URL/path</label><input class="form-control mb-3" name="landing_image" value="<?= e($member['landing_image']??'') ?>"><label class="form-label">Contact information</label><textarea class="form-control mb-3" name="contact_info"><?= e($member['contact_info']??'') ?></textarea><button class="btn btn-primary">Save page</button></form></div></div></div><div class="col-lg-4"><div class="card module-card"><div class="card-body"><h5>Referral link</h5><?php if($ref): ?><input id="refLink" class="form-control mb-3" readonly value="<?= e($publicLink) ?>"><button class="btn btn-outline-primary w-100 mb-2" onclick="navigator.clipboard.writeText(document.getElementById('refLink').value)">Copy link</button><a class="btn btn-primary w-100" target="_blank" href="<?= e($publicLink) ?>">Open public page</a><?php else: ?><p class="text-muted">Save this page or activate a plan to generate your referral code.</p><?php endif; ?></div></div></div></div>

<?php elseif ($slug === 'social'): $social=json_decode((string)($member['social_json']??'{}'),true)?:[];$ref=(string)($member['referral_code']??'');$share=url('landing/member.php?ref='.urlencode($ref)); ?>
<div class="row g-4"><div class="col-lg-6"><div class="card module-card"><div class="card-body"><h5>Social profiles</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="save_social"><?php foreach(['facebook','whatsapp','instagram','youtube'] as $network): ?><label class="form-label"><?= e(ucfirst($network)) ?></label><input class="form-control mb-3" name="<?= e($network) ?>" value="<?= e($social[$network]??'') ?>"><?php endforeach; ?><button class="btn btn-primary">Save profiles</button></form></div></div></div><div class="col-lg-6"><div class="card module-card"><div class="card-body"><h5>Share your store</h5><textarea id="shareText" class="form-control mb-3" rows="4">Visit my <?= e(APP_NAME) ?> store: <?= e($share) ?></textarea><div class="d-grid gap-2"><a class="btn btn-success" target="_blank" href="https://wa.me/?text=<?= rawurlencode('Visit my '.APP_NAME.' store: '.$share) ?>">Share on WhatsApp</a><a class="btn btn-primary" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=<?= rawurlencode($share) ?>">Share on Facebook</a><button class="btn btn-outline-primary" onclick="navigator.clipboard.writeText(document.getElementById('shareText').value)">Copy text</button></div></div></div></div></div>

<?php elseif ($slug === 'clicks'): $clicks=$member?Database::safeFetchAll('SELECT DATE(created_at) click_date,COUNT(*) clicks FROM affiliate_clicks WHERE referral_code=? GROUP BY DATE(created_at) ORDER BY click_date DESC LIMIT 60',[$member['referral_code']]):[];$conv=$memberId?Database::safeFetchAll('SELECT ac.*,o.order_no FROM affiliate_conversions ac LEFT JOIN orders o ON o.id=ac.order_id WHERE ac.affiliate_member_id=? ORDER BY ac.id DESC LIMIT 60',[$memberId]):[]; ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card"><div class="card-header bg-white"><strong>Daily clicks</strong></div><table class="table mb-0"><tr><th>Date</th><th>Clicks</th></tr><?php if(!$clicks): ?><?= table_empty(2,'No tracked clicks.') ?><?php endif; ?><?php foreach($clicks as $r): ?><tr><td><?= e($r['click_date']) ?></td><td><?= (int)$r['clicks'] ?></td></tr><?php endforeach; ?></table></div></div><div class="col-lg-7"><div class="card module-card"><div class="card-header bg-white"><strong>Conversions</strong></div><table class="table mb-0"><tr><th>Order</th><th>Amount</th><th>Commission</th><th>Date</th></tr><?php if(!$conv): ?><?= table_empty(4,'No tracked conversions.') ?><?php endif; ?><?php foreach($conv as $r): ?><tr><td><?= e($r['order_no']??('#'.$r['order_id'])) ?></td><td><?= money($r['amount']) ?></td><td><?= money($r['commission']) ?></td><td><?= e($r['created_at']) ?></td></tr><?php endforeach; ?></table></div></div></div></div>

<?php elseif ($slug === 'statements' || $slug === 'commissions'): $rows=Database::safeFetchAll('SELECT * FROM affiliate_statements WHERE affiliate_member_id=? ORDER BY period_end DESC,id DESC LIMIT 100',[$memberId]);$royalties=Database::safeFetchAll('SELECT * FROM leadership_royalties WHERE affiliate_member_id=? ORDER BY id DESC LIMIT 100',[$memberId]); ?>
<div class="card module-card mb-4"><div class="card-header bg-white"><strong>Affiliate statements</strong></div><div class="table-responsive"><table class="table mb-0"><thead><tr><th>Period</th><th>Sales</th><th>PSA</th><th>Royalty</th><th>Team</th><th>Leadership</th><th>Status</th></tr></thead><tbody><?php if(!$rows): ?><?= table_empty(7,'No statements generated.') ?><?php endif; ?><?php foreach($rows as $r): ?><tr><td><?= e(($r['period_start']??'').' – '.($r['period_end']??'')) ?></td><td><?= money($r['total_sales']) ?></td><td><?= money($r['total_psa']) ?></td><td><?= money($r['total_royalty']) ?></td><td><?= money($r['team_income']??0) ?></td><td><?= money($r['leadership_bonus']??0) ?></td><td><?= badge($r['status']) ?></td></tr><?php endforeach; ?></tbody></table></div></div><?php if($slug==='commissions'): ?><div class="card module-card"><div class="card-header bg-white"><strong>Leadership royalties</strong></div><table class="table mb-0"><tr><th>Type</th><th>Percentage</th><th>Amount</th><th>Date</th></tr><?php if(!$royalties): ?><?= table_empty(4,'No royalty entries.') ?><?php endif; ?><?php foreach($royalties as $r): ?><tr><td><?= e($r['leader_type']) ?></td><td><?= e($r['percentage']) ?>%</td><td><?= money($r['amount']) ?></td><td><?= e($r['created_at']) ?></td></tr><?php endforeach; ?></table></div><?php endif; ?>

<?php elseif ($slug === 'rank'): $ranks=Database::safeFetchAll('SELECT * FROM affiliate_ranks ORDER BY required_psa');$weeklyMin=(float)(setting('weekly_royalty_min_sale','2000'));$weekly=(float)($member['weekly_personal_sales']??0); ?>
<div class="row g-4"><div class="col-lg-8"><div class="card module-card"><div class="card-header bg-white"><strong>Rank progress</strong></div><table class="table mb-0"><tr><th>Rank</th><th>Required PSA</th><th>Your PSA</th><th>Status</th></tr><?php foreach($ranks as $r): ?><tr><td><?= e($r['code'].' – '.$r['name']) ?></td><td><?= money($r['required_psa']) ?></td><td><?= money($totalPsa) ?></td><td><?= badge($totalPsa>=(float)$r['required_psa']?'achieved':'in progress') ?></td></tr><?php endforeach; ?></table></div></div><div class="col-lg-4"><div class="card module-card"><div class="card-body"><h5>Royalty eligibility</h5><p>Required weekly sale: <strong><?= money($weeklyMin) ?></strong></p><p>Your weekly sale: <strong><?= money($weekly) ?></strong></p><?= badge($weekly>=$weeklyMin?'eligible':'not eligible') ?></div></div></div></div>

<?php else: ?>
<div class="card module-card"><div class="card-body"><h5><?= e($title) ?></h5><p class="text-muted">This affiliate module is connected to your live database.</p></div></div>
<?php endif; ?>
<?php require_once ROOT_PATH . '/app/Layouts/panel_footer.php'; ?>
