<?php
/* ============================================================================
   WBMCZ ADMIN — PAYOUT & EARNING MANAGEMENT
   One screen per audience (All / Free / Pro / Seller / Employees / Admin)
   showing what each member earned, what they withdrew, what is still owed.
   ============================================================================ */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/includes/role_filter.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }

/* Only a staff account that was given this module may open the page */
require_once __DIR__ . '/../includes/rbac.php';
rbac_guard('manage_transactions');

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = $_SESSION['user_id'];

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user      = !empty($user_data) ? $user_data[0] : null;
if (!$user) { session_destroy(); redirect('login.php'); }

$flash = $_SESSION['flash_success'] ?? '';
unset($_SESSION['flash_success']);

/* ---------------------------------------------------------------------------
   CONTEXT
   ------------------------------------------------------------------------ */
$wb_role  = wb_role();
if ($wb_role === '') $wb_role = 'all';
$cond     = wb_role_sql($wb_role, 'u');
$search   = trim((string)($_GET['q'] ?? ''));
$sort     = in_array($_GET['sort'] ?? '', ['earned', 'withdrawn', 'pending', 'balance', 'name'], true) ? $_GET['sort'] : 'earned';

/* Which wallet_ledger categories count as "earning" */
$EARN_CATS = "'referral','seller_share','staff_share','bonus','commission','cashback'";

/* ---------------------------------------------------------------------------
   HEADLINE TOTALS
   ------------------------------------------------------------------------ */
$T = ['earned' => 0.0, 'withdrawn' => 0.0, 'pending_amt' => 0.0, 'pending_no' => 0, 'balance' => 0.0, 'members' => 0];

try {
    $r = $db->select("SELECT COUNT(*) n, COALESCE(SUM(u.wallet_balance),0) bal FROM users u WHERE $cond");
    if (!empty($r)) { $T['members'] = (int)$r[0]['n']; $T['balance'] = (float)$r[0]['bal']; }
} catch (\Throwable $e) {}

try {
    $r = $db->select("SELECT COALESCE(SUM(l.amount),0) s
                        FROM wallet_ledger l JOIN users u ON u.id = l.user_id
                       WHERE l.direction = 'credit' AND l.category IN ($EARN_CATS) AND $cond");
    if (!empty($r)) $T['earned'] = (float)$r[0]['s'];
} catch (\Throwable $e) {}

try {
    $r = $db->select("SELECT
            COALESCE(SUM(CASE WHEN w.status IN ('approved','Approved') THEN w.net_amount ELSE 0 END),0) paid,
            COALESCE(SUM(CASE WHEN w.status IN ('pending','Pending','processing','Processing') THEN w.amount ELSE 0 END),0) pend,
            SUM(CASE WHEN w.status IN ('pending','Pending','processing','Processing') THEN 1 ELSE 0 END) pn
          FROM withdrawal_requests w JOIN users u ON u.id = w.user_id WHERE $cond");
    if (!empty($r)) {
        $T['withdrawn']   = (float)$r[0]['paid'];
        $T['pending_amt'] = (float)$r[0]['pend'];
        $T['pending_no']  = (int)$r[0]['pn'];
    }
} catch (\Throwable $e) {}

/* ---------------------------------------------------------------------------
   PER-MEMBER BREAKDOWN
   ------------------------------------------------------------------------ */
$order_map = [
    'earned'    => 'earned DESC',
    'withdrawn' => 'withdrawn DESC',
    'pending'   => 'pending DESC',
    'balance'   => 'u.wallet_balance DESC',
    'name'      => 'u.name ASC',
];
$order_sql = $order_map[$sort];

$params = [];
$search_sql = '';
if ($search !== '') {
    $search_sql = " AND (u.name LIKE ? OR u.mobile LIKE ? OR u.email LIKE ? OR u.id = ?)";
    $like = "%$search%";
    array_push($params, $like, $like, $like, (int)preg_replace('/\D/', '', $search));
}

$rows = [];
try {
    $rows = $db->select(
        "SELECT u.id, u.name, u.mobile, u.user_type, u.role_id,
                COALESCE(u.is_subscribed,0) AS is_subscribed,
                COALESCE(u.wallet_balance,0) AS wallet_balance,
                COALESCE(u.bonus_wallet,0)   AS bonus_wallet,
                COALESCE((SELECT SUM(l.amount) FROM wallet_ledger l
                           WHERE l.user_id = u.id AND l.direction='credit'
                             AND l.category IN ($EARN_CATS)),0) AS earned,
                COALESCE((SELECT SUM(w.net_amount) FROM withdrawal_requests w
                           WHERE w.user_id = u.id AND w.status IN ('approved','Approved')),0) AS withdrawn,
                COALESCE((SELECT SUM(w.amount) FROM withdrawal_requests w
                           WHERE w.user_id = u.id AND w.status IN ('pending','Pending','processing','Processing')),0) AS pending
           FROM users u
          WHERE $cond $search_sql
          ORDER BY $order_sql
          LIMIT 300", $params);
} catch (\Throwable $e) { $rows = []; }

/* ---------------------------------------------------------------------------
   RECENT PAYOUT REQUESTS FOR THIS AUDIENCE
   ------------------------------------------------------------------------ */
$requests = [];
try {
    $requests = $db->select(
        "SELECT w.*, u.name AS member, u.mobile
           FROM withdrawal_requests w
           JOIN users u ON u.id = w.user_id
          WHERE $cond
          ORDER BY FIELD(LOWER(w.status),'pending','processing','approved','rejected'), w.created_at DESC
          LIMIT 40");
} catch (\Throwable $e) { $requests = []; }

/* ---------------------------------------------------------------------------
   EARNING MIX (what the money came from)
   ------------------------------------------------------------------------ */
$mix = [];
try {
    $mix = $db->select(
        "SELECT l.category, COALESCE(SUM(l.amount),0) s, COUNT(*) n
           FROM wallet_ledger l JOIN users u ON u.id = l.user_id
          WHERE l.direction='credit' AND l.category IN ($EARN_CATS) AND $cond
          GROUP BY l.category ORDER BY s DESC");
} catch (\Throwable $e) { $mix = []; }
$mix_total = 0.0;
foreach ($mix as $m) { $mix_total += (float)$m['s']; }

/* CSV export */
if (isset($_GET['export'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=payouts_' . $wb_role . '_' . date('Ymd_His') . '.csv');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID', 'Name', 'Mobile', 'Type', 'Earned', 'Withdrawn', 'Pending', 'Wallet Balance']);
    foreach ($rows as $r) {
        fputcsv($out, [$r['id'], $r['name'], $r['mobile'], $r['user_type'],
                       $r['earned'], $r['withdrawn'], $r['pending'], $r['wallet_balance']]);
    }
    fclose($out);
    exit;
}

$raw_logo     = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($raw_logo, 'http') === 0) ? $raw_logo : '../' . ltrim($raw_logo, '/');
$company_name = getSetting('company_name', 'WBMCZ');

function pay_status_pill($s) {
    switch (strtolower((string)$s)) {
        case 'approved':   return 'bg-emerald-50 text-emerald-700 ring-emerald-200';
        case 'rejected':   return 'bg-rose-50 text-rose-700 ring-rose-200';
        case 'processing': return 'bg-sky-50 text-sky-700 ring-sky-200';
        default:           return 'bg-amber-50 text-amber-700 ring-amber-200';
    }
}
function pay_cat_label($c) {
    $m = ['referral' => 'Referral income', 'seller_share' => 'Seller share', 'staff_share' => 'Staff share',
          'bonus' => 'Bonus', 'commission' => 'Commission', 'cashback' => 'Cashback'];
    return $m[$c] ?? ucwords(str_replace('_', ' ', (string)$c));
}
function pay_qs($over = []) {
    $q = array_merge($_GET, $over);
    unset($q['export']);
    return '?' . http_build_query(array_filter($q, function ($v) { return $v !== '' && $v !== null; }));
}
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payout &amp; Earning - <?php echo htmlspecialchars($company_name); ?> Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        [x-cloak] { display: none !important; }
    </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768, tab: 'members' }">

<div class="flex h-screen overflow-hidden">

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

    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">

        <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative flex-shrink-0">
            <div class="flex items-center min-w-0">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg hover:bg-gray-100 transition-colors"><i class="fas fa-bars text-xl"></i></button>
                <div class="min-w-0">
                    <h2 class="text-xl font-bold truncate">Payout &amp; Earning</h2>
                    <p class="text-[11px] text-slate-400 hidden sm:block"><?php echo htmlspecialchars(wb_role_label($wb_role)); ?> &bull; <?php echo number_format($T['members']); ?> members</p>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <a href="<?php echo pay_qs(); ?>&export=1" class="hidden sm:inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-white ring-1 ring-slate-200 text-xs font-bold text-slate-600 hover:bg-slate-50 transition-colors">
                    <i class="fas fa-file-csv"></i> Export
                </a>
                <a href="withdrawals.php#bank_requests" class="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold shadow-lg shadow-emerald-600/25 transition-all">
                    <i class="fas fa-building-columns"></i> Approve payouts
                    <?php if ($T['pending_no'] > 0): ?><span class="ml-1 px-1.5 py-0.5 rounded-full bg-white/20 text-[10px]"><?php echo $T['pending_no']; ?></span><?php endif; ?>
                </a>
            </div>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">

            <?php if ($flash): ?>
            <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                <i class="fas fa-check-circle mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($flash); ?></span>
            </div>
            <?php endif; ?>

            <?php echo wb_role_tabs($wb_role, 'payouts.php'); ?>

            <!-- ================= HEADLINE ================= -->
            <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                <?php
                $cards = [
                    ['Total earned',    $T['earned'],      'fa-sack-dollar',        'from-emerald-500 to-teal-600',  'text-emerald-600'],
                    ['Paid out',        $T['withdrawn'],   'fa-money-bill-transfer','from-sky-500 to-blue-600',      'text-sky-600'],
                    ['Pending payouts', $T['pending_amt'], 'fa-hourglass-half',     'from-amber-500 to-orange-600',  'text-amber-600'],
                    ['Wallet holdings', $T['balance'],     'fa-wallet',             'from-violet-500 to-purple-600', 'text-violet-600'],
                ];
                foreach ($cards as $c): ?>
                <div class="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm relative overflow-hidden">
                    <div class="absolute -right-6 -top-6 w-24 h-24 rounded-full bg-gradient-to-br <?php echo $c[3]; ?> opacity-10"></div>
                    <div class="w-10 h-10 rounded-xl bg-gradient-to-br <?php echo $c[3]; ?> text-white grid place-items-center mb-3 shadow-lg"><i class="fas <?php echo $c[2]; ?>"></i></div>
                    <p class="text-[11px] font-bold uppercase tracking-widest text-slate-400"><?php echo $c[0]; ?></p>
                    <p class="text-2xl font-extrabold <?php echo $c[4]; ?>">&#8377;<?php echo number_format($c[1], 2); ?></p>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- ================= EARNING MIX ================= -->
            <?php if (!empty($mix)): ?>
            <div class="bg-white rounded-2xl border border-slate-200 p-5 md:p-6 shadow-sm mb-6">
                <h3 class="text-sm font-extrabold text-slate-800 mb-4"><i class="fas fa-chart-simple text-emerald-600 mr-2"></i>Where the earnings came from</h3>
                <div class="space-y-3">
                    <?php foreach ($mix as $m):
                        $pct = $mix_total > 0 ? ((float)$m['s'] / $mix_total) * 100 : 0; ?>
                        <div>
                            <div class="flex items-center justify-between text-xs mb-1.5">
                                <span class="font-bold text-slate-700"><?php echo htmlspecialchars(pay_cat_label($m['category'])); ?>
                                    <span class="text-slate-400 font-medium">&middot; <?php echo number_format((int)$m['n']); ?> entries</span>
                                </span>
                                <span class="font-extrabold text-slate-800">&#8377;<?php echo number_format((float)$m['s'], 2); ?>
                                    <span class="text-slate-400 font-semibold ml-1"><?php echo number_format($pct, 1); ?>%</span>
                                </span>
                            </div>
                            <div class="h-2 rounded-full bg-slate-100 overflow-hidden">
                                <div class="h-full rounded-full bg-gradient-to-r from-emerald-400 to-teal-500" style="width: <?php echo max(1.5, $pct); ?>%"></div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- ================= TABS ================= -->
            <div class="flex items-center gap-2 mb-4">
                <button @click="tab = 'members'" :class="tab === 'members' ? 'bg-slate-900 text-white ring-slate-900 shadow-lg shadow-slate-900/20' : 'bg-white text-slate-600 ring-slate-200 hover:bg-slate-50'"
                        class="px-4 py-2 rounded-xl text-xs font-bold ring-1 transition-all"><i class="fas fa-users mr-1.5"></i>Member breakdown</button>
                <button @click="tab = 'requests'" :class="tab === 'requests' ? 'bg-slate-900 text-white ring-slate-900 shadow-lg shadow-slate-900/20' : 'bg-white text-slate-600 ring-slate-200 hover:bg-slate-50'"
                        class="px-4 py-2 rounded-xl text-xs font-bold ring-1 transition-all"><i class="fas fa-receipt mr-1.5"></i>Payout requests
                    <?php if ($T['pending_no'] > 0): ?><span class="ml-1 px-1.5 py-0.5 rounded-full bg-rose-500 text-white text-[10px]"><?php echo $T['pending_no']; ?></span><?php endif; ?>
                </button>
            </div>

            <!-- ================= MEMBERS ================= -->
            <div x-show="tab === 'members'" x-cloak>
                <form method="GET" class="flex flex-wrap gap-2 mb-4">
                    <input type="hidden" name="role" value="<?php echo htmlspecialchars($wb_role); ?>">
                    <div class="relative flex-1 min-w-[15rem]">
                        <i class="fas fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-300 text-xs"></i>
                        <input type="text" name="q" value="<?php echo htmlspecialchars($search); ?>" placeholder="Search member by name, mobile or ID…"
                               class="w-full pl-9 pr-3 py-2.5 bg-white border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-emerald-400 focus:border-emerald-400 outline-none transition-all">
                    </div>
                    <select name="sort" onchange="this.form.submit()" class="px-3 py-2.5 bg-white border border-slate-200 rounded-xl text-sm font-semibold text-slate-600 outline-none">
                        <option value="earned"    <?php echo $sort === 'earned'    ? 'selected' : ''; ?>>Highest earning</option>
                        <option value="pending"   <?php echo $sort === 'pending'   ? 'selected' : ''; ?>>Pending payout</option>
                        <option value="withdrawn" <?php echo $sort === 'withdrawn' ? 'selected' : ''; ?>>Most withdrawn</option>
                        <option value="balance"   <?php echo $sort === 'balance'   ? 'selected' : ''; ?>>Wallet balance</option>
                        <option value="name"      <?php echo $sort === 'name'      ? 'selected' : ''; ?>>Name (A&ndash;Z)</option>
                    </select>
                    <button type="submit" class="px-5 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold shadow-lg shadow-emerald-600/25 transition-all">Search</button>
                </form>

                <div class="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm">
                            <thead class="bg-slate-50 text-slate-500 text-[11px] uppercase tracking-wider">
                                <tr>
                                    <th class="px-5 py-3 text-left font-bold">Member</th>
                                    <th class="px-5 py-3 text-left font-bold">Type</th>
                                    <th class="px-5 py-3 text-right font-bold">Earned</th>
                                    <th class="px-5 py-3 text-right font-bold">Withdrawn</th>
                                    <th class="px-5 py-3 text-right font-bold">Pending</th>
                                    <th class="px-5 py-3 text-right font-bold">Wallet</th>
                                    <th class="px-5 py-3 text-right font-bold"></th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                            <?php if (empty($rows)): ?>
                                <tr><td colspan="7" class="px-5 py-16 text-center text-slate-400">
                                    <i class="fas fa-inbox text-3xl mb-3 block text-slate-300"></i>No members in this audience yet.
                                </td></tr>
                            <?php else: foreach ($rows as $r):
                                $type = $r['user_type'] === 'admin'
                                        ? (empty($r['role_id']) ? 'Admin' : 'Employee')
                                        : ($r['user_type'] === 'seller' ? 'Seller' : (!empty($r['is_subscribed']) ? 'Pro User' : 'Free User')); ?>
                                <tr class="hover:bg-slate-50/70 transition-colors">
                                    <td class="px-5 py-3">
                                        <p class="font-bold text-slate-800"><?php echo htmlspecialchars($r['name']); ?></p>
                                        <p class="text-[11px] text-slate-400 font-mono">WBMCZ<?php echo str_pad($r['id'], 4, '0', STR_PAD_LEFT); ?> &middot; <?php echo htmlspecialchars($r['mobile']); ?></p>
                                    </td>
                                    <td class="px-5 py-3">
                                        <span class="px-2.5 py-1 rounded-full text-[10px] font-bold bg-slate-100 text-slate-600"><?php echo $type; ?></span>
                                    </td>
                                    <td class="px-5 py-3 text-right font-extrabold text-emerald-600">&#8377;<?php echo number_format((float)$r['earned'], 2); ?></td>
                                    <td class="px-5 py-3 text-right font-semibold text-sky-600">&#8377;<?php echo number_format((float)$r['withdrawn'], 2); ?></td>
                                    <td class="px-5 py-3 text-right font-semibold <?php echo (float)$r['pending'] > 0 ? 'text-amber-600' : 'text-slate-300'; ?>">&#8377;<?php echo number_format((float)$r['pending'], 2); ?></td>
                                    <td class="px-5 py-3 text-right font-extrabold text-slate-800">&#8377;<?php echo number_format((float)$r['wallet_balance'], 2); ?></td>
                                    <td class="px-5 py-3 text-right whitespace-nowrap">
                                        <a href="wallet_history.php?uid=<?php echo (int)$r['id']; ?>" class="text-xs font-bold text-slate-400 hover:text-emerald-600 transition-colors"><i class="fas fa-clock-rotate-left mr-1"></i>History</a>
                                    </td>
                                </tr>
                            <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- ================= REQUESTS ================= -->
            <div x-show="tab === 'requests'" x-cloak>
                <div class="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm">
                            <thead class="bg-slate-50 text-slate-500 text-[11px] uppercase tracking-wider">
                                <tr>
                                    <th class="px-5 py-3 text-left font-bold">Reference</th>
                                    <th class="px-5 py-3 text-left font-bold">Member</th>
                                    <th class="px-5 py-3 text-left font-bold">Bank</th>
                                    <th class="px-5 py-3 text-right font-bold">Amount</th>
                                    <th class="px-5 py-3 text-right font-bold">Net</th>
                                    <th class="px-5 py-3 text-left font-bold">Status</th>
                                    <th class="px-5 py-3 text-left font-bold">Requested</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                            <?php if (empty($requests)): ?>
                                <tr><td colspan="7" class="px-5 py-16 text-center text-slate-400">
                                    <i class="fas fa-receipt text-3xl mb-3 block text-slate-300"></i>No payout requests from this audience.
                                </td></tr>
                            <?php else: foreach ($requests as $w): ?>
                                <tr class="hover:bg-slate-50/70 transition-colors">
                                    <td class="px-5 py-3 font-mono text-xs text-slate-500"><?php echo htmlspecialchars($w['reference_no']); ?></td>
                                    <td class="px-5 py-3">
                                        <p class="font-bold text-slate-800"><?php echo htmlspecialchars($w['member']); ?></p>
                                        <p class="text-[11px] text-slate-400"><?php echo htmlspecialchars($w['mobile']); ?></p>
                                    </td>
                                    <td class="px-5 py-3 text-slate-600 text-xs">
                                        <?php echo htmlspecialchars($w['bank_name'] ?: '—'); ?><br>
                                        <span class="text-slate-400 font-mono"><?php echo htmlspecialchars($w['account_number'] ?: ''); ?></span>
                                    </td>
                                    <td class="px-5 py-3 text-right font-extrabold text-slate-800">&#8377;<?php echo number_format((float)$w['amount'], 2); ?></td>
                                    <td class="px-5 py-3 text-right font-semibold text-emerald-600">&#8377;<?php echo number_format((float)$w['net_amount'], 2); ?></td>
                                    <td class="px-5 py-3">
                                        <span class="px-2.5 py-1 rounded-full text-[10px] font-bold ring-1 <?php echo pay_status_pill($w['status']); ?>"><?php echo htmlspecialchars(ucfirst($w['status'])); ?></span>
                                    </td>
                                    <td class="px-5 py-3 text-slate-500 text-xs whitespace-nowrap"><?php echo date('d M Y', strtotime($w['created_at'])); ?></td>
                                </tr>
                            <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php if (!empty($requests)): ?>
                    <div class="px-5 py-3 bg-slate-50 border-t border-slate-100 text-right">
                        <a href="withdrawals.php#bank_requests" class="text-xs font-bold text-emerald-600 hover:text-emerald-700">Open full payout console <i class="fas fa-arrow-right ml-1"></i></a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="h-10"></div>
        </main>
    </div>
</div>

</body>
</html>
