<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Wallet Withdrawal Settings';
include 'side.php';
require_once 'admin_protect.php';

$conn = getConnection();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'update_wallets') {
        $submittedWallets = $_POST['wallet_types'] ?? [];
        $conn->query("UPDATE wallet_withdrawal_settings SET status = 'disabled'");
        $stmt = $conn->prepare("INSERT INTO wallet_withdrawal_settings (wallet_type, status) VALUES (?, 'enabled') ON DUPLICATE KEY UPDATE status = 'enabled'");
        foreach ($submittedWallets as $walletType) {
            $stmt->bind_param("s", $walletType);
            $stmt->execute();
        }
        setFlash('success', 'Wallet withdrawal settings updated successfully!');
        header('Location: ' . $_SERVER['PHP_SELF']); exit;
    }
}

/*
 * WALLET TYPE DEFINITIONS
 * ─────────────────────────────────────────────────────────────
 *  DB column         | Display label
 * ─────────────────────────────────────────────────────────────
 *  main_wallet       | Store Wallet  (digital product commissions)
 *  referral_wallet   | Affiliate Wallet (referral / activation commissions)
 * ─────────────────────────────────────────────────────────────
 */
$walletTypes = [
    'main_wallet'          => [
        'name'  => 'Store Wallet',
        'icon'  => 'fa-store',
        'color' => '#10b981',
        'desc'  => 'Commissions earned when your downlines purchase digital products from the store',
    ],
    'referral_wallet'      => [
        'name'  => 'Affiliate Wallet',
        'icon'  => 'fa-share-alt',
        'color' => '#5B77F5',
        'desc'  => 'Earnings from referral commissions on account activations',
    ],
    'bonus_wallet'         => [
        'name'  => 'Bonus Wallet',
        'icon'  => 'fa-gift',
        'color' => '#f59e0b',
        'desc'  => 'Welcome bonuses and promotional rewards',
    ],
    'video_wallet'         => [
        'name'  => 'Video Wallet',
        'icon'  => 'fa-video',
        'color' => '#f97316',
        'desc'  => 'Earnings from watching videos',
    ],
    'trivia_wallet'        => [
        'name'  => 'Trivia Wallet',
        'icon'  => 'fa-question-circle',
        'color' => '#ec4899',
        'desc'  => 'Rewards from trivia questions',
    ],
    'survey_wallet'        => [
        'name'  => 'Survey Wallet',
        'icon'  => 'fa-poll',
        'color' => '#06b6d4',
        'desc'  => 'Earnings from completing surveys',
    ],
    'ads_wallet'           => [
        'name'  => 'Ads Wallet',
        'icon'  => 'fa-ad',
        'color' => '#8b5cf6',
        'desc'  => 'Revenue from viewing advertisements',
    ],
    'spin_wallet'          => [
        'name'  => 'Spin Wallet',
        'icon'  => 'fa-spinner',
        'color' => '#14b8a6',
        'desc'  => 'Winnings from the spin wheel game',
    ],
    'blog_wallet'          => [
        'name'  => 'Blog Wallet',
        'icon'  => 'fa-blog',
        'color' => '#f97316',
        'desc'  => 'Earnings from blog activities',
    ],
    'meme_wallet'          => [
        'name'  => 'Meme Wallet',
        'icon'  => 'fa-images',
        'color' => '#e11d48',
        'desc'  => 'Rewards from meme contests',
    ],
    'chat_wallet'          => [
        'name'  => 'Chat Wallet',
        'icon'  => 'fa-comments',
        'color' => '#3b82f6',
        'desc'  => 'Earnings from chat tasks',
    ],
    'transcription_wallet' => [
        'name'  => 'Transcription Wallet',
        'icon'  => 'fa-keyboard',
        'color' => '#10b981',
        'desc'  => 'Earnings from transcription tasks',
    ],
];

