<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/referrals.php';

if (!isset($pdo)) {
    $pdo = require_once __DIR__ . '/../config/database.php';
}

require_admin();

$action = $_POST['action'] ?? '';

// Mark Status
if ($action === 'mark_status') {
  ensure_csrf();
  $id = (int)($_POST['id'] ?? 0);
  $status = in_array($_POST['status'] ?? 'pending', ['pending','paid','void'], true) ? $_POST['status'] : 'pending';
  $tsCol = $status==='paid' ? 'paid_at' : null;
  
  if ($tsCol) {
    $pdo->prepare("UPDATE commissions SET status=?, {$tsCol}=? WHERE id=?")->execute([$status, date('c'), $id]);
  } else {
    $pdo->prepare("UPDATE commissions SET status=? WHERE id=?")->execute([$status, $id]);
  }
  set_flash('success','Commission status updated');
  redirect('/admin/commissions.php');
}

if ($action === 'process_weekly') {
    ensure_csrf();
    $count = process_weekly_payouts($pdo);
    set_flash('success', "$count commissions marked for payout.");
    redirect('/admin/commissions.php');
}

// Fetch Commissions
$comms = $pdo->query("
    SELECT c.*, u.full_name AS ref_name, s.full_name AS source_name 
    FROM commissions c 
    JOIN users u ON u.id=c.referrer_id 
    LEFT JOIN users s ON s.id=c.source_user_id 
    ORDER BY c.created_at DESC LIMIT 100
")->fetchAll();

// Stats
$totalPending = $pdo->query("SELECT SUM(amount) FROM commissions WHERE status='pending'")->fetchColumn() ?: 0;
$totalPaid = $pdo->query("SELECT SUM(amount) FROM commissions WHERE status='paid'")->fetchColumn() ?: 0;

include __DIR__ . '/../includes/header.php';
?>
<style>
/* Commissions Admin Styles */
.admin-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px; gap: 16px; flex-wrap: wrap; }
.admin-title { margin: 0; font-size: 28px; font-weight: 800; color: var(--text); letter-spacing: -0.5px; }

/* Stats Grid */
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 24px; margin-bottom: 32px; }
.stat-card { background: #fff; border: 1px solid var(--border); border-radius: 24px; padding: 28px; display: flex; align-items: flex-start; gap: 20px; }
.stat-icon { width: 56px; height: 56px; border-radius: 16px; display: flex; align-items: center; justify-content: center; font-size: 24px; }
.stat-info { flex: 1; }
.stat-value { font-size: 28px; font-weight: 800; color: var(--text); line-height: 1; margin-bottom: 8px; }
.stat-label { font-size: 14px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px; }

.stat-pending { border-left: 5px solid #f59e0b; }
.stat-pending .stat-icon { background: #fef3c7; color: #d97706; }
.stat-paid { border-left: 5px solid #10b981; }
.stat-paid .stat-icon { background: #ecfdf5; color: #059669; }

/* Table Section */
.comm-table-card { background: #fff; border: 1px solid var(--border); border-radius: 24px; overflow: hidden; }
.comm-table-header { padding: 24px 32px; border-bottom: 1px solid var(--border); background: #f8fafc; display: flex; justify-content: space-between; align-items: center; }

@media(max-width:767px){
    .admin-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
    }
    .stats-grid { grid-template-columns: 1fr; }
    .comm-table-header { flex-direction: column; align-items: flex-start; gap: 16px; }
    .comm-table-header form {
        width: 100%;
    }
    .comm-table-header button {
        width: 100%;
        justify-content: center;
    }
    .table-wrap { display: none; }
    .mobile-grid { display: grid; gap: 16px; padding: 16px; }
}
@media(min-width:768px){
    .mobile-grid { display: none; }
}
</style>

<div class="admin-header">
    <h1 class="admin-title">Commissions & Referrals</h1>
    <div style="font-size:14px; color:var(--muted); font-weight:600">
        <?=date('F Y')?> Period
    </div>
</div>

<div class="stats-grid">
    <div class="stat-card stat-pending">
        <div class="stat-icon"><?=ui_icon('pricing', 24)?></div>
        <div class="stat-info">
            <div class="stat-value">₦<?=number_format((float)$totalPending, 2)?></div>
            <div class="stat-label">Pending Payouts</div>
        </div>
    </div>
    <div class="stat-card stat-paid">
        <div class="stat-icon"><?=ui_icon('approved', 24)?></div>
        <div class="stat-info">
            <div class="stat-value">₦<?=number_format((float)$totalPaid, 2)?></div>
            <div class="stat-label">Total Paid Out</div>
        </div>
    </div>
</div>

<div class="comm-table-card">
    <div class="comm-table-header">
        <h3 style="margin:0; font-size:18px; font-weight:800">Payout Ledger</h3>
        <form method="post" onsubmit="return confirm('Process weekly payouts? This will mark pending commissions from last week as processed.');">
            <?=csrf_field()?>
            <input type="hidden" name="action" value="process_weekly">
            <button class="btn primary" style="padding:10px 24px; font-weight:700">
                <?=ui_icon('processing', 18)?> Process Weekly Payouts
            </button>
        </form>
    </div>
    
    <div class="table-wrap">
        <table class="striped">
            <thead>
                <tr>
                    <th style="padding-left:32px">Date</th>
                    <th>Referrer</th>
                    <th>Source Details</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th style="padding-right:32px; text-align:right">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($comms as $c): ?>
                <tr>
                    <td style="padding-left:32px">
                        <div style="font-weight:600; font-size:14px"><?=date('M j, Y', strtotime($c['created_at']))?></div>
                        <div style="font-size:12px; color:var(--muted)"><?=date('H:i', strtotime($c['created_at']))?></div>
                    </td>
                    <td>
                        <div style="display:flex; align-items:center; gap:12px">
                            <div style="width:36px; height:36px; border-radius:10px; background:#eff6ff; color:#2563eb; display:flex; align-items:center; justify-content:center; font-weight:800; font-size:14px">
                                <?=strtoupper(substr($c['ref_name'], 0, 1))?>
                            </div>
                            <div style="font-weight:700; color:var(--text)"><?=e($c['ref_name'])?></div>
                        </div>
                    </td>
                    <td>
                        <div style="font-weight:600; font-size:14px"><?=e($c['source_name'] ?? 'Guest User')?></div>
                        <div style="font-size:12px; color:var(--muted)">Application #<?=e((string)$c['application_id'])?></div>
                    </td>
                    <td>
                        <div style="font-weight:800; color:var(--text); font-size:16px">₦<?=number_format((float)$c['amount'], 2)?></div>
                    </td>
                    <td>
                        <?php 
                        $st = $c['status'];
                        $cls = 'status-submitted'; // blue/yellow
                        if($st=='paid') $cls='status-approved'; // green
                        if($st=='void') $cls='status-rejected'; // red
                        ?>
                        <span class="status-pill <?=$cls?>"><?=ucfirst($st)?></span>
                    </td>
                    <td style="padding-right:32px; text-align:right">
                        <?php if($c['status'] === 'pending'): ?>
                        <form method="post" style="display:inline-flex; gap:8px; justify-content:flex-end">
                            <?=csrf_field()?>
                            <input type="hidden" name="action" value="mark_status">
                            <input type="hidden" name="id" value="<?=e((string)$c['id'])?>">
                            <button name="status" value="paid" class="btn primary" style="padding:8px 14px; font-size:12px; font-weight:700">Mark Paid</button>
                            <button name="status" value="void" class="btn" style="padding:8px 14px; font-size:12px; font-weight:700; color:#ef4444; border-color:#fecaca">Void</button>
                        </form>
                        <?php else: ?>
                        <div style="font-size:12px; font-weight:600; color:var(--muted); background:#f1f5f9; padding:4px 10px; border-radius:6px; display:inline-block">
                            <?= $c['status'] === 'paid' ? 'Paid on '.date('M j', strtotime($c['paid_at'] ?? '')) : 'Voided' ?>
                        </div>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if(empty($comms)): ?>
                <tr><td colspan="6" style="text-align:center; padding:80px; color:var(--muted)">No commissions recorded in the system yet.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <div class="mobile-grid">
        <?php foreach ($comms as $c): ?>
            <?php 
            $st = $c['status'];
            $cls = 'status-submitted'; // blue/yellow
            if($st=='paid') $cls='status-approved'; // green
            if($st=='void') $cls='status-rejected'; // red
            ?>
            <div class="card" style="margin-bottom:0; padding:20px; border-radius:16px">
                <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:16px">
                    <div>
                        <div style="font-weight:700; color:var(--text)"><?=e($c['ref_name'])?></div>
                        <div style="font-size:13px; color:var(--muted)"><?=e($c['source_name'] ?? 'Guest User')?> (#<?=e((string)$c['application_id'])?>)</div>
                    </div>
                    <span class="status-pill <?=$cls?>"><?=ucfirst($st)?></span>
                </div>
                <div style="font-size:13px; color:var(--muted); margin-bottom:4px">Date: <?=date('M j, Y H:i', strtotime($c['created_at']))?></div>
                <div style="display:flex; justify-content:space-between; align-items:center; margin-top:8px; border-top:1px solid #f1f5f9; padding-top:12px">
                    <div style="font-weight:800; color:var(--text); font-size:16px">₦<?=number_format((float)$c['amount'], 2)?></div>
                    <?php if($c['status'] === 'pending'): ?>
                    <div style="display:flex; gap:8px;">
                        <form method="post" style="display:flex; gap:8px;">
                            <?=csrf_field()?>
                            <input type="hidden" name="action" value="mark_status">
                            <input type="hidden" name="id" value="<?=e((string)$c['id'])?>">
                            <button name="status" value="paid" class="btn primary" style="padding:6px 12px; font-size:12px; font-weight:700">Mark Paid</button>
                            <button name="status" value="void" class="btn" style="padding:6px 12px; font-size:12px; font-weight:700; color:#ef4444; border-color:#fecaca">Void</button>
                        </form>
                    </div>
                    <?php else: ?>
                    <div style="font-size:12px; font-weight:600; color:var(--muted); background:#f1f5f9; padding:4px 10px; border-radius:6px; display:inline-block">
                        <?= $c['status'] === 'paid' ? 'Paid on '.date('M j', strtotime($c['paid_at'] ?? '')) : 'Voided' ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
