<?php
/**
 * Super Admin - Gerenciamento de Gateways de Pagamento
 * 
 * Permite selecionar o gateway ativo e configurar credenciais.
 */

session_start();
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/Payment/PaymentFactory.php';

// Verificar se é Super Admin
// TODO: Implementar autenticação de super admin
$isSuperAdmin = true; // Por enquanto, permitir acesso

if (!$isSuperAdmin) {
    header('Location: /admin/login.php');
    exit;
}

use Payment\PaymentFactory;

$factory = new PaymentFactory(getDB());
$message = '';
$messageType = '';

// Processar formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'activate') {
        $gatewayId = (int) ($_POST['gateway_id'] ?? 0);
        if ($factory->activateGateway($gatewayId)) {
            $message = 'Gateway ativado com sucesso!';
            $messageType = 'success';
        } else {
            $message = 'Erro ao ativar gateway.';
            $messageType = 'danger';
        }
    }

    if ($action === 'update_credentials') {
        $gatewayId = (int) ($_POST['gateway_id'] ?? 0);
        $data = [
            'public_key' => trim($_POST['public_key'] ?? ''),
            'secret_key' => trim($_POST['secret_key'] ?? ''),
            'webhook_secret' => trim($_POST['webhook_secret'] ?? ''),
            'environment' => $_POST['environment'] ?? 'sandbox'
        ];

        if ($factory->updateGateway($gatewayId, $data)) {
            $message = 'Credenciais atualizadas com sucesso!';
            $messageType = 'success';
        } else {
            $message = 'Erro ao atualizar credenciais.';
            $messageType = 'danger';
        }
    }
}

// Buscar todos os gateways
$gateways = $factory->getAllGateways();
$activeGateway = $factory->getActiveGateway();

// Ícones dos gateways
$gatewayIcons = [
    'mercadopago' => 'https://http2.mlstatic.com/frontend-assets/mp-web-navigation/ui-navigation/5.21.22/mercadopago/favicon.svg',
    'stripe' => 'https://stripe.com/favicon.ico',
    'asaas' => 'https://www.asaas.com/favicon.ico'
];
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gateways de Pagamento - Super Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://code.iconify.design/iconify-icon/1.0.7/iconify-icon.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: #0f172a;
            color: #e2e8f0;
            min-height: 100vh;
        }
        
        .superadmin-layout {
            display: flex;
            min-height: 100vh;
        }
        
        .superadmin-sidebar {
            width: 260px;
            background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
            border-right: 1px solid rgba(255,255,255,0.1);
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            z-index: 100;
        }
        
        .sidebar-header {
            padding: 1.5rem;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .sidebar-logo {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .sidebar-logo-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
            color: white;
        }
        
        .sidebar-logo-text {
            font-weight: 700;
            font-size: 1.25rem;
            color: white;
        }
        
        .sidebar-logo-badge {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
            font-size: 0.65rem;
            padding: 0.15rem 0.5rem;
            border-radius: 50px;
            font-weight: 600;
            margin-left: 0.5rem;
        }
        
        .sidebar-nav {
            padding: 1rem 0;
        }
        
        .nav-section {
            margin-bottom: 1.5rem;
        }
        
        .nav-section-title {
            color: #64748b;
            font-size: 0.7rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            padding: 0 1.5rem;
            margin-bottom: 0.75rem;
        }
        
        .nav-link {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.75rem 1.5rem;
            color: #94a3b8;
            text-decoration: none;
            font-size: 0.9rem;
            transition: all 0.2s;
        }
        
        .nav-link:hover {
            background: rgba(99, 102, 241, 0.1);
            color: #e2e8f0;
        }
        
        .nav-link.active {
            background: linear-gradient(90deg, rgba(99, 102, 241, 0.2) 0%, transparent 100%);
            color: #818cf8;
            border-left: 3px solid #6366f1;
        }
        
        .nav-link iconify-icon {
            font-size: 1.25rem;
        }
        
        .superadmin-main {
            flex: 1;
            margin-left: 260px;
            padding: 2rem;
        }
        
        .page-header {
            margin-bottom: 2rem;
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 700;
            color: white;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .page-subtitle {
            color: #64748b;
            margin-top: 0.5rem;
        }
        
        .alert {
            padding: 1rem 1.5rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .alert-success {
            background: rgba(34, 197, 94, 0.1);
            border: 1px solid rgba(34, 197, 94, 0.3);
            color: #4ade80;
        }
        
        .alert-danger {
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #f87171;
        }
        
        .alert-warning {
            background: rgba(245, 158, 11, 0.1);
            border: 1px solid rgba(245, 158, 11, 0.3);
            color: #fbbf24;
        }
        
        .gateways-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 1.5rem;
        }
        
        .gateway-card {
            background: #1e293b;
            border-radius: 16px;
            border: 1px solid rgba(255,255,255,0.1);
            overflow: hidden;
            transition: all 0.3s;
        }
        
        .gateway-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px rgba(0,0,0,0.3);
        }
        
        .gateway-card.active {
            border: 2px solid #22c55e;
        }
        
        .gateway-header {
            padding: 1.25rem;
            background: rgba(255,255,255,0.02);
            display: flex;
            align-items: center;
            gap: 1rem;
            border-bottom: 1px solid rgba(255,255,255,0.05);
        }
        
        .gateway-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            background: white;
            padding: 8px;
            object-fit: contain;
        }
        
        .gateway-name {
            font-weight: 600;
            font-size: 1.1rem;
            color: white;
        }
        
        .gateway-badges {
            display: flex;
            gap: 0.5rem;
            margin-top: 0.25rem;
        }
        
        .badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.6rem;
            border-radius: 50px;
            font-weight: 500;
        }
        
        .badge-success {
            background: rgba(34, 197, 94, 0.2);
            color: #4ade80;
        }
        
        .badge-secondary {
            background: rgba(100, 116, 139, 0.2);
            color: #94a3b8;
        }
        
        .badge-warning {
            background: rgba(245, 158, 11, 0.2);
            color: #fbbf24;
        }
        
        .badge-danger {
            background: rgba(239, 68, 68, 0.2);
            color: #f87171;
        }
        
        .gateway-body {
            padding: 1.25rem;
        }
        
        .form-group {
            margin-bottom: 1rem;
        }
        
        .form-label {
            display: block;
            font-size: 0.8rem;
            color: #64748b;
            margin-bottom: 0.5rem;
        }
        
        .form-control {
            width: 100%;
            padding: 0.65rem 1rem;
            background: #0f172a;
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 8px;
            color: #e2e8f0;
            font-size: 0.9rem;
            font-family: 'Courier New', monospace;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #6366f1;
        }
        
        .form-select {
            width: 100%;
            padding: 0.65rem 1rem;
            background: #0f172a;
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 8px;
            color: #e2e8f0;
            font-size: 0.9rem;
        }
        
        .input-group {
            display: flex;
        }
        
        .input-group .form-control {
            border-radius: 8px 0 0 8px;
        }
        
        .input-group .btn-toggle {
            background: #334155;
            border: 1px solid rgba(255,255,255,0.1);
            border-left: none;
            border-radius: 0 8px 8px 0;
            color: #94a3b8;
            padding: 0 1rem;
            cursor: pointer;
        }
        
        .btn-group {
            display: flex;
            gap: 0.75rem;
            margin-top: 1rem;
        }
        
        .btn {
            padding: 0.65rem 1.25rem;
            border-radius: 8px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            border: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(99, 102, 241, 0.3);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(34, 197, 94, 0.3);
        }
        
        .info-card {
            background: #1e293b;
            border-radius: 12px;
            padding: 1.5rem;
            margin-top: 2rem;
            border: 1px solid rgba(255,255,255,0.1);
        }
        
        .info-card h4 {
            color: white;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .info-card ul {
            list-style: none;
            color: #94a3b8;
        }
        
        .info-card li {
            padding: 0.5rem 0;
            display: flex;
            align-items: flex-start;
            gap: 0.5rem;
        }
        
        .info-card li::before {
            content: "•";
            color: #6366f1;
        }
        
        @media (max-width: 768px) {
            .superadmin-sidebar {
                display: none;
            }
            .superadmin-main {
                margin-left: 0;
            }
            .gateways-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="superadmin-layout">
        <!-- Sidebar -->
        <aside class="superadmin-sidebar">
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <div class="sidebar-logo-icon">
                        <iconify-icon icon="solar:crown-bold"></iconify-icon>
                    </div>
                    <span class="sidebar-logo-text">BarberFlow</span>
                    <span class="sidebar-logo-badge">ADMIN</span>
                </div>
            </div>
            
            <nav class="sidebar-nav">
                <div class="nav-section">
                    <div class="nav-section-title">Principal</div>
                    <a href="/superadmin/" class="nav-link">
                        <iconify-icon icon="solar:chart-bold"></iconify-icon>
                        <span>Dashboard</span>
                    </a>
                    <a href="/superadmin/stores.php" class="nav-link">
                        <iconify-icon icon="solar:shop-2-bold"></iconify-icon>
                        <span>Lojas</span>
                    </a>
                    <a href="/superadmin/users.php" class="nav-link">
                        <iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon>
                        <span>Usuários</span>
                    </a>
                </div>
                
                <div class="nav-section">
                    <div class="nav-section-title">Financeiro</div>
                    <a href="/superadmin/subscriptions.php" class="nav-link">
                        <iconify-icon icon="solar:card-bold"></iconify-icon>
                        <span>Assinaturas</span>
                    </a>
                    <a href="/superadmin/invoices.php" class="nav-link">
                        <iconify-icon icon="solar:document-bold"></iconify-icon>
                        <span>Faturas</span>
                    </a>
                    <a href="/superadmin/revenue.php" class="nav-link">
                        <iconify-icon icon="solar:wallet-money-bold"></iconify-icon>
                        <span>Receita</span>
                    </a>
                </div>
                
                <div class="nav-section">
                    <div class="nav-section-title">Sistema</div>
                    <a href="/superadmin/plans.php" class="nav-link">
                        <iconify-icon icon="solar:tag-price-bold"></iconify-icon>
                        <span>Planos</span>
                    </a>
                    <a href="/superadmin/features.php" class="nav-link">
                        <iconify-icon icon="solar:flag-bold"></iconify-icon>
                        <span>Feature Flags</span>
                    </a>
                    <a href="/superadmin/settings.php" class="nav-link">
                        <iconify-icon icon="solar:settings-bold"></iconify-icon>
                        <span>Configurações</span>
                    </a>
                    <a href="/superadmin/gateways.php" class="nav-link active">
                        <iconify-icon icon="solar:card-transfer-bold"></iconify-icon>
                        <span>Gateways de Pagamento</span>
                    </a>
                </div>
                
                <div class="nav-section">
                    <div class="nav-section-title">Logs</div>
                    <a href="/superadmin/audit.php" class="nav-link">
                        <iconify-icon icon="solar:clipboard-list-bold"></iconify-icon>
                        <span>Auditoria</span>
                    </a>
                    <a href="/superadmin/impersonations.php" class="nav-link">
                        <iconify-icon icon="solar:user-check-bold"></iconify-icon>
                        <span>Impersonations</span>
                    </a>
                </div>
            </nav>
        </aside>
        
        <!-- Main Content -->
        <main class="superadmin-main">
            <div class="page-header">
                <h1 class="page-title">
                    <iconify-icon icon="solar:card-transfer-bold"></iconify-icon>
                    Gateways de Pagamento
                </h1>
                <p class="page-subtitle">Configure e gerencie os provedores de pagamento da plataforma</p>
            </div>

            <?php if ($message): ?>
            <div class="alert alert-<?= $messageType ?>">
                <iconify-icon icon="<?= $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:danger-triangle-bold' ?>"></iconify-icon>
                <?= htmlspecialchars($message) ?>
            </div>
            <?php endif; ?>

            <?php if (!$activeGateway): ?>
            <div class="alert alert-warning">
                <iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>
                <strong>Atenção:</strong> Nenhum gateway de pagamento está ativo. Configure e ative um gateway para aceitar pagamentos.
            </div>
            <?php endif; ?>

            <div class="gateways-grid">
                <?php foreach ($gateways as $gateway): ?>
                <div class="gateway-card <?= $gateway['is_active'] ? 'active' : '' ?>">
                    <div class="gateway-header">
                        <img src="<?= $gatewayIcons[$gateway['name']] ?? '' ?>" 
                             alt="<?= htmlspecialchars($gateway['display_name']) ?>" 
                             class="gateway-icon"
                             onerror="this.style.display='none'">
                        <div>
                            <div class="gateway-name"><?= htmlspecialchars($gateway['display_name']) ?></div>
                            <div class="gateway-badges">
                                <?php if ($gateway['is_active']): ?>
                                <span class="badge badge-success">✓ Ativo</span>
                                <?php else: ?>
                                <span class="badge badge-secondary">Inativo</span>
                                <?php endif; ?>
                                
                                <span class="badge <?= $gateway['environment'] === 'production' ? 'badge-danger' : 'badge-warning' ?>">
                                    <?= $gateway['environment'] === 'production' ? '🚀 Produção' : '🧪 Sandbox' ?>
                                </span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="gateway-body">
                        <form method="POST">
                            <input type="hidden" name="action" value="update_credentials">
                            <input type="hidden" name="gateway_id" value="<?= $gateway['id'] ?>">
                            
                            <div class="form-group">
                                <label class="form-label">Public Key</label>
                                <input type="text" 
                                       class="form-control" 
                                       name="public_key" 
                                       value="<?= htmlspecialchars($gateway['public_key'] ?? '') ?>"
                                       placeholder="Chave pública (se aplicável)">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Secret Key / Access Token</label>
                                <div class="input-group">
                                    <input type="password" 
                                           class="form-control" 
                                           name="secret_key" 
                                           id="secret_<?= $gateway['id'] ?>"
                                           value="<?= htmlspecialchars($gateway['secret_key'] ?? '') ?>"
                                           placeholder="Access Token ou Secret Key">
                                    <button type="button" 
                                            class="btn-toggle" 
                                            onclick="togglePassword('secret_<?= $gateway['id'] ?>')">
                                        <iconify-icon icon="solar:eye-bold" id="icon_secret_<?= $gateway['id'] ?>"></iconify-icon>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Webhook Secret (opcional)</label>
                                <input type="text" 
                                       class="form-control" 
                                       name="webhook_secret" 
                                       value="<?= htmlspecialchars($gateway['webhook_secret'] ?? '') ?>"
                                       placeholder="Secret para validar webhooks">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Ambiente</label>
                                <select class="form-select" name="environment">
                                    <option value="sandbox" <?= $gateway['environment'] === 'sandbox' ? 'selected' : '' ?>>
                                        🧪 Sandbox (Testes)
                                    </option>
                                    <option value="production" <?= $gateway['environment'] === 'production' ? 'selected' : '' ?>>
                                        🚀 Produção
                                    </option>
                                </select>
                            </div>
                            
                            <div class="btn-group">
                                <button type="submit" class="btn btn-primary" style="flex:1">
                                    <iconify-icon icon="solar:diskette-bold"></iconify-icon>
                                    Salvar
                                </button>
                                
                                <?php if (!$gateway['is_active']): ?>
                                <button type="submit" 
                                        name="action" 
                                        value="activate"
                                        class="btn btn-success"
                                        onclick="return confirm('Ativar este gateway? O gateway atual será desativado.')">
                                    <iconify-icon icon="solar:power-bold"></iconify-icon>
                                    Ativar
                                </button>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="info-card">
                <h4>
                    <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                    Como funciona
                </h4>
                <ul>
                    <li><strong>Apenas um gateway pode estar ativo</strong> por vez.</li>
                    <li>Ao ativar um novo gateway, o anterior é automaticamente desativado.</li>
                    <li>Use o ambiente <strong>Sandbox</strong> para testes antes de ir para produção.</li>
                    <li>O <strong>Webhook Secret</strong> é usado para validar notificações de pagamento.</li>
                    <li>Configure o webhook no painel do gateway: <code>https://dev.duolead.com.br/api/webhook-payment.php</code></li>
                </ul>
            </div>
        </main>
    </div>

    <script>
        function togglePassword(inputId) {
            const input = document.getElementById(inputId);
            const icon = document.getElementById('icon_' + inputId);
            
            if (input.type === 'password') {
                input.type = 'text';
                icon.setAttribute('icon', 'solar:eye-closed-bold');
            } else {
                input.type = 'password';
                icon.setAttribute('icon', 'solar:eye-bold');
            }
        }
    </script>
</body>
</html>
