<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/lipalink.php'; // LipaLink/PesaFlux API helper
require_once 'admin_protect.php';
requirePermission('system_settings');

$conn = getConnection();
$activeTab = $_GET['tab'] ?? 'chat';

// ════════════════════════════════════════════════════════════════════
// POST HANDLER
// ════════════════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // ── Chat Settings ─────────────────────────────────────────────────
    if ($action === 'chat_settings') {
        updateSetting('chat_foreigners_unlock_fee',    sanitize($_POST['chat_foreigners_unlock_fee'] ?? '100'));
        updateSetting('chat_foreigners_redirect_link', sanitize($_POST['chat_foreigners_redirect_link'] ?? ''));
        updateSetting('chat_foreigners_api_key',       sanitize($_POST['chat_foreigners_api_key'] ?? ''));
        updateSetting('chat_foreigners_business_id',   sanitize($_POST['chat_foreigners_business_id'] ?? ''));
        // Upline commission levels (fixed KES per level)
        updateSetting('cf_commission_l1', max(0, floatval($_POST['cf_commission_l1'] ?? 0)));
        updateSetting('cf_commission_l2', max(0, floatval($_POST['cf_commission_l2'] ?? 0)));
        updateSetting('cf_commission_l3', max(0, floatval($_POST['cf_commission_l3'] ?? 0)));
        setFlash('success', 'Chat Foreigners settings saved!');
        redirect('chat_spin_admin.php?tab=chat');
    }

    // ── Spin Settings ─────────────────────────────────────────────────
    if ($action === 'spin_settings') {
        updateSetting('spin_rtp_red',        max(0, min(100, floatval($_POST['spin_rtp_red']        ?? 48))));
        updateSetting('spin_rtp_black',      max(0, min(100, floatval($_POST['spin_rtp_black']      ?? 48))));
        updateSetting('spin_rtp_even',       max(0, min(100, floatval($_POST['spin_rtp_even']       ?? 47))));
        updateSetting('spin_rtp_odd',        max(0, min(100, floatval($_POST['spin_rtp_odd']        ?? 47))));
        updateSetting('spin_min_bet',        max(1,          floatval($_POST['spin_min_bet']        ?? 10)));
        updateSetting('spin_max_bet',        max(10,         floatval($_POST['spin_max_bet']        ?? 1000)));
        updateSetting('spin_win_multiplier', max(1.1,        floatval($_POST['spin_win_multiplier'] ?? 1.9)));
        updateSetting('spin_api_key',        sanitize($_POST['spin_api_key'] ?? ''));
        updateSetting('spin_business_id',    sanitize($_POST['spin_business_id'] ?? ''));
        setFlash('success', 'Spin & Win settings saved!');
        redirect('chat_spin_admin.php?tab=spin');
    }

    // ── User search (AJAX) ────────────────────────────────────────────
    if ($action === 'search_user') {
        header('Content-Type: application/json');
        $q = trim($_POST['query'] ?? '');
        if (strlen($q) < 2) { echo json_encode([]); exit; }
        $like = '%' . $conn->real_escape_string($q) . '%';
        $res  = $conn->query("SELECT id, username, email, phone, country FROM users
            WHERE username LIKE '$like' OR email LIKE '$like' OR phone LIKE '$like'
            LIMIT 8");
        $rows = [];
        while ($r = $res->fetch_assoc()) $rows[] = $r;
        echo json_encode($rows);
        exit;
    }

    // ── Grant access ──────────────────────────────────────────────────
    if ($action === 'grant_access') {
        $uid = intval($_POST['user_id'] ?? 0);
        if ($uid < 1) { setFlash('error','Select a user first.'); redirect('chat_spin_admin.php?tab=users'); }
        $uChk = $conn->prepare("SELECT id,username FROM users WHERE id=? LIMIT 1");
        $uChk->bind_param("i",$uid); $uChk->execute();
        $uRow = $uChk->get_result()->fetch_assoc();
        if (!$uRow) { setFlash('error','User not found.'); redirect('chat_spin_admin.php?tab=users'); }
        $conn->query("CREATE TABLE IF NOT EXISTS chat_foreigners_access (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL UNIQUE,
            status ENUM('active','revoked') DEFAULT 'active',
            granted_by INT,
            granted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            revoked_at DATETIME NULL,
            INDEX idx_user (user_id), INDEX idx_status (status)
        )");
        $adminId = $_SESSION['admin_id'] ?? 0;
        $stat = 'active';
        $stmt = $conn->prepare("INSERT INTO chat_foreigners_access (user_id,status,granted_by) VALUES (?,?,?)
            ON DUPLICATE KEY UPDATE status='active',granted_at=NOW(),revoked_at=NULL,granted_by=?");
        $stmt->bind_param("isii",$uid,$stat,$adminId,$adminId); $stmt->execute();
        logAdminAction('grant_cf_access','Granted CF access to '.$uRow['username'].' #'.$uid,$uid);
        setFlash('success','Access granted to '.htmlspecialchars($uRow['username']).'!');
        redirect('chat_spin_admin.php?tab=users');
    }

    // ── Revoke access ─────────────────────────────────────────────────
    if ($action === 'revoke_access') {
        $uid = intval($_POST['user_id']);
        $s = $conn->prepare("UPDATE chat_foreigners_access SET status='revoked',revoked_at=NOW() WHERE user_id=?");
        $s->bind_param("i",$uid); $s->execute();
        logAdminAction('revoke_cf_access','Revoked CF access user #'.$uid,$uid);
        setFlash('success','Access revoked.');
        redirect('chat_spin_admin.php?tab=users');
    }

    // ── STK push spin credit (user pays via M-PESA) ───────────────────
    if ($action === 'credit_spin_stk') {
        $uid   = intval($_POST['user_id'] ?? 0);
        $amt   = floatval($_POST['amount'] ?? 0);
        $phone = trim($_POST['phone'] ?? '');
        if ($uid < 1 || $amt < 1 || empty($phone)) {
            setFlash('error','User, phone and amount are required.');
            redirect('chat_spin_admin.php?tab=spin');
        }
        $phone = lipalink_format_phone($phone);
        if (!lipalink_valid_phone($phone)) {
            setFlash('error','Invalid phone number. Use format 07XXXXXXXX');
            redirect('chat_spin_admin.php?tab=spin');
        }
        $ref        = 'SPIN_CREDIT_' . $uid . '_' . time();
        $spinApiKey = getSetting('spin_api_key','');
        $spinBizId  = getSetting('spin_business_id','');
        if (empty($spinApiKey) || intval($spinBizId) < 1) {
            setFlash('error','Spin gateway not configured. Set Spin API Key & Business ID first.');
            redirect('chat_spin_admin.php?tab=spin');
        }
        $result = lipalink_stk_push($phone, intval($amt), $ref, $spinApiKey, $spinBizId);
        if (!empty($result['success']) && !empty($result['transaction_id'])) {
            $transactionId = $result['transaction_id']; // PFX...
            ensureWalletExists($conn, $uid);
            $desc = "Admin spin top-up via M-PESA: Ksh {$amt}";
            $meta = json_encode(['spin_credit'=>true,'admin_uid'=>$_SESSION['admin_id']??0]);
            $t = $conn->prepare("INSERT INTO transactions
                (user_id,wallet_type,type,amount,description,reference,status,meta_json)
                VALUES (?,'spin','credit',?,?,?,'pending',?)");
            $t->bind_param("idsss",$uid,$amt,$desc,$transactionId,$meta); $t->execute();
            setFlash('success',($result['message']??'STK push sent!') . ' Wallet will be credited on payment.');
        } else {
            setFlash('error','STK failed: '.($result['error']??'Unknown error'));
        }
        redirect('chat_spin_admin.php?tab=spin');
    }

    // ── Free admin credit (no payment) ───────────────────────────────
    if ($action === 'credit_spin_free') {
        $uid = intval($_POST['user_id'] ?? 0);
        $amt = floatval($_POST['amount'] ?? 0);
        if ($uid > 0 && $amt > 0) {
            ensureWalletExists($conn,$uid);
            $s = $conn->prepare("UPDATE wallets SET spin_wallet=COALESCE(spin_wallet,0)+?,balance=COALESCE(balance,0)+?,updated_at=NOW() WHERE user_id=?");
            $s->bind_param("ddi",$amt,$amt,$uid); $s->execute();
            $desc = "Admin free spin credit: Ksh {$amt}";
            $ref  = 'SPIN_FREE_'.$uid.'_'.time();
            $t = $conn->prepare("INSERT INTO transactions (user_id,wallet_type,type,amount,description,reference,status)
                VALUES (?,'spin','credit',?,?,?,'completed')");
            $t->bind_param("idss",$uid,$amt,$desc,$ref); $t->execute();
            setFlash('success',"Credited Ksh {$amt} free to user #{$uid} spin wallet!");
        }
        redirect('chat_spin_admin.php?tab=spin');
    }
}

// ════════════════════════════════════════════════════════════════════
// LipaLink helpers are in ../includes/lipalink.php (already required above)
// Use: lipalink_stk_push(), lipalink_check_status(), lipalink_parse_webhook()
// ════════════════════════════════════════════════════════════════════

// Convenience wrapper for Chat Foreigners (uses its own gateway credentials)
function _cf_stk_push($phone, $amount, $reference) {
    $apiKey = getSetting('chat_foreigners_api_key', '');
    $bizId  = getSetting('chat_foreigners_business_id', '');
    return lipalink_stk_push($phone, $amount, $reference, $apiKey, $bizId);
}

$pageTitle = 'Chat & Spin Settings';
include 'side.php';

// ════════════════════════════════════════════════════════════════════
// LOAD DATA
// ════════════════════════════════════════════════════════════════════
$cfFee       = getSetting('chat_foreigners_unlock_fee','100');
$cfLink      = getSetting('chat_foreigners_redirect_link','');
$cfApiKey    = getSetting('chat_foreigners_api_key','');
$cfBizId     = getSetting('chat_foreigners_business_id','');
$cfCommL1    = getSetting('cf_commission_l1','0');
$cfCommL2    = getSetting('cf_commission_l2','0');
$cfCommL3    = getSetting('cf_commission_l3','0');
$spinApiKey  = getSetting('spin_api_key','');
$spinBizId   = getSetting('spin_business_id','');

$spinRtpRed   = getSetting('spin_rtp_red','48');
$spinRtpBlack = getSetting('spin_rtp_black','48');
$spinRtpEven  = getSetting('spin_rtp_even','47');
$spinRtpOdd   = getSetting('spin_rtp_odd','47');
$spinMinBet   = getSetting('spin_min_bet','10');
$spinMaxBet   = getSetting('spin_max_bet','1000');
$spinMult     = getSetting('spin_win_multiplier','1.9');

$accessUsers = [];
$accessChk = $conn->query("SHOW TABLES LIKE 'chat_foreigners_access'");
if ($accessChk && $accessChk->num_rows > 0) {
    $aRes = $conn->query("SELECT a.*,u.username,u.email,u.phone,u.country
        FROM chat_foreigners_access a JOIN users u ON u.id=a.user_id
        ORDER BY a.granted_at DESC LIMIT 100");
    while ($r = $aRes->fetch_assoc()) $accessUsers[] = $r;
}

$spinStats = [];
$sq = $conn->query("SELECT
    SUM(CASE WHEN type='credit' THEN amount ELSE 0 END) as total_won,
    SUM(CASE WHEN type='debit'  THEN amount ELSE 0 END) as total_lost,
    COUNT(*) as total_spins
    FROM transactions WHERE wallet_type='spin'
    AND created_at >= DATE_SUB(NOW(),INTERVAL 7 DAY)");
if ($sq) $spinStats = $sq->fetch_assoc();

$spinRecent = $conn->query("SELECT t.*,u.username FROM transactions t
    JOIN users u ON u.id=t.user_id WHERE t.wallet_type='spin'
    ORDER BY t.created_at DESC LIMIT 30");

$cfPaymentsQ = null;
$pChk = $conn->query("SHOW TABLES LIKE 'chat_foreigners_payments'");
if ($pChk && $pChk->num_rows > 0) {
    $cfPaymentsQ = $conn->query("SELECT p.*,u.username,u.email
        FROM chat_foreigners_payments p JOIN users u ON u.id=p.user_id
        ORDER BY p.created_at DESC LIMIT 50");
}

// ════════════════════════════════════════════════════════════════════
// EARNINGS DATA
// ════════════════════════════════════════════════════════════════════

// ── Spin earnings: house profit/loss per day (last 14 days) ──────
$spinDaily = $conn->query("
    SELECT DATE(created_at) as day,
        SUM(CASE WHEN type='debit'  THEN amount ELSE 0 END) as house_in,
        SUM(CASE WHEN type='credit' AND description NOT LIKE '%deposit%' THEN amount ELSE 0 END) as house_out,
        COUNT(CASE WHEN type='debit' THEN 1 END) as spins
    FROM transactions
    WHERE wallet_type='spin' AND status='completed'
      AND created_at >= DATE_SUB(NOW(), INTERVAL 14 DAY)
    GROUP BY DATE(created_at)
    ORDER BY day DESC
");
$spinDailyRows = [];
if ($spinDaily) while ($r = $spinDaily->fetch_assoc()) $spinDailyRows[] = $r;

// ── Spin totals all-time ──────────────────────────────────────────
$spinTotals = $conn->query("
    SELECT
        COUNT(CASE WHEN type='debit' THEN 1 END)                                    as total_spins,
        SUM(CASE WHEN type='debit' THEN amount ELSE 0 END)                          as total_bets,
        SUM(CASE WHEN type='credit' AND description NOT LIKE '%deposit%' AND description NOT LIKE '%Admin%' THEN amount ELSE 0 END) as total_payouts,
        SUM(CASE WHEN type='credit' AND description LIKE '%deposit%' THEN amount ELSE 0 END) as total_deposited,
        COUNT(DISTINCT user_id)                                                      as unique_players
    FROM transactions
    WHERE wallet_type='spin' AND status='completed'
");
$spinTotals = $spinTotals ? $spinTotals->fetch_assoc() : [];

// ── Top spin players ──────────────────────────────────────────────
$topSpinPlayers = $conn->query("
    SELECT u.username, u.phone,
        COUNT(CASE WHEN t.type='debit' THEN 1 END) as spins,
        SUM(CASE WHEN t.type='debit' THEN t.amount ELSE 0 END) as total_bet,
        SUM(CASE WHEN t.type='credit' AND t.description NOT LIKE '%deposit%' AND t.description NOT LIKE '%Admin%' THEN t.amount ELSE 0 END) as total_won,
        MAX(t.created_at) as last_spin
    FROM transactions t JOIN users u ON u.id=t.user_id
    WHERE t.wallet_type='spin' AND t.status='completed'
    GROUP BY t.user_id, u.username, u.phone
    ORDER BY total_bet DESC LIMIT 15
");

// ── Chat earnings: revenue from unlock payments ───────────────────
$cfEarnings = ['total_revenue'=>0,'total_payments'=>0,'completed'=>0,'failed'=>0,'pending'=>0];
$cfDailyRows = [];
$cfTopBuyers = null;

$cfTblChk = $conn->query("SHOW TABLES LIKE 'chat_foreigners_payments'");
if ($cfTblChk && $cfTblChk->num_rows > 0) {
    $cfTot = $conn->query("
        SELECT
            COUNT(*) as total_payments,
            SUM(CASE WHEN status='completed' THEN amount ELSE 0 END) as total_revenue,
            SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
            SUM(CASE WHEN status='failed'    THEN 1 ELSE 0 END) as failed,
            SUM(CASE WHEN status='pending'   THEN 1 ELSE 0 END) as pending
        FROM chat_foreigners_payments
    ");
    if ($cfTot) $cfEarnings = $cfTot->fetch_assoc();

    // Daily chat revenue last 14 days
    $cfDaily = $conn->query("
        SELECT DATE(created_at) as day,
            COUNT(*) as payments,
            SUM(CASE WHEN status='completed' THEN amount ELSE 0 END) as revenue,
            SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as successful
        FROM chat_foreigners_payments
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 14 DAY)
        GROUP BY DATE(created_at)
        ORDER BY day DESC
    ");
    if ($cfDaily) while ($r = $cfDaily->fetch_assoc()) $cfDailyRows[] = $r;

    // Top buyers
    $cfTopBuyers = $conn->query("
        SELECT u.username, u.phone, p.amount, p.status, p.created_at,
            DATEDIFF(DATE_ADD(p.created_at, INTERVAL 30 DAY), NOW()) as days_left
        FROM chat_foreigners_payments p JOIN users u ON u.id=p.user_id
        WHERE p.status='completed'
        ORDER BY p.created_at DESC LIMIT 20
    ");
}

// ── Chat task completions + earnings ─────────────────────────────
$chatTaskStats = $conn->query("
    SELECT
        COUNT(*) as total_completions,
        SUM(tc.reward_earned) as total_paid_out,
        COUNT(DISTINCT tc.user_id) as unique_earners
    FROM task_completions tc
    JOIN tasks t ON t.id=tc.task_id
    WHERE t.task_type='chat' AND tc.status='completed'
");
$chatTaskStats = $chatTaskStats ? $chatTaskStats->fetch_assoc() : [];

$flash = getFlash();
?>
<style>
/* ── Tabs ─────────────────────────────────────────────────────────── */
.csa-tabs{display:flex;gap:0;margin-bottom:18px;border-bottom:2px solid var(--border-color);overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none}
.csa-tabs::-webkit-scrollbar{display:none}
.csa-tab{padding:10px 14px;background:none;border:none;border-bottom:3px solid transparent;margin-bottom:-2px;color:var(--text-secondary);font-size:12.5px;font-weight:600;cursor:pointer;transition:all .2s;white-space:nowrap;display:flex;align-items:center;gap:5px;flex-shrink:0}
.csa-tab:hover{color:var(--text-primary)}
.csa-tab.on{color:var(--theme-color);border-bottom-color:var(--theme-color)}
.tab-pane{display:none}.tab-pane.on{display:block}

/* ── Cards ────────────────────────────────────────────────────────── */
.csa-card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:14px;padding:16px;margin-bottom:14px}
@media(min-width:480px){.csa-card{padding:22px;margin-bottom:18px}}
.csa-card-title{font-size:14px;font-weight:700;color:var(--text-primary);margin-bottom:14px;display:flex;align-items:center;gap:8px;flex-wrap:wrap}

/* ── Forms ────────────────────────────────────────────────────────── */
.form-group{margin-bottom:13px}
.form-label{display:block;font-size:12px;font-weight:600;color:var(--text-primary);margin-bottom:5px}
.form-ctrl{width:100%;padding:10px 13px;font-size:13px;border:2px solid var(--border-color);border-radius:9px;background:var(--dark-bg);color:var(--text-primary);transition:.2s;box-sizing:border-box}
.form-ctrl:focus{outline:none;border-color:var(--theme-color)}
.form-hint{font-size:11px;color:var(--text-secondary);margin-top:4px;line-height:1.5}

/* ── Grid ─────────────────────────────────────────────────────────── */
.two-col{display:grid;grid-template-columns:1fr;gap:10px}
@media(min-width:500px){.two-col{grid-template-columns:1fr 1fr}}
.four-col{display:grid;grid-template-columns:1fr 1fr;gap:10px}
@media(min-width:600px){.four-col{grid-template-columns:1fr 1fr 1fr 1fr}}

/* ── Buttons ──────────────────────────────────────────────────────── */
.btn-save{padding:10px 16px;background:linear-gradient(135deg,var(--theme-color),#ec4899);color:#fff;border:none;border-radius:9px;font-size:13px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:6px;transition:.2s;white-space:nowrap}
.btn-save:hover{transform:translateY(-1px);box-shadow:0 4px 14px rgba(0,0,0,.25)}
.btn-green{background:linear-gradient(135deg,#10b981,#059669)!important}
.btn-red  {background:linear-gradient(135deg,#ef4444,#dc2626)!important}
.btn-amber{background:linear-gradient(135deg,#f59e0b,#d97706)!important}
.btn-sm   {padding:6px 11px!important;font-size:11px!important}

/* ── RTP ──────────────────────────────────────────────────────────── */
.rtp-row{display:flex;align-items:center;gap:8px;margin-bottom:12px;flex-wrap:nowrap}
.rtp-label{font-size:11.5px;font-weight:700;min-width:60px;flex-shrink:0;color:var(--text-primary)}
.rtp-slider{flex:1;min-width:80px;height:6px;border-radius:3px;cursor:pointer;accent-color:var(--theme-color)}
.rtp-val{min-width:36px;text-align:right;font-size:13px;font-weight:800;color:var(--theme-color);flex-shrink:0}
.rtp-warn{font-size:11.5px;color:#f59e0b;background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.2);border-radius:9px;padding:10px 12px;margin-bottom:14px;line-height:1.6}

/* ── Stats grid ───────────────────────────────────────────────────── */
.stat-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:14px}
.stat-c{background:var(--card-bg);border:1px solid var(--border-color);border-radius:12px;padding:12px 8px;text-align:center}
.stat-v{font-size:16px;font-weight:800;color:var(--theme-color);line-height:1;word-break:break-all}
.stat-l{font-size:9px;text-transform:uppercase;letter-spacing:.5px;color:var(--text-secondary);margin-top:4px;font-weight:600}

/* ── Tables ───────────────────────────────────────────────────────── */
.tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;border-radius:10px}
.csa-tbl{width:100%;border-collapse:collapse;font-size:12px;min-width:400px}
.csa-tbl th{text-align:left;padding:8px 10px;background:var(--dark-bg);color:var(--text-secondary);font-size:9.5px;text-transform:uppercase;letter-spacing:.6px;font-weight:700;white-space:nowrap}
.csa-tbl td{padding:9px 10px;border-bottom:1px solid var(--border-color);color:var(--text-primary);vertical-align:middle}
.csa-tbl tr:last-child td{border-bottom:none}
.csa-tbl tr:hover td{background:rgba(255,255,255,.02)}

/* ── Badges ───────────────────────────────────────────────────────── */
.badge{display:inline-flex;align-items:center;padding:2px 7px;border-radius:5px;font-size:9.5px;font-weight:700;text-transform:uppercase;white-space:nowrap}
.badge.active   {background:rgba(16,185,129,.15);color:#10b981}
.badge.revoked  {background:rgba(239,68,68,.12);color:#ef4444}
.badge.pending  {background:rgba(245,158,11,.12);color:#f59e0b}
.badge.completed{background:rgba(16,185,129,.12);color:#10b981}
.badge.failed   {background:rgba(239,68,68,.10);color:#ef4444}
.badge.win      {background:rgba(16,185,129,.12);color:#10b981}
.badge.lose     {background:rgba(239,68,68,.10);color:#ef4444}

/* ── User search ──────────────────────────────────────────────────── */
.search-wrap{position:relative;margin-bottom:12px}
.search-inp{width:100%;padding:10px 14px 10px 38px;border:2px solid var(--border-color);border-radius:10px;background:var(--dark-bg);color:var(--text-primary);font-size:13px;outline:none;box-sizing:border-box;transition:.2s}
.search-inp:focus{border-color:var(--theme-color)}
.search-ico{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--text-secondary);font-size:13px;pointer-events:none}
.search-results{position:absolute;left:0;right:0;top:calc(100% + 4px);z-index:9999;background:var(--card-bg);border:1px solid var(--border-color);border-radius:10px;box-shadow:0 12px 32px rgba(0,0,0,.4);max-height:240px;overflow-y:auto;display:none}
.search-result-item{padding:10px 13px;cursor:pointer;border-bottom:1px solid var(--border-color);transition:.15s;display:flex;align-items:center;gap:9px}
.search-result-item:last-child{border-bottom:none}
.search-result-item:hover{background:rgba(255,255,255,.04)}
.sri-avatar{width:32px;height:32px;border-radius:50%;flex-shrink:0;background:linear-gradient(135deg,var(--theme-color),#ec4899);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:800;color:#fff}
.sri-name{font-size:13px;font-weight:700;color:var(--text-primary)}
.sri-meta{font-size:11px;color:var(--text-secondary);margin-top:1px}

/* ── Selected user card ───────────────────────────────────────────── */
.selected-user{display:none;align-items:center;gap:10px;padding:10px 13px;border:2px solid var(--theme-color);border-radius:10px;margin-bottom:12px;background:rgba(0,0,0,.1);flex-wrap:wrap}
.selected-user.show{display:flex}
.su-avatar{width:38px;height:38px;border-radius:50%;flex-shrink:0;background:linear-gradient(135deg,var(--theme-color),#ec4899);display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:800;color:#fff}
.su-info{flex:1;min-width:0}
.su-name{font-size:13px;font-weight:700;color:var(--text-primary)}
.su-meta{font-size:11px;color:var(--text-secondary);margin-top:2px;word-break:break-all}

/* ── Info note ────────────────────────────────────────────────────── */
.info-note{display:flex;align-items:flex-start;gap:8px;padding:10px 12px;border-radius:9px;margin-bottom:14px;background:rgba(99,102,241,.07);border:1px solid rgba(99,102,241,.18);font-size:12px;color:var(--text-secondary);line-height:1.55}
.info-note i{color:#818cf8;flex-shrink:0;margin-top:1px}

/* ── Credit mode tabs ─────────────────────────────────────────────── */
.credit-tabs{display:flex;gap:6px;margin-bottom:14px;flex-wrap:wrap}
.credit-tab{padding:7px 14px;border:2px solid var(--border-color);border-radius:8px;background:none;color:var(--text-secondary);font-size:12px;font-weight:700;cursor:pointer;transition:.2s}
.credit-tab.on{border-color:var(--theme-color);color:var(--theme-color);background:rgba(99,102,241,.07)}
.credit-panel{display:none}.credit-panel.on{display:block}

/* ── Empty state ──────────────────────────────────────────────────── */
.empty-state{text-align:center;padding:30px 20px;color:var(--text-secondary);font-size:13px}
.empty-state i{font-size:26px;opacity:.3;display:block;margin-bottom:10px}
/* ── Section label ────────────────────────────────────────────────── */
.csa-section-lbl{font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.8px;color:var(--text-secondary);margin-bottom:10px;padding-bottom:6px;border-bottom:1px solid var(--border-color)}
/* ── Mono font for credentials ────────────────────────────────────── */
.monofont{font-family:monospace;font-size:12px!important;letter-spacing:.3px}
/* ── Hint colours ─────────────────────────────────────────────────── */
.hint-ok{color:#10b981;font-weight:700}
.hint-err{color:#ef4444;font-weight:700}

/* ── Earnings tab ─────────────────────────────────────────────────── */
.earn-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:16px}
@media(min-width:600px){.earn-grid{grid-template-columns:repeat(4,1fr)}}
.earn-stat{background:var(--card-bg);border:1px solid var(--border-color);border-radius:12px;padding:14px 12px;text-align:center;position:relative;overflow:hidden}
.earn-stat::before{content:'';position:absolute;top:0;left:0;right:0;height:2px}
.earn-stat.green::before{background:linear-gradient(90deg,#10b981,#34d399)}
.earn-stat.red::before{background:linear-gradient(90deg,#ef4444,#f87171)}
.earn-stat.blue::before{background:linear-gradient(90deg,#6366f1,#818cf8)}
.earn-stat.amber::before{background:linear-gradient(90deg,#f59e0b,#fbbf24)}
.earn-stat.purple::before{background:linear-gradient(90deg,#8b5cf6,#a78bfa)}
.earn-val{font-size:20px;font-weight:900;line-height:1;margin-bottom:4px}
.earn-val.green{color:#34d399}.earn-val.red{color:#f87171}
.earn-val.blue{color:#818cf8}.earn-val.amber{color:#fbbf24}.earn-val.purple{color:#a78bfa}
.earn-lbl{font-size:9px;text-transform:uppercase;letter-spacing:.7px;color:var(--text-secondary);font-weight:700}
.earn-sub{font-size:10px;color:var(--text-secondary);margin-top:3px}

/* Daily table */
.daily-tbl{width:100%;border-collapse:collapse;font-size:12px}
.daily-tbl th{text-align:left;padding:7px 10px;font-size:9.5px;text-transform:uppercase;letter-spacing:.5px;color:var(--text-secondary);font-weight:700;background:var(--dark-bg)}
.daily-tbl td{padding:8px 10px;border-bottom:1px solid var(--border-color);vertical-align:middle}
.daily-tbl tr:last-child td{border-bottom:none}
.daily-tbl tr:hover td{background:rgba(255,255,255,.02)}
.profit-bar{height:6px;border-radius:3px;min-width:4px;display:inline-block}

/* Earn section header */
.earn-section{font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:1px;color:var(--text-secondary);margin:18px 0 10px;padding-bottom:6px;border-bottom:1px solid var(--border-color);display:flex;align-items:center;gap:7px}
.earn-section i{color:var(--theme-color)}
</style>

<!-- Page header -->
<div class="page-header" style="margin-bottom:18px">
    <h1 class="page-title" style="font-size:clamp(15px,4vw,21px)">
    <span style="display:inline-flex;align-items:center;gap:8px">
        <i class="fas fa-satellite-dish" style="color:var(--theme-color);font-size:18px"></i>
        Chat &amp; Spin Management
    </span>
</h1>
    <p class="page-subtitle" style="font-size:12px;margin-top:3px">Chat Foreigners &amp; Spin &amp; Win — each with their own M-PESA gateway credentials</p>
</div>

<?php if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?>" style="margin-bottom:14px;font-size:13px;border-radius:10px;display:flex;align-items:center;gap:8px">
    <i class="fas fa-<?= $flash['type']==='success'?'check-circle':'exclamation-triangle' ?>"></i>
    <?= htmlspecialchars($flash['message']) ?>
</div>
<?php endif; ?>

<!-- Tabs -->
<div class="csa-tabs">
    <button class="csa-tab" onclick="switchTab('chat')"><i class="fas fa-globe-africa"></i> Chat</button>
    <button class="csa-tab" onclick="switchTab('spin')"><i class="fas fa-hurricane"></i> Spin</button>
    <button class="csa-tab" onclick="switchTab('users')"><i class="fas fa-users"></i> Access</button>
    <button class="csa-tab" onclick="switchTab('payments')"><i class="fas fa-money-bill-wave"></i> Payments</button>
    <button class="csa-tab" onclick="switchTab('earnings')"><i class="fas fa-chart-line"></i> Earnings</button>
</div>

<!-- ═══════════════════ CHAT TAB ═══════════════════ -->
<div id="tab-chat" class="tab-pane">

    <div class="csa-card">
        <div class="csa-card-title"><i class="fas fa-lock" style="color:var(--theme-color)"></i> Unlock Settings</div>

        <form method="POST">
            <input type="hidden" name="action" value="chat_settings">

            <div class="csa-section-lbl">💳 Payment Gateway (Chat Foreigners Only)</div>
            <div class="two-col">
                <div class="form-group">
                    <label class="form-label">API Key</label>
                    <input type="text" name="chat_foreigners_api_key" class="form-ctrl monofont"
                        value="<?= htmlspecialchars($cfApiKey) ?>" placeholder="e.g. h26524dWWzolI" autocomplete="off">
                    <p class="form-hint">
                        <?php if (!empty($cfApiKey)): ?>
                        <span class="hint-ok">✅ Set (<?= strlen($cfApiKey) ?> chars)</span>
                        <?php else: ?><span class="hint-err">❌ Not configured</span><?php endif; ?>
                    </p>
                </div>
                <div class="form-group">
                    <label class="form-label">Business ID</label>
                    <input type="text" name="chat_foreigners_business_id" class="form-ctrl monofont"
                        value="<?= htmlspecialchars($cfBizId) ?>" placeholder="e.g. 3">
                    <p class="form-hint">
                        <?php if (!empty($cfBizId)): ?>
                        <span class="hint-ok">✅ <?= htmlspecialchars($cfBizId) ?></span>
                        <?php else: ?><span class="hint-err">❌ Not set</span><?php endif; ?>
                    </p>
                </div>
            </div>

            <div class="csa-section-lbl" style="margin-top:4px">⚙️ Unlock Settings</div>
            <div class="two-col">
                <div class="form-group">
                    <label class="form-label">Unlock Fee (Ksh)</label>
                    <input type="number" name="chat_foreigners_unlock_fee" class="form-ctrl"
                        value="<?= htmlspecialchars($cfFee) ?>" min="0" step="10" required>
                    <p class="form-hint">One-time fee for 30-day access</p>
                </div>
                <div class="form-group">
                    <label class="form-label">Post-Payment Redirect URL</label>
                    <input type="url" name="chat_foreigners_redirect_link" class="form-ctrl"
                        value="<?= htmlspecialchars($cfLink) ?>" placeholder="https://…">
                    <p class="form-hint">Optional redirect after payment</p>
                </div>
            </div>
            <div class="csa-section-lbl" style="margin-top:4px">💰 Upline Referral Commission (credited to Chat Wallet)</div>
            <div class="info-note" style="margin-bottom:12px">
                <i class="fas fa-info-circle"></i>
                <div>
                    Fixed <strong>Ksh</strong> amount credited to each upline's <strong>Chat Wallet</strong> when a downline pays the unlock fee.
                    Set to <strong>0</strong> to disable a level. L1 = direct referrer, L2 = their referrer, L3 = one more up.
                </div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:14px">
                <div class="form-group" style="margin-bottom:0">
                    <label class="form-label">Level 1 (Direct) — Ksh</label>
                    <input type="number" name="cf_commission_l1" class="form-ctrl"
                        value="<?= htmlspecialchars($cfCommL1) ?>" min="0" step="1" placeholder="e.g. 50">
                    <p class="form-hint">Goes to direct referrer</p>
                </div>
                <div class="form-group" style="margin-bottom:0">
                    <label class="form-label">Level 2 — Ksh</label>
                    <input type="number" name="cf_commission_l2" class="form-ctrl"
                        value="<?= htmlspecialchars($cfCommL2) ?>" min="0" step="1" placeholder="e.g. 20">
                    <p class="form-hint">Goes to L2 upline</p>
                </div>
                <div class="form-group" style="margin-bottom:0">
                    <label class="form-label">Level 3 — Ksh</label>
                    <input type="number" name="cf_commission_l3" class="form-ctrl"
                        value="<?= htmlspecialchars($cfCommL3) ?>" min="0" step="1" placeholder="e.g. 10">
                    <p class="form-hint">Goes to L3 upline</p>
                </div>
            </div>
            <?php
            $totalComm = floatval($cfCommL1) + floatval($cfCommL2) + floatval($cfCommL3);
            $unlockAmt = floatval($cfFee);
            $remaining = $unlockAmt - $totalComm;
            ?>
            <div class="rtp-warn" style="margin-bottom:14px">
                <i class="fas fa-calculator" style="margin-right:5px"></i>
                Unlock fee: <strong>Ksh <?= number_format($unlockAmt,0) ?></strong>
                &nbsp;·&nbsp; Total commissions: <strong>Ksh <?= number_format($totalComm,0) ?></strong>
                &nbsp;·&nbsp; You keep: <strong style="color:<?= $remaining >= 0 ? '#34d399' : '#f87171' ?>">Ksh <?= number_format($remaining,0) ?></strong>
                <?php if ($totalComm > $unlockAmt): ?><br><span style="color:#ef4444">⚠ Commissions exceed unlock fee!</span><?php endif; ?>
            </div>
            <button type="submit" class="btn-save"><i class="fas fa-save"></i> Save Chat Settings</button>
        </form>
    </div>

    <div class="csa-card">
        <div class="csa-card-title"><i class="fas fa-receipt" style="color:#10b981"></i> Recent Unlock Payments</div>
        <?php if ($cfPaymentsQ && $cfPaymentsQ->num_rows > 0):
            $cfPaymentsQ->data_seek(0); ?>
        <div class="tbl-wrap">
        <table class="csa-tbl">
            <thead><tr><th>User</th><th>Phone</th><th>Amount</th><th>Status</th><th>Date</th></tr></thead>
            <tbody>
            <?php while ($p = $cfPaymentsQ->fetch_assoc()): ?>
            <tr>
                <td><strong><?= htmlspecialchars($p['username']) ?></strong><br>
                    <small style="color:var(--text-secondary)"><?= htmlspecialchars($p['email']) ?></small></td>
                <td style="white-space:nowrap"><?= htmlspecialchars($p['phone']) ?></td>
                <td style="white-space:nowrap">Ksh <?= number_format($p['amount'],2) ?></td>
                <td><span class="badge <?= $p['status'] ?>"><?= strtoupper($p['status']) ?></span></td>
                <td style="white-space:nowrap"><?= date('M j, H:i',strtotime($p['created_at'])) ?></td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
        </div>
        <?php else: ?>
        <div class="empty-state"><i class="fas fa-receipt"></i>No payments yet</div>
        <?php endif; ?>
    </div>
</div>

<!-- ═══════════════════ SPIN TAB ═══════════════════ -->
<div id="tab-spin" class="tab-pane">

    <div class="stat-grid">
        <div class="stat-c">
            <div class="stat-v"><?= number_format(intval($spinStats['total_spins']??0)) ?></div>
            <div class="stat-l">7-Day Spins</div>
        </div>
        <div class="stat-c">
            <div class="stat-v" style="color:#10b981">Ksh&nbsp;<?= number_format($spinStats['total_won']??0) ?></div>
            <div class="stat-l">Won (7d)</div>
        </div>
        <div class="stat-c">
            <div class="stat-v" style="color:#ef4444">Ksh&nbsp;<?= number_format($spinStats['total_lost']??0) ?></div>
            <div class="stat-l">Lost (7d)</div>
        </div>
    </div>

    <div class="csa-card">
        <div class="csa-card-title"><i class="fas fa-sliders" style="color:var(--theme-color)"></i> RTP (Win Probability)</div>
        <div class="rtp-warn">
            <i class="fas fa-exclamation-triangle" style="margin-right:5px"></i>
            <strong>House edge:</strong> 48% RTP ≈ 4% edge. Higher = more user wins.
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="spin_settings">
            <div class="rtp-row">
                <span class="rtp-label" style="color:#fc8181">🔴 Red</span>
                <input type="range" class="rtp-slider" name="spin_rtp_red" min="0" max="95"
                    value="<?= intval($spinRtpRed) ?>" oninput="document.getElementById('rv_red').textContent=this.value+'%'">
                <span class="rtp-val" id="rv_red"><?= intval($spinRtpRed) ?>%</span>
            </div>
            <div class="rtp-row">
                <span class="rtp-label" style="color:rgba(255,255,255,.5)">⚫ Black</span>
                <input type="range" class="rtp-slider" name="spin_rtp_black" min="0" max="95"
                    value="<?= intval($spinRtpBlack) ?>" oninput="document.getElementById('rv_blk').textContent=this.value+'%'">
                <span class="rtp-val" id="rv_blk"><?= intval($spinRtpBlack) ?>%</span>
            </div>
            <div class="rtp-row">
                <span class="rtp-label">EVEN</span>
                <input type="range" class="rtp-slider" name="spin_rtp_even" min="0" max="95"
                    value="<?= intval($spinRtpEven) ?>" oninput="document.getElementById('rv_evn').textContent=this.value+'%'">
                <span class="rtp-val" id="rv_evn"><?= intval($spinRtpEven) ?>%</span>
            </div>
            <div class="rtp-row">
                <span class="rtp-label">ODD</span>
                <input type="range" class="rtp-slider" name="spin_rtp_odd" min="0" max="95"
                    value="<?= intval($spinRtpOdd) ?>" oninput="document.getElementById('rv_odd').textContent=this.value+'%'">
                <span class="rtp-val" id="rv_odd"><?= intval($spinRtpOdd) ?>%</span>
            </div>
            <div class="four-col" style="margin-top:8px">
                <div class="form-group">
                    <label class="form-label">Min Bet (Ksh)</label>
                    <input type="number" name="spin_min_bet" class="form-ctrl" value="<?= htmlspecialchars($spinMinBet) ?>" min="1" step="1">
                </div>
                <div class="form-group">
                    <label class="form-label">Max Bet (Ksh)</label>
                    <input type="number" name="spin_max_bet" class="form-ctrl" value="<?= htmlspecialchars($spinMaxBet) ?>" min="10" step="10">
                </div>
                <div class="form-group" style="grid-column:span 2">
                    <label class="form-label">Win Multiplier (e.g. 1.9)</label>
                    <input type="number" name="spin_win_multiplier" class="form-ctrl" value="<?= htmlspecialchars($spinMult) ?>" min="1.1" max="10" step="0.1">
                    <p class="form-hint">Bet 100 → win <?= floatval($spinMult)*100 ?> at <?= $spinMult ?>x</p>
                </div>
            </div>
            <div class="csa-section-lbl" style="margin-top:18px">💳 Payment Gateway (Spin & Win Only)</div>
            <div class="two-col">
                <div class="form-group">
                    <label class="form-label">API Key</label>
                    <input type="text" name="spin_api_key" class="form-ctrl monofont"
                        value="<?= htmlspecialchars($spinApiKey) ?>" placeholder="e.g. h26524dWWzolI" autocomplete="off">
                    <p class="form-hint">
                        <?php if (!empty($spinApiKey)): ?>
                        <span class="hint-ok">✅ Set (<?= strlen($spinApiKey) ?> chars)</span>
                        <?php else: ?><span class="hint-err">❌ Not configured — STK push will fail</span><?php endif; ?>
                    </p>
                </div>
                <div class="form-group">
                    <label class="form-label">Business ID</label>
                    <input type="text" name="spin_business_id" class="form-ctrl monofont"
                        value="<?= htmlspecialchars($spinBizId) ?>" placeholder="e.g. 3">
                    <p class="form-hint">
                        <?php if (!empty($spinBizId)): ?>
                        <span class="hint-ok">✅ <?= htmlspecialchars($spinBizId) ?></span>
                        <?php else: ?><span class="hint-err">❌ Not set</span><?php endif; ?>
                    </p>
                </div>
            </div>
            <button type="submit" class="btn-save"><i class="fas fa-save"></i> Save Spin Settings</button>
        </form>
    </div>

    <!-- Credit wallet -->
    <div class="csa-card">
        <div class="csa-card-title"><i class="fas fa-coins" style="color:#f59e0b"></i> Credit User Spin Wallet</div>

        <div class="info-note">
            <i class="fas fa-info-circle"></i>
            <div><strong>STK Push</strong> — uses the <em>Spin &amp; Win own gateway</em> credentials set above. Wallet is credited when callback confirms payment. &nbsp;<strong>Free Credit</strong> — credits instantly, no payment needed.</div>
        </div>

        <div class="credit-tabs">
            <button class="credit-tab on" onclick="switchCredit('stk',this)"><i class="fas fa-mobile-alt"></i> STK Push</button>
            <button class="credit-tab" onclick="switchCredit('free',this)"><i class="fas fa-gift"></i> Free Credit</button>
        </div>

        <div id="credit-stk" class="credit-panel on">
            <!-- User search -->
            <div class="search-wrap">
                <i class="fas fa-search search-ico"></i>
                <input type="text" class="search-inp" id="stkUserSearch" autocomplete="off"
                    placeholder="Search user by username, email or phone…"
                    oninput="userSearch(this,'stk')" onkeydown="if(event.key==='Enter')event.preventDefault()">
                <div class="search-results" id="stkSearchResults"></div>
            </div>
            <div class="selected-user" id="stkSelectedUser">
                <div class="su-avatar" id="stkAvatar">?</div>
                <div class="su-info">
                    <div class="su-name" id="stkSelName">—</div>
                    <div class="su-meta" id="stkSelMeta">—</div>
                </div>
                <button type="button" onclick="clearUser('stk')" style="margin-left:auto;background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:18px;line-height:1">×</button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="credit_spin_stk">
                <input type="hidden" name="user_id" id="stkUserId" value="">
                <div class="two-col">
                    <div class="form-group">
                        <label class="form-label">Phone (receives STK prompt)</label>
                        <input type="tel" name="phone" id="stkPhone" class="form-ctrl" placeholder="07XXXXXXXX" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Amount (Ksh)</label>
                        <input type="number" name="amount" class="form-ctrl" placeholder="e.g. 100" min="1" required>
                    </div>
                </div>
                <button type="submit" class="btn-save btn-amber" onclick="return checkUser('stk')">
                    <i class="fas fa-mobile-alt"></i> Send STK Push &amp; Credit
                </button>
            </form>
        </div>

        <div id="credit-free" class="credit-panel">
            <div class="search-wrap">
                <i class="fas fa-search search-ico"></i>
                <input type="text" class="search-inp" id="freeUserSearch" autocomplete="off"
                    placeholder="Search user by username, email or phone…"
                    oninput="userSearch(this,'free')" onkeydown="if(event.key==='Enter')event.preventDefault()">
                <div class="search-results" id="freeSearchResults"></div>
            </div>
            <div class="selected-user" id="freeSelectedUser">
                <div class="su-avatar" id="freeAvatar">?</div>
                <div class="su-info">
                    <div class="su-name" id="freeSelName">—</div>
                    <div class="su-meta" id="freeSelMeta">—</div>
                </div>
                <button type="button" onclick="clearUser('free')" style="margin-left:auto;background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:18px;line-height:1">×</button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="credit_spin_free">
                <input type="hidden" name="user_id" id="freeUserId" value="">
                <div class="form-group" style="max-width:200px">
                    <label class="form-label">Free Amount (Ksh)</label>
                    <input type="number" name="amount" class="form-ctrl" placeholder="e.g. 50" min="1" required>
                </div>
                <button type="submit" class="btn-save btn-green" onclick="return checkUser('free')">
                    <i class="fas fa-gift"></i> Credit for Free
                </button>
            </form>
        </div>
    </div>

    <!-- Recent transactions -->
    <div class="csa-card">
        <div class="csa-card-title"><i class="fas fa-list" style="color:var(--theme-color)"></i> Recent Spin Transactions</div>
        <div class="tbl-wrap">
        <table class="csa-tbl">
            <thead><tr><th>User</th><th>Description</th><th>Ksh</th><th>Type</th><th>Time</th></tr></thead>
            <tbody>
            <?php if ($spinRecent): while ($r = $spinRecent->fetch_assoc()): $w = $r['type']==='credit'; ?>
            <tr>
                <td style="white-space:nowrap"><?= htmlspecialchars($r['username']) ?></td>
                <td style="max-width:160px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?= htmlspecialchars($r['description']) ?></td>
                <td style="white-space:nowrap"><?= number_format($r['amount'],2) ?></td>
                <td><span class="badge <?= $w?'win':'lose' ?>"><?= $w?'WIN':'LOSS' ?></span></td>
                <td style="white-space:nowrap"><?= date('M j H:i',strtotime($r['created_at'])) ?></td>
            </tr>
            <?php endwhile; endif; ?>
            </tbody>
        </table>
        </div>
    </div>
</div>

<!-- ═══════════════════ ACCESS TAB ═══════════════════ -->
<div id="tab-users" class="tab-pane">
    <div class="csa-card">
        <div class="csa-card-title"><i class="fas fa-user-plus" style="color:#10b981"></i> Grant Chat Foreigners Access</div>

        <div class="info-note">
            <i class="fas fa-info-circle"></i>
            <div>Search by <strong>username, email or phone</strong>. Admin-granted access never expires and is completely free for the user.</div>
        </div>

        <div class="search-wrap">
            <i class="fas fa-search search-ico"></i>
            <input type="text" class="search-inp" id="grantUserSearch" autocomplete="off"
                placeholder="Type username, email or phone…"
                oninput="userSearch(this,'grant')" onkeydown="if(event.key==='Enter')event.preventDefault()">
            <div class="search-results" id="grantSearchResults"></div>
        </div>

        <div class="selected-user" id="grantSelectedUser">
            <div class="su-avatar" id="grantAvatar">?</div>
            <div class="su-info">
                <div class="su-name" id="grantSelName">—</div>
                <div class="su-meta" id="grantSelMeta">—</div>
            </div>
            <button type="button" onclick="clearUser('grant')" style="margin-left:auto;background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:18px;line-height:1">×</button>
        </div>

        <form method="POST">
            <input type="hidden" name="action" value="grant_access">
            <input type="hidden" name="user_id" id="grantUserId" value="">
            <button type="submit" class="btn-save btn-green" onclick="return checkUser('grant')">
                <i class="fas fa-unlock"></i> Grant Access
            </button>
        </form>

        <!-- Existing access list -->
        <div style="margin-top:20px;padding-top:16px;border-top:1px solid var(--border-color)">
            <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--text-secondary);margin-bottom:10px">
                Users with Access (<?= count($accessUsers) ?>)
            </div>
            <?php if (empty($accessUsers)): ?>
            <div class="empty-state"><i class="fas fa-users-slash"></i>No users granted access yet</div>
            <?php else: ?>
            <div class="tbl-wrap">
            <table class="csa-tbl">
                <thead><tr><th>User</th><th>Contact</th><th>Status</th><th>Granted</th><th>Action</th></tr></thead>
                <tbody>
                <?php foreach ($accessUsers as $u): ?>
                <tr>
                    <td>
                        <strong><?= htmlspecialchars($u['username']) ?></strong><br>
                        <small style="color:var(--text-secondary)"><?= htmlspecialchars($u['country']??'') ?></small>
                    </td>
                    <td>
                        <small style="color:var(--text-secondary)"><?= htmlspecialchars($u['email']??'') ?></small><br>
                        <small style="color:var(--text-secondary)"><?= htmlspecialchars($u['phone']??'') ?></small>
                    </td>
                    <td><span class="badge <?= $u['status'] ?>"><?= strtoupper($u['status']) ?></span></td>
                    <td style="white-space:nowrap"><?= date('M j, Y',strtotime($u['granted_at'])) ?></td>
                    <td>
                        <?php if ($u['status']==='active'): ?>
                        <form method="POST" onsubmit="return confirm('Revoke <?= htmlspecialchars(addslashes($u['username'])) ?>?')">
                            <input type="hidden" name="action" value="revoke_access">
                            <input type="hidden" name="user_id" value="<?= $u['user_id'] ?>">
                            <button type="submit" class="btn-save btn-red btn-sm"><i class="fas fa-ban"></i> Revoke</button>
                        </form>
                        <?php else: ?>
                        <form method="POST">
                            <input type="hidden" name="action" value="grant_access">
                            <input type="hidden" name="user_id" value="<?= $u['user_id'] ?>">
                            <button type="submit" class="btn-save btn-green btn-sm"><i class="fas fa-unlock"></i> Re-grant</button>
                        </form>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- ═══════════════════ PAYMENTS TAB ═══════════════════ -->
<div id="tab-payments" class="tab-pane">
    <div class="csa-card">
        <div class="csa-card-title"><i class="fas fa-mobile-alt" style="color:#10b981"></i> All Chat Foreigners Payments</div>
        <?php if ($cfPaymentsQ): $cfPaymentsQ->data_seek(0);
            if ($cfPaymentsQ->num_rows > 0): ?>
        <div class="tbl-wrap">
        <table class="csa-tbl">
            <thead><tr><th>User</th><th>Phone</th><th>Amount</th><th>Reference</th><th>Status</th><th>Date</th></tr></thead>
            <tbody>
            <?php while ($p = $cfPaymentsQ->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($p['username']) ?><br><small style="color:var(--text-secondary)">#<?= $p['user_id'] ?></small></td>
                <td style="white-space:nowrap"><?= htmlspecialchars($p['phone']) ?></td>
                <td style="font-weight:700;white-space:nowrap">Ksh <?= number_format($p['amount'],2) ?></td>
                <td><code style="font-size:9px;color:var(--text-secondary);word-break:break-all"><?= htmlspecialchars($p['reference']) ?></code></td>
                <td><span class="badge <?= $p['status'] ?>"><?= strtoupper($p['status']) ?></span></td>
                <td style="white-space:nowrap"><?= date('M j, H:i',strtotime($p['created_at'])) ?></td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
        </div>
        <?php else: ?>
        <div class="empty-state"><i class="fas fa-receipt"></i>No payments yet</div>
        <?php endif; ?>
        <?php else: ?>
        <div class="empty-state"><i class="fas fa-database"></i>Table auto-creates on first payment</div>
        <?php endif; ?>
    </div>
</div>

<!-- ═══════════════════ EARNINGS TAB ═══════════════════ -->
<div id="tab-earnings" class="tab-pane">

    <!-- ── SPIN EARNINGS ── -->
    <div class="earn-section"><i class="fas fa-hurricane"></i> Spin &amp; Win — All-Time</div>

    <div class="earn-grid">
        <div class="earn-stat green">
            <div class="earn-val green">Ksh <?= number_format($spinTotals['total_bets']??0) ?></div>
            <div class="earn-lbl">Total Bets</div>
            <div class="earn-sub"><?= number_format($spinTotals['total_spins']??0) ?> spins</div>
        </div>
        <div class="earn-stat red">
            <div class="earn-val red">Ksh <?= number_format($spinTotals['total_payouts']??0) ?></div>
            <div class="earn-lbl">Total Paid Out</div>
        </div>
        <div class="earn-stat amber">
            <?php
                $spinProfit = ($spinTotals['total_bets']??0) - ($spinTotals['total_payouts']??0);
                $profitClass = $spinProfit >= 0 ? 'green' : 'red';
            ?>
            <div class="earn-val <?= $profitClass ?>">Ksh <?= number_format(abs($spinProfit)) ?></div>
            <div class="earn-lbl">House <?= $spinProfit >= 0 ? 'Profit' : 'Loss' ?></div>
            <?php if (($spinTotals['total_bets']??0) > 0): ?>
            <div class="earn-sub"><?= round($spinProfit/($spinTotals['total_bets']??1)*100,1) ?>% edge</div>
            <?php endif; ?>
        </div>
        <div class="earn-stat blue">
            <div class="earn-val blue">Ksh <?= number_format($spinTotals['total_deposited']??0) ?></div>
            <div class="earn-lbl">Deposited</div>
            <div class="earn-sub"><?= number_format($spinTotals['unique_players']??0) ?> players</div>
        </div>
    </div>

    <div class="csa-card" style="margin-bottom:14px">
        <div class="csa-card-title"><i class="fas fa-calendar-days" style="color:var(--theme-color)"></i> Daily Spin Performance (Last 14 Days)</div>
        <?php if (empty($spinDailyRows)): ?>
        <div class="empty-state"><i class="fas fa-chart-bar"></i>No spin data yet</div>
        <?php else: ?>
        <div class="tbl-wrap">
        <table class="daily-tbl">
            <thead><tr><th>Date</th><th>Spins</th><th>Bets</th><th>Payouts</th><th>Profit</th><th>Bar</th></tr></thead>
            <tbody>
            <?php
            $maxP = max(array_map(fn($r)=>abs(($r['house_in']??0)-($r['house_out']??0)),$spinDailyRows)) ?: 1;
            foreach ($spinDailyRows as $r):
                $p = ($r['house_in']??0) - ($r['house_out']??0);
                $pct = min(100, abs($p)/$maxP*100);
                $isPos = $p >= 0;
            ?>
            <tr>
                <td style="white-space:nowrap;font-weight:600"><?= date('M j',strtotime($r['day'])) ?></td>
                <td><?= number_format($r['spins']??0) ?></td>
                <td>Ksh <?= number_format($r['house_in']??0) ?></td>
                <td>Ksh <?= number_format($r['house_out']??0) ?></td>
                <td style="font-weight:700;color:<?= $isPos?'#34d399':'#f87171' ?>">
                    <?= $isPos?'+':'-' ?>Ksh <?= number_format(abs($p)) ?>
                </td>
                <td>
                    <div class="profit-bar" style="width:<?= max(4,round($pct)) ?>px;background:<?= $isPos?'#34d399':'#f87171' ?>"></div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>

    <div class="csa-card" style="margin-bottom:18px">
        <div class="csa-card-title"><i class="fas fa-trophy" style="color:#f59e0b"></i> Top Spin Players</div>
        <?php if (!$topSpinPlayers || $topSpinPlayers->num_rows === 0): ?>
        <div class="empty-state"><i class="fas fa-users"></i>No players yet</div>
        <?php else: ?>
        <div class="tbl-wrap">
        <table class="daily-tbl">
            <thead><tr><th>Player</th><th>Spins</th><th>Total Bet</th><th>Total Won</th><th>Net (House)</th><th>Last Spin</th></tr></thead>
            <tbody>
            <?php while ($r = $topSpinPlayers->fetch_assoc()):
                $net = ($r['total_bet']??0) - ($r['total_won']??0);
            ?>
            <tr>
                <td>
                    <strong><?= htmlspecialchars($r['username']) ?></strong><br>
                    <small style="color:var(--text-secondary)"><?= htmlspecialchars($r['phone']??'') ?></small>
                </td>
                <td><?= number_format($r['spins']??0) ?></td>
                <td>Ksh <?= number_format($r['total_bet']??0) ?></td>
                <td>Ksh <?= number_format($r['total_won']??0) ?></td>
                <td style="font-weight:700;color:<?= $net>=0?'#34d399':'#f87171' ?>">
                    <?= $net>=0?'+':'' ?>Ksh <?= number_format($net) ?>
                </td>
                <td style="white-space:nowrap;color:var(--text-secondary);font-size:11px"><?= date('M j H:i',strtotime($r['last_spin'])) ?></td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>

    <!-- ── CHAT FOREIGNERS EARNINGS ── -->
    <div class="earn-section"><i class="fas fa-satellite-dish"></i> Chat Foreigners — Unlock Revenue</div>

    <div class="earn-grid">
        <div class="earn-stat green">
            <div class="earn-val green">Ksh <?= number_format($cfEarnings['total_revenue']??0) ?></div>
            <div class="earn-lbl">Total Revenue</div>
            <div class="earn-sub"><?= number_format($cfEarnings['completed']??0) ?> payments</div>
        </div>
        <div class="earn-stat blue">
            <div class="earn-val blue"><?= number_format($cfEarnings['total_payments']??0) ?></div>
            <div class="earn-lbl">Total Attempts</div>
        </div>
        <div class="earn-stat red">
            <div class="earn-val red"><?= number_format($cfEarnings['failed']??0) ?></div>
            <div class="earn-lbl">Failed</div>
        </div>
        <div class="earn-stat amber">
            <div class="earn-val amber"><?= number_format($cfEarnings['pending']??0) ?></div>
            <div class="earn-lbl">Pending</div>
        </div>
    </div>

    <?php if (!empty($cfDailyRows)): ?>
    <div class="csa-card" style="margin-bottom:14px">
        <div class="csa-card-title"><i class="fas fa-calendar-days" style="color:#10b981"></i> Daily Chat Revenue (Last 14 Days)</div>
        <div class="tbl-wrap">
        <table class="daily-tbl">
            <thead><tr><th>Date</th><th>Attempts</th><th>Successful</th><th>Revenue</th><th>Bar</th></tr></thead>
            <tbody>
            <?php
            $maxRev = max(array_map(fn($r)=>$r['revenue']??0,$cfDailyRows)) ?: 1;
            foreach ($cfDailyRows as $r):
                $pct = min(100, ($r['revenue']??0)/$maxRev*100);
            ?>
            <tr>
                <td style="white-space:nowrap;font-weight:600"><?= date('M j',strtotime($r['day'])) ?></td>
                <td><?= number_format($r['payments']??0) ?></td>
                <td style="color:#34d399;font-weight:600"><?= number_format($r['successful']??0) ?></td>
                <td style="font-weight:700;color:#34d399">Ksh <?= number_format($r['revenue']??0) ?></td>
                <td>
                    <div class="profit-bar" style="width:<?= max(4,round($pct)) ?>px;background:#34d399"></div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($chatTaskStats['total_completions'])): ?>
    <div class="csa-card" style="margin-bottom:14px">
        <div class="csa-card-title"><i class="fas fa-comments" style="color:#6366f1"></i> Chat Task Completions</div>
        <div class="earn-grid" style="grid-template-columns:repeat(3,1fr)">
            <div class="earn-stat purple">
                <div class="earn-val purple"><?= number_format($chatTaskStats['total_completions']??0) ?></div>
                <div class="earn-lbl">Total Sessions</div>
            </div>
            <div class="earn-stat red">
                <div class="earn-val red">Ksh <?= number_format($chatTaskStats['total_paid_out']??0) ?></div>
                <div class="earn-lbl">Paid to Users</div>
            </div>
            <div class="earn-stat blue">
                <div class="earn-val blue"><?= number_format($chatTaskStats['unique_earners']??0) ?></div>
                <div class="earn-lbl">Unique Earners</div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($cfTopBuyers && $cfTopBuyers->num_rows > 0): ?>
    <div class="csa-card" style="margin-bottom:18px">
        <div class="csa-card-title"><i class="fas fa-users" style="color:#10b981"></i> Recent Paying Users</div>
        <div class="tbl-wrap">
        <table class="daily-tbl">
            <thead><tr><th>User</th><th>Phone</th><th>Paid</th><th>Access</th><th>Date</th></tr></thead>
            <tbody>
            <?php while ($r = $cfTopBuyers->fetch_assoc()): ?>
            <tr>
                <td><strong><?= htmlspecialchars($r['username']) ?></strong></td>
                <td style="white-space:nowrap"><?= htmlspecialchars($r['phone']??'') ?></td>
                <td style="font-weight:700;color:#34d399">Ksh <?= number_format($r['amount'],2) ?></td>
                <td>
                    <?php if (($r['days_left']??0) > 0): ?>
                    <span style="color:#fbbf24;font-size:11px;font-weight:600"><?= intval($r['days_left']) ?>d left</span>
                    <?php else: ?>
                    <span style="color:#f87171;font-size:11px">Expired</span>
                    <?php endif; ?>
                </td>
                <td style="white-space:nowrap;color:var(--text-secondary);font-size:11px"><?= date('M j, Y',strtotime($r['created_at'])) ?></td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
        </div>
    </div>
    <?php endif; ?>

</div><!-- /#tab-earnings -->

<script>
// ── Tab switching ─────────────────────────────────────────────────────────
var VALID=['chat','spin','users','payments','earnings'];
function switchTab(t){
    if(!VALID.includes(t))t='chat';
    document.querySelectorAll('.tab-pane').forEach(p=>p.classList.remove('on'));
    document.querySelectorAll('.csa-tab').forEach(b=>b.classList.remove('on'));
    var p=document.getElementById('tab-'+t);if(p)p.classList.add('on');
    document.querySelectorAll('.csa-tab').forEach(b=>{
        if(b.getAttribute('onclick')&&b.getAttribute('onclick').includes("'"+t+"'"))b.classList.add('on');
    });
    history.replaceState(null,'','?tab='+t);
}
switchTab('<?= in_array($activeTab,['chat','spin','users','payments'])?htmlspecialchars($activeTab):'chat' ?>');

// ── Credit sub-tabs ───────────────────────────────────────────────────────
function switchCredit(t,btn){
    document.querySelectorAll('.credit-tab').forEach(b=>b.classList.remove('on'));
    document.querySelectorAll('.credit-panel').forEach(p=>p.classList.remove('on'));
    if(btn) btn.classList.add('on');
    var panel=document.getElementById('credit-'+t);
    if(panel) panel.classList.add('on');
}

// ── User search ───────────────────────────────────────────────────────────
var _timers={},_sel={};
function userSearch(inp,ctx){
    var q=inp.value.trim();
    var box=document.getElementById(ctx+'SearchResults');
    if(!box) return;
    clearTimeout(_timers[ctx]);
    if(q.length<2){box.style.display='none';return;}
    _timers[ctx]=setTimeout(function(){
        // Use URLSearchParams so PHP reads $_POST cleanly
        var params=new URLSearchParams();
        params.append('action','search_user');
        params.append('query',q);
        fetch('chat_spin_admin.php',{
            method:'POST',
            headers:{'Content-Type':'application/x-www-form-urlencoded'},
            body:params.toString()
        })
        .then(function(r){
            if(!r.ok) throw new Error('HTTP '+r.status);
            return r.json();
        })
        .then(function(rows){
            box.innerHTML='';
            if(!rows||!rows.length){box.style.display='none';return;}
            rows.forEach(function(u){
                var d=document.createElement('div');
                d.className='search-result-item';
                d.innerHTML=
                    '<div class="sri-avatar">'+e(u.username).charAt(0).toUpperCase()+'</div>'+
                    '<div>'+
                      '<div class="sri-name">'+e(u.username)+'</div>'+
                      '<div class="sri-meta">'+
                        e(u.email||'')+
                        (u.phone?' &middot; '+e(u.phone):'')+
                        (u.country?' &middot; '+e(u.country):'')+
                      '</div>'+
                    '</div>';
                d.onclick=function(){ selectUser(ctx,u); };
                box.appendChild(d);
            });
            box.style.display='block';
        })
        .catch(function(err){
            console.warn('Search error:',err);
            box.style.display='none';
        });
    },300);
}

function selectUser(ctx,u){
    _sel[ctx]=u;
    document.getElementById(ctx+'SearchResults').style.display='none';
    document.getElementById(ctx+'UserSearch').value='';
    var card=document.getElementById(ctx+'SelectedUser');
    card.classList.add('show');
    document.getElementById(ctx+'Avatar').textContent=u.username.charAt(0).toUpperCase();
    document.getElementById(ctx+'SelName').textContent=u.username+' (#'+u.id+')';
    document.getElementById(ctx+'SelMeta').textContent=(u.email||'')+(u.phone?' · '+u.phone:'')+(u.country?' · '+u.country:'');
    document.getElementById(ctx+'UserId').value=u.id;
    if(ctx==='stk'&&u.phone){var ph=document.getElementById('stkPhone');if(ph&&!ph.value)ph.value=u.phone;}
}

function clearUser(ctx){
    _sel[ctx]=null;
    document.getElementById(ctx+'SelectedUser').classList.remove('show');
    document.getElementById(ctx+'UserId').value='';
    document.getElementById(ctx+'UserSearch').value='';
    if(ctx==='stk'){var ph=document.getElementById('stkPhone');if(ph)ph.value='';}
}

function checkUser(ctx){
    if(!document.getElementById(ctx+'UserId').value){
        alert('Please search and select a user first.');return false;
    }return true;
}

function e(s){return s?(s+'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'):''}

// Close search on outside click
document.addEventListener('click',function(ev){
    document.querySelectorAll('.search-results').forEach(function(el){
        if(!el.closest('.search-wrap').contains(ev.target))el.style.display='none';
    });
});
</script>
<?php include 'footer.php'; ?>