<?php
require_once '../config/db.php';
require_once 'layout.php';

// OVERRIDE: Admin panel needs HTML
header('Content-Type: text/html; charset=utf-8');

// Handle Post Actions (Withdrawal Status Update)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['id'])) {
    if ($_POST['action'] === 'update_withdrawal') {
        $wid = (int)$_POST['id'];
        $status = $_POST['status'];
        $pdo->prepare("UPDATE withdrawals SET status = ? WHERE id = ?")->execute([$status, $wid]);
    } elseif ($_POST['action'] === 'save_gateway') {
        $provider = $_POST['provider'];
        $key = $_POST['api_key'];
        $secret = $_POST['secret_key'];
        $active = isset($_POST['is_active']) ? 1 : 0;
        
        // Upsert logic
        $stmt = $pdo->prepare("SELECT id FROM payment_gateways WHERE provider = ?");
        $stmt->execute([$provider]);
        if ($stmt->fetch()) {
             $pdo->prepare("UPDATE payment_gateways SET api_key = ?, secret_key = ?, is_active = ? WHERE provider = ?")
                 ->execute([$key, $secret, $active, $provider]);
        } else {
             $pdo->prepare("INSERT INTO payment_gateways (provider, api_key, secret_key, is_active) VALUES (?, ?, ?, ?)")
                 ->execute([$provider, $key, $secret, $active]);
        }
    }
    echo "<script>window.location.href='payments.php';</script>";
    exit;
}

// Fetch Data
try {
    // Withdrawals
    $withdrawals = $pdo->query("SELECT w.*, u.username, u.email FROM withdrawals w JOIN users u ON w.user_id = u.id ORDER BY w.created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
    
    // Gateways
    $gateways = $pdo->query("SELECT * FROM payment_gateways")->fetchAll(PDO::FETCH_ASSOC);
    // Index by provider for easier access
    $gw_config = [];
    foreach ($gateways as $g) $gw_config[$g['provider']] = $g;

} catch (PDOException $e) {
    die("Error DB: " . $e->getMessage());
}

renderAdminSidebar('payments');
?>

<div class="flex flex-col h-[calc(100vh-140px)]">
    <!-- Header -->
    <div class="mb-6">
        <h2 class="text-3xl font-bold text-white tracking-tight">Finanzas & Pagos</h2>
        <p class="text-gray-400 mt-1">Gestiona solicitudes de retiro y configura pasarelas de pago.</p>
    </div>

    <!-- Main Content -->
    <div class="flex-1 bg-dark-800 rounded-2xl border border-dark-700 shadow-xl overflow-hidden flex flex-col">
        <!-- Tabs -->
        <div class="flex border-b border-dark-700 bg-dark-900/50">
            <button onclick="switchTab('withdrawals')" id="tab-withdrawals" class="px-6 py-4 text-sm font-bold text-brand-500 border-b-2 border-brand-500 bg-dark-800 transition">
                <i class="fas fa-hand-holding-usd mr-2"></i> Solicitudes de Retiro
            </button>
            <button onclick="switchTab('gateways')" id="tab-gateways" class="px-6 py-4 text-sm font-medium text-gray-400 hover:text-white hover:bg-dark-800 transition border-b-2 border-transparent">
                <i class="fas fa-credit-card mr-2"></i> Pasarelas de Pago
            </button>
        </div>

        <!-- Content: Withdrawals -->
        <div id="content-withdrawals" class="flex-1 overflow-y-auto">
             <table class="w-full text-left text-sm text-gray-400">
                <thead class="bg-dark-900 text-gray-200 font-medium uppercase text-xs sticky top-0">
                    <tr>
                        <th class="px-6 py-4">ID</th>
                        <th class="px-6 py-4">Usuario</th>
                        <th class="px-6 py-4">Monto (USD)</th>
                        <th class="px-6 py-4">Método</th>
                        <th class="px-6 py-4">Estado</th>
                        <th class="px-6 py-4 text-right">Acción</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-dark-700">
                    <?php foreach ($withdrawals as $w): ?>
                    <tr class="hover:bg-dark-700/50 transition">
                        <td class="px-6 py-4">#<?php echo $w['id']; ?></td>
                        <td class="px-6 py-4">
                            <span class="block text-white font-bold"><?php echo htmlspecialchars($w['username']); ?></span>
                            <span class="text-xs"><?php echo htmlspecialchars($w['email']); ?></span>
                        </td>
                        <td class="px-6 py-4 text-green-400 font-bold">$<?php echo number_format($w['payout_amount'], 2); ?></td>
                        <td class="px-6 py-4 uppercase text-xs font-bold"><?php echo htmlspecialchars($w['method']); ?></td>
                        <td class="px-6 py-4">
                            <?php 
                            $colors = ['pending' => 'yellow', 'approved' => 'blue', 'completed' => 'green', 'rejected' => 'red'];
                            $c = $colors[$w['status']] ?? 'gray';
                            ?>
                            <span class="px-2 py-0.5 rounded-full bg-<?php echo $c; ?>-500/20 text-<?php echo $c; ?>-400 border border-<?php echo $c; ?>-500/30 text-[10px] uppercase font-bold">
                                <?php echo $w['status']; ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-right">
                             <?php if ($w['status'] === 'pending'): ?>
                             <div class="flex justify-end gap-2">
                                <form method="POST">
                                    <input type="hidden" name="action" value="update_withdrawal">
                                    <input type="hidden" name="id" value="<?php echo $w['id']; ?>">
                                    <input type="hidden" name="status" value="approved">
                                    <button class="bg-blue-600 hover:bg-blue-700 text-white p-1.5 rounded text-xs" title="Aprobar"><i class="fas fa-check"></i></button>
                                </form>
                                <form method="POST">
                                    <input type="hidden" name="action" value="update_withdrawal">
                                    <input type="hidden" name="id" value="<?php echo $w['id']; ?>">
                                    <input type="hidden" name="status" value="rejected">
                                    <button class="bg-red-600 hover:bg-red-700 text-white p-1.5 rounded text-xs" title="Rechazar"><i class="fas fa-times"></i></button>
                                </form>
                             </div>
                             <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
             <?php if(empty($withdrawals)): ?>
                <div class="p-12 text-center text-gray-500">
                    No hay solicitudes de retiro pendientes.
                </div>
            <?php endif; ?>
        </div>

        <!-- Content: Gateways -->
        <div id="content-gateways" class="flex-1 overflow-y-auto hidden p-8">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                <!-- Stripe (Tarjetas, Apple Pay, Google Pay) -->
                <div class="bg-dark-900 border border-dark-700 rounded-xl p-6 relative overflow-hidden group hover:border-indigo-500/50 transition">
                    <div class="absolute top-0 right-0 w-32 h-32 bg-indigo-500/5 rounded-bl-full -z-10"></div>
                    <form method="POST" class="space-y-4">
                        <div class="flex justify-between items-center mb-4">
                            <div>
                                <h3 class="text-xl font-bold text-white flex items-center gap-2"><i class="fab fa-stripe text-indigo-400"></i> Stripe</h3>
                                <p class="text-[10px] text-gray-400 mt-1">Tarjetas Débito/Crédito, Apple Pay , Google Pay 🤖</p>
                            </div>
                            <div class="w-3 h-3 rounded-full <?php echo ($gw_config['stripe']['is_active'] ?? 0) ? 'bg-green-500 shadow-[0_0_10px_#22c55e]' : 'bg-gray-600'; ?>"></div>
                        </div>
                        <input type="hidden" name="action" value="save_gateway">
                        <input type="hidden" name="provider" value="stripe">
                        
                        <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Publishable Key</label>
                            <input type="text" name="api_key" value="<?php echo htmlspecialchars($gw_config['stripe']['api_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm font-mono mt-1" placeholder="pk_live_...">
                        </div>
                         <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Secret Key</label>
                            <input type="password" name="secret_key" value="<?php echo htmlspecialchars($gw_config['stripe']['secret_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm font-mono mt-1" placeholder="sk_live_...">
                        </div>
                        <div class="flex items-center gap-2 pt-2">
                             <input type="checkbox" name="is_active" id="stripe_active" <?php echo ($gw_config['stripe']['is_active'] ?? 0) ? 'checked' : ''; ?> class="accent-indigo-600 w-4 h-4">
                             <label for="stripe_active" class="text-sm text-gray-300 cursor-pointer">Activar pasarela integral (Stripe)</label>
                        </div>
                        <button class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 rounded transition shadow-lg shadow-indigo-500/20">Guardar Stripe</button>
                    </form>
                </div>

                 <!-- PayPal -->
                <div class="bg-dark-900 border border-dark-700 rounded-xl p-6 relative overflow-hidden group hover:border-blue-500/50 transition">
                    <div class="absolute top-0 right-0 w-32 h-32 bg-blue-500/5 rounded-bl-full -z-10"></div>
                    <form method="POST" class="space-y-4">
                        <div class="flex justify-between items-center mb-4">
                            <div>
                                <h3 class="text-xl font-bold text-white flex items-center gap-2"><i class="fab fa-paypal text-blue-400"></i> PayPal</h3>
                                <p class="text-[10px] text-gray-400 mt-1">Pagos rápidos con saldo PayPal</p>
                            </div>
                            <div class="w-3 h-3 rounded-full <?php echo ($gw_config['paypal']['is_active'] ?? 0) ? 'bg-green-500 shadow-[0_0_10px_#22c55e]' : 'bg-gray-600'; ?>"></div>
                        </div>
                        <input type="hidden" name="action" value="save_gateway">
                        <input type="hidden" name="provider" value="paypal">
                        
                        <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Client ID</label>
                            <input type="text" name="api_key" value="<?php echo htmlspecialchars($gw_config['paypal']['api_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm font-mono mt-1">
                        </div>
                         <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Client Secret</label>
                            <input type="password" name="secret_key" value="<?php echo htmlspecialchars($gw_config['paypal']['secret_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm font-mono mt-1">
                        </div>
                        <div class="flex items-center gap-2 pt-2">
                             <input type="checkbox" name="is_active" id="paypal_active" <?php echo ($gw_config['paypal']['is_active'] ?? 0) ? 'checked' : ''; ?> class="accent-blue-600 w-4 h-4">
                             <label for="paypal_active" class="text-sm text-gray-300 cursor-pointer">Activar pago por PayPal</label>
                        </div>
                        <button class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 rounded transition shadow-lg shadow-blue-500/20">Guardar PayPal</button>
                    </form>
                </div>

                <!-- Zelle (Manual) -->
                <div class="bg-dark-900 border border-dark-700 rounded-xl p-6 relative overflow-hidden group hover:border-purple-500/50 transition">
                    <form method="POST" class="space-y-4">
                        <div class="flex justify-between items-center mb-4">
                            <div>
                                <h3 class="text-xl font-bold text-white flex items-center gap-2"><i class="fas fa-bolt text-purple-400"></i> Zelle</h3>
                                <p class="text-[10px] text-gray-400 mt-1">Transferencias rápidas EE.UU (Verificación Manual)</p>
                            </div>
                            <div class="w-3 h-3 rounded-full <?php echo ($gw_config['zelle']['is_active'] ?? 0) ? 'bg-green-500 shadow-[0_0_10px_#22c55e]' : 'bg-gray-600'; ?>"></div>
                        </div>
                        <input type="hidden" name="action" value="save_gateway">
                        <input type="hidden" name="provider" value="zelle">
                        
                        <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Email o Teléfono Zelle</label>
                            <input type="text" name="api_key" value="<?php echo htmlspecialchars($gw_config['zelle']['api_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm mt-1" placeholder="pagos@tuapp.com">
                        </div>
                         <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Nombre del Titular (Opcional)</label>
                            <input type="text" name="secret_key" value="<?php echo htmlspecialchars($gw_config['zelle']['secret_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm mt-1" placeholder="Juan Perez">
                        </div>
                        <div class="flex items-center gap-2 pt-2">
                             <input type="checkbox" name="is_active" id="zelle_active" <?php echo ($gw_config['zelle']['is_active'] ?? 0) ? 'checked' : ''; ?> class="accent-purple-600 w-4 h-4">
                             <label for="zelle_active" class="text-sm text-gray-300 cursor-pointer">Activar Zelle</label>
                        </div>
                        <button class="w-full bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 rounded transition shadow-lg shadow-purple-500/20">Guardar Zelle</button>
                    </form>
                </div>

                <!-- Transferencia Bancaria 1 (Manual) -->
                <div class="bg-dark-900 border border-dark-700 rounded-xl p-6 relative overflow-hidden group hover:border-emerald-500/50 transition">
                    <form method="POST" class="space-y-4">
                        <div class="flex justify-between items-center mb-4">
                            <div>
                                <h3 class="text-xl font-bold text-white flex items-center gap-2"><i class="fas fa-university text-emerald-400"></i> Banco Físico 1</h3>
                                <p class="text-[10px] text-gray-400 mt-1">Cuenta principal (Verificación Manual)</p>
                            </div>
                            <div class="w-3 h-3 rounded-full <?php echo ($gw_config['bank_transfer']['is_active'] ?? 0) ? 'bg-green-500 shadow-[0_0_10px_#22c55e]' : 'bg-gray-600'; ?>"></div>
                        </div>
                        <input type="hidden" name="action" value="save_gateway">
                        <input type="hidden" name="provider" value="bank_transfer">
                        
                        <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Número de Cuenta y Banco</label>
                            <input type="text" name="api_key" value="<?php echo htmlspecialchars($gw_config['bank_transfer']['api_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm mt-1" placeholder="Ej: Chase - 123456789">
                        </div>
                         <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Nombre a quien depositar / Instrucciones</label>
                            <input type="text" name="secret_key" value="<?php echo htmlspecialchars($gw_config['bank_transfer']['secret_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm mt-1" placeholder="...">
                        </div>
                        <div class="flex items-center gap-2 pt-2">
                             <input type="checkbox" name="is_active" id="bank_active" <?php echo ($gw_config['bank_transfer']['is_active'] ?? 0) ? 'checked' : ''; ?> class="accent-emerald-600 w-4 h-4">
                             <label for="bank_active" class="text-sm text-gray-300 cursor-pointer">Activar Banco 1</label>
                        </div>
                        <button class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2 rounded transition shadow-lg shadow-emerald-500/20">Guardar Banco 1</button>
                    </form>
                </div>

                <!-- Transferencia Bancaria 2 (Manual) -->
                <div class="bg-dark-900 border border-dark-700 rounded-xl p-6 relative overflow-hidden group hover:border-emerald-500/50 transition">
                    <form method="POST" class="space-y-4">
                        <div class="flex justify-between items-center mb-4">
                            <div>
                                <h3 class="text-xl font-bold text-white flex items-center gap-2"><i class="fas fa-university text-teal-400"></i> Banco Físico 2</h3>
                                <p class="text-[10px] text-gray-400 mt-1">Cuenta secundaria (Verificación Manual)</p>
                            </div>
                            <div class="w-3 h-3 rounded-full <?php echo ($gw_config['bank_transfer_2']['is_active'] ?? 0) ? 'bg-green-500 shadow-[0_0_10px_#22c55e]' : 'bg-gray-600'; ?>"></div>
                        </div>
                        <input type="hidden" name="action" value="save_gateway">
                        <input type="hidden" name="provider" value="bank_transfer_2">
                        
                        <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Número de Cuenta y Banco 2</label>
                            <input type="text" name="api_key" value="<?php echo htmlspecialchars($gw_config['bank_transfer_2']['api_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm mt-1" placeholder="Ej: Banreservas - 987654321">
                        </div>
                         <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Nombre a quien depositar / Instrucciones</label>
                            <input type="text" name="secret_key" value="<?php echo htmlspecialchars($gw_config['bank_transfer_2']['secret_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm mt-1" placeholder="...">
                        </div>
                        <div class="flex items-center gap-2 pt-2">
                             <input type="checkbox" name="is_active" id="bank_active_2" <?php echo ($gw_config['bank_transfer_2']['is_active'] ?? 0) ? 'checked' : ''; ?> class="accent-teal-600 w-4 h-4">
                             <label for="bank_active_2" class="text-sm text-gray-300 cursor-pointer">Activar Banco 2</label>
                        </div>
                        <button class="w-full bg-teal-600 hover:bg-teal-700 text-white font-bold py-2 rounded transition shadow-lg shadow-teal-500/20">Guardar Banco 2</button>
                    </form>
                </div>

                <!-- Transferencia Bancaria 3 (Manual) -->
                <div class="bg-dark-900 border border-dark-700 rounded-xl p-6 relative overflow-hidden group hover:border-emerald-500/50 transition">
                    <form method="POST" class="space-y-4">
                        <div class="flex justify-between items-center mb-4">
                            <div>
                                <h3 class="text-xl font-bold text-white flex items-center gap-2"><i class="fas fa-university text-cyan-400"></i> Banco Físico 3</h3>
                                <p class="text-[10px] text-gray-400 mt-1">Tercera cuenta u otro país (Verificación Manual)</p>
                            </div>
                            <div class="w-3 h-3 rounded-full <?php echo ($gw_config['bank_transfer_3']['is_active'] ?? 0) ? 'bg-green-500 shadow-[0_0_10px_#22c55e]' : 'bg-gray-600'; ?>"></div>
                        </div>
                        <input type="hidden" name="action" value="save_gateway">
                        <input type="hidden" name="provider" value="bank_transfer_3">
                        
                        <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Número de Cuenta y Banco 3</label>
                            <input type="text" name="api_key" value="<?php echo htmlspecialchars($gw_config['bank_transfer_3']['api_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm mt-1" placeholder="Ej: BHD - 11223344">
                        </div>
                         <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Nombre a quien depositar / Instrucciones</label>
                            <input type="text" name="secret_key" value="<?php echo htmlspecialchars($gw_config['bank_transfer_3']['secret_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm mt-1" placeholder="...">
                        </div>
                        <div class="flex items-center gap-2 pt-2">
                             <input type="checkbox" name="is_active" id="bank_active_3" <?php echo ($gw_config['bank_transfer_3']['is_active'] ?? 0) ? 'checked' : ''; ?> class="accent-cyan-600 w-4 h-4">
                             <label for="bank_active_3" class="text-sm text-gray-300 cursor-pointer">Activar Banco 3</label>
                        </div>
                        <button class="w-full bg-cyan-600 hover:bg-cyan-700 text-white font-bold py-2 rounded transition shadow-lg shadow-cyan-500/20">Guardar Banco 3</button>
                    </form>
                </div>

                <!-- Criptomonedas (USDT/Bitcoin) -->
                <div class="bg-dark-900 border border-dark-700 rounded-xl p-6 relative overflow-hidden group hover:border-orange-500/50 transition">
                    <form method="POST" class="space-y-4">
                        <div class="flex justify-between items-center mb-4">
                            <div>
                                <h3 class="text-xl font-bold text-white flex items-center gap-2"><i class="fab fa-bitcoin text-orange-400"></i> Crypto</h3>
                                <p class="text-[10px] text-gray-400 mt-1">USDT, BTC o integración Binance Pay</p>
                            </div>
                            <div class="w-3 h-3 rounded-full <?php echo ($gw_config['crypto']['is_active'] ?? 0) ? 'bg-green-500 shadow-[0_0_10px_#22c55e]' : 'bg-gray-600'; ?>"></div>
                        </div>
                        <input type="hidden" name="action" value="save_gateway">
                        <input type="hidden" name="provider" value="crypto">
                        
                        <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Wallet Address (Ej. USDT TRC20)</label>
                            <input type="text" name="api_key" value="<?php echo htmlspecialchars($gw_config['crypto']['api_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm font-mono mt-1" placeholder="T...">
                        </div>
                         <div>
                            <label class="text-xs text-gray-400 font-bold uppercase">Merchant ID o API Coinbase (Opcional)</label>
                            <input type="text" name="secret_key" value="<?php echo htmlspecialchars($gw_config['crypto']['secret_key'] ?? ''); ?>" class="w-full bg-dark-800 border border-dark-700 rounded p-2 text-white text-sm font-mono mt-1" placeholder="...">
                        </div>
                        <div class="flex items-center gap-2 pt-2">
                             <input type="checkbox" name="is_active" id="crypto_active" <?php echo ($gw_config['crypto']['is_active'] ?? 0) ? 'checked' : ''; ?> class="accent-orange-600 w-4 h-4">
                             <label for="crypto_active" class="text-sm text-gray-300 cursor-pointer">Activar pagos con Crypto</label>
                        </div>
                        <button class="w-full bg-orange-600 hover:bg-orange-700 text-white font-bold py-2 rounded transition shadow-lg shadow-orange-500/20">Guardar Crypto</button>
                    </form>
                </div>

            </div>
        </div>
    </div>
</div>

<script>
function switchTab(tab) {
    document.getElementById('tab-withdrawals').className = tab === 'withdrawals' 
        ? 'px-6 py-4 text-sm font-bold text-brand-500 border-b-2 border-brand-500 bg-dark-800 transition'
        : 'px-6 py-4 text-sm font-medium text-gray-400 hover:text-white hover:bg-dark-800 transition border-b-2 border-transparent';
    
    document.getElementById('tab-gateways').className = tab === 'gateways'
        ? 'px-6 py-4 text-sm font-bold text-brand-500 border-b-2 border-brand-500 bg-dark-800 transition'
        : 'px-6 py-4 text-sm font-medium text-gray-400 hover:text-white hover:bg-dark-800 transition border-b-2 border-transparent';

    document.getElementById('content-withdrawals').classList.toggle('hidden', tab !== 'withdrawals');
    document.getElementById('content-gateways').classList.toggle('hidden', tab !== 'gateways');
}
</script>

<?php renderAdminFooter(); ?>