$settingsQuery = $conn->query("SELECT * FROM wallet_withdrawal_settings");
$currentSettings = [];
if ($settingsQuery) {
    while ($s = $settingsQuery->fetch_assoc()) $currentSettings[$s['wallet_type']] = $s['status'];
}
if (empty($currentSettings)) {
    foreach (array_keys($walletTypes) as $t) $currentSettings[$t] = 'enabled';
}

$walletStats = [];
foreach (array_keys($walletTypes) as $type) {
    $q = $conn->query("SELECT COUNT(*) as user_count, COALESCE(SUM(`$type`),0) as total_balance FROM wallets WHERE `$type` > 0");
    $walletStats[$type] = $q ? $q->fetch_assoc() : ['user_count'=>0,'total_balance'=>0];
}
?>
<style>
.settings-container{max-width:1400px;margin:0 auto;padding:20px}
.page-header{margin-bottom:32px}
.page-title{font-size:28px;font-weight:900;color:var(--text-primary);margin-bottom:8px;display:flex;align-items:center;gap:12px}
.page-subtitle{font-size:14px;color:var(--text-secondary)}
.info-banner{background:rgba(59,130,246,.1);border:1px solid #3b82f6;border-radius:12px;padding:20px;margin-bottom:24px;display:flex;gap:16px}
.info-banner i{font-size:24px;color:#3b82f6;flex-shrink:0}
.info-content h3{font-size:16px;font-weight:700;color:#3b82f6;margin-bottom:8px}
.info-content p{font-size:14px;color:var(--text-primary);line-height:1.6}
.quick-actions{display:flex;gap:12px;margin-bottom:24px;flex-wrap:wrap}
.quick-btn{padding:10px 20px;border:2px solid var(--border-color);border-radius:8px;background:var(--card-bg);color:var(--text-primary);font-size:13px;font-weight:600;cursor:pointer;transition:all .3s;display:flex;align-items:center;gap:8px}
.quick-btn:hover{border-color:var(--theme-color);background:var(--darker-bg)}

/* WALLET GRID */
.wallets-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:20px;margin-bottom:32px}
.wallet-card{background:var(--card-bg);border:2px solid var(--border-color);border-radius:16px;padding:20px;transition:all .3s ease;cursor:pointer;position:relative}
.wallet-card:hover{transform:translateY(-4px);box-shadow:0 12px 24px rgba(0,0,0,.1)}
.wallet-card.enabled{border-color:rgba(16,185,129,.5);background:rgba(16,185,129,.04)}
.wallet-card.disabled{border-color:rgba(239,68,68,.4);background:rgba(239,68,68,.04);opacity:.75}
.wallet-card.featured{border-width:3px}

.wallet-header{display:flex;align-items:center;gap:12px;margin-bottom:16px;padding-right:60px}
.wallet-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;color:#fff;flex-shrink:0}
.wallet-name{font-size:15px;font-weight:700;color:var(--text-primary);margin-bottom:3px;display:flex;align-items:center;gap:6px;flex-wrap:wrap}
.wallet-type-tag{font-size:11px;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.5px;font-family:monospace}

/* Badge pills */
.wpill{display:inline-block;font-size:9px;font-weight:800;padding:2px 7px;border-radius:5px;text-transform:uppercase;vertical-align:middle;letter-spacing:.4px}
.wpill-store{background:rgba(16,185,129,.15);color:#10b981;border:1px solid rgba(16,185,129,.3)}
.wpill-aff{background:rgba(91,119,245,.15);color:#5B77F5;border:1px solid rgba(91,119,245,.3)}

/* Toggle */
.wallet-toggle{position:absolute;top:20px;right:20px}
.wallet-toggle input[type="checkbox"]{width:48px;height:24px;position:relative;appearance:none;background:#ef4444;border-radius:12px;cursor:pointer;transition:all .3s ease}
.wallet-toggle input[type="checkbox"]:checked{background:#10b981}
.wallet-toggle input[type="checkbox"]::before{content:'';position:absolute;width:18px;height:18px;border-radius:50%;background:white;top:3px;left:3px;transition:all .3s ease;box-shadow:0 1px 4px rgba(0,0,0,.2)}
.wallet-toggle input[type="checkbox"]:checked::before{left:27px}

.wallet-status{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600;padding:8px 0}
.status-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}
.status-dot.enabled{background:#10b981;box-shadow:0 0 8px rgba(16,185,129,.5)}
.status-dot.disabled{background:#ef4444}

.wallet-stats{display:grid;grid-template-columns:1fr 1fr;gap:10px;padding-top:12px;border-top:1px solid var(--border-color);margin-top:10px}
.stat-item{background:var(--darker-bg);padding:10px;border-radius:8px}
.stat-label{font-size:10px;color:var(--text-secondary);text-transform:uppercase;margin-bottom:4px;letter-spacing:.3px}
.stat-value{font-size:16px;font-weight:800;color:var(--text-primary)}
.wallet-desc{font-size:12.5px;color:var(--text-secondary);line-height:1.6;margin-top:10px;padding-top:10px;border-top:1px solid var(--border-color)}

/* Action buttons */
.action-buttons{display:flex;gap:16px;justify-content:center}
.btn{padding:14px 32px;border:none;border-radius:10px;font-size:15px;font-weight:700;cursor:pointer;transition:all .3s ease;display:inline-flex;align-items:center;gap:10px}
.btn-primary{background:linear-gradient(135deg,var(--theme-color),#ec4899);color:white}
.btn-primary:hover{transform:translateY(-2px);box-shadow:0 8px 24px rgba(var(--theme-rgb),.4)}
.btn-secondary{background:var(--darker-bg);border:2px solid var(--border-color);color:var(--text-primary)}

@media(max-width:768px){
    .settings-container{padding:12px}
    .wallets-grid{grid-template-columns:1fr}
    .action-buttons{flex-direction:column}
    .btn{width:100%;justify-content:center}
}
</style>

<div class="settings-container">
    <div class="page-header">
        <h1 class="page-title"><i class="fas fa-wallet"></i> Wallet Withdrawal Settings</h1>
        <p class="page-subtitle">Control which wallets users can withdraw from. Toggle each wallet on or off to enable or disable withdrawals.</p>
    </div>

    <div class="info-banner">
        <i class="fas fa-info-circle"></i>
        <div class="info-content">
            <h3>Wallet Guide</h3>
            <p>
                <strong>Store Wallet</strong> (<code>main_wallet</code>) — credited when downlines purchase digital products from the store.<br>
                <strong>Affiliate Wallet</strong> (<code>referral_wallet</code>) — credited when referred users activate their accounts.<br>
                Enable both to allow users to withdraw store earnings and referral bonuses separately.
            </p>
        </div>
    </div>

    <div class="quick-actions">
        <button class="quick-btn" onclick="enableAll()">
            <i class="fas fa-check-double"></i> Enable All
        </button>
        <button class="quick-btn" onclick="disableAll()">
            <i class="fas fa-times"></i> Disable All
        </button>
        <button class="quick-btn" onclick="enableTask()">
            <i class="fas fa-tasks"></i> Task Wallets Only
        </button>
        <button class="quick-btn" onclick="enableEarnings()" style="border-color:#10b981;color:#10b981">
            <i class="fas fa-coins"></i> Store + Affiliate
        </button>
    </div>

    <form method="POST" id="walletSettingsForm">
        <input type="hidden" name="action" value="update_wallets">
        <div class="wallets-grid">
            <?php foreach ($walletTypes as $type => $info):
                $isEnabled  = ($currentSettings[$type] ?? 'enabled') === 'enabled';
                $stats      = $walletStats[$type] ?? ['user_count'=>0,'total_balance'=>0];
                $isStore     = ($type === 'main_wallet');
                $isAffiliate = ($type === 'referral_wallet');
            ?>
            <div class="wallet-card <?php echo $isEnabled ? 'enabled' : 'disabled'; ?> <?php echo ($isStore || $isAffiliate) ? 'featured' : ''; ?>"
                 onclick="toggleWallet('<?php echo $type; ?>')">

                <div class="wallet-toggle">
                    <input type="checkbox"
                           name="wallet_types[]"
                           value="<?php echo $type; ?>"
                           id="wallet_<?php echo $type; ?>"
                           <?php echo $isEnabled ? 'checked' : ''; ?>
                           onclick="event.stopPropagation()">
                </div>

                <div class="wallet-header">
                    <div class="wallet-icon" style="background:<?php echo $info['color']; ?>">
                        <i class="fas <?php echo $info['icon']; ?>"></i>
                    </div>
                    <div>
                        <div class="wallet-name">
                            <?php echo htmlspecialchars($info['name']); ?>
                            <?php if ($isStore): ?>
                                <span class="wpill wpill-store">Store</span>
                            <?php elseif ($isAffiliate): ?>
                                <span class="wpill wpill-aff">Affiliate</span>
                            <?php endif; ?>
                        </div>
                        <div class="wallet-type-tag"><?php echo $type; ?></div>
                    </div>
                </div>

                <div class="wallet-status">
                    <span class="status-dot <?php echo $isEnabled ? 'enabled' : 'disabled'; ?>"></span>
                    <span><?php echo $isEnabled ? 'Withdrawals Enabled' : 'Withdrawals Disabled'; ?></span>
                </div>

                <div class="wallet-stats">
                    <div class="stat-item">
                        <div class="stat-label">Users with balance</div>
                        <div class="stat-value"><?php echo number_format($stats['user_count']); ?></div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">Total Balance</div>
                        <div class="stat-value">KSH <?php echo number_format($stats['total_balance'], 2); ?></div>
                    </div>
                </div>

                <div class="wallet-desc"><?php echo htmlspecialchars($info['desc']); ?></div>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="action-buttons">
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-save"></i> Save Settings
            </button>
            <button type="button" class="btn btn-secondary" onclick="window.location.reload()">
                <i class="fas fa-undo"></i> Reset
            </button>
        </div>
    </form>
</div>

<script>
function toggleWallet(type) {
    var cb = document.getElementById('wallet_' + type);
    cb.checked = !cb.checked;
    updateCard(cb.closest('.wallet-card'), cb);
}

function updateCard(card, cb) {
    var on = cb.checked;
    card.classList.toggle('enabled',  on);
    card.classList.toggle('disabled', !on);
    card.querySelector('.status-dot').className       = 'status-dot ' + (on ? 'enabled' : 'disabled');
    card.querySelector('.wallet-status span:last-child').textContent = on ? 'Withdrawals Enabled' : 'Withdrawals Disabled';
}

function enableAll() {
    document.querySelectorAll('input[name="wallet_types[]"]').forEach(function(cb) {
        cb.checked = true; updateCard(cb.closest('.wallet-card'), cb);
    });
}

function disableAll() {
    document.querySelectorAll('input[name="wallet_types[]"]').forEach(function(cb) {
        cb.checked = false; updateCard(cb.closest('.wallet-card'), cb);
    });
}

/* Task wallets only — excludes store and affiliate */
function enableTask() {
    var task = ['video_wallet','survey_wallet','trivia_wallet','chat_wallet',
                'transcription_wallet','ads_wallet','spin_wallet','blog_wallet','meme_wallet'];
    document.querySelectorAll('input[name="wallet_types[]"]').forEach(function(cb) {
        cb.checked = task.includes(cb.value);
        updateCard(cb.closest('.wallet-card'), cb);
    });
}

/* Store Wallet (main_wallet) + Affiliate Wallet (referral_wallet) */
function enableEarnings() {
    var earn = ['main_wallet', 'referral_wallet'];
    document.querySelectorAll('input[name="wallet_types[]"]').forEach(function(cb) {
        cb.checked = earn.includes(cb.value);
        updateCard(cb.closest('.wallet-card'), cb);
    });
}
</script>

<?php include 'footer.php'; ?>