<?php
/**
 * Gateways de Pagamento - Super Admin
 * Gerenciamento de provedores de pagamento
 */
require_once __DIR__ . '/../../../includes/config.php';
require_once __DIR__ . '/../../../includes/Payment/PaymentFactory.php';

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

use Payment\PaymentFactory;

$superAdmin = getSuperAdmin();
$pdo = getDB();
$factory = new PaymentFactory($pdo);

$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 = 'error';
        }
    } elseif ($action === 'update_credentials') {
        $gatewayId = (int) ($_POST['gateway_id'] ?? 0);
        // Debug: log what we receive
        error_log("UPDATE_CREDENTIALS: " . json_encode($_POST));
        $data = [
            'public_key' => trim($_POST['public_key'] ?? ''),
            'secret_key' => trim($_POST['secret_key'] ?? ''),
            'webhook_secret' => trim($_POST['webhook_secret'] ?? ''),
            'environment' => $_POST['environment'] ?? 'sandbox',
            'oauth_client_id' => trim($_POST['oauth_client_id'] ?? ''),
            'oauth_client_secret' => trim($_POST['oauth_client_secret'] ?? '')
        ];

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

// 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'
];

$pageTitle = 'Gateways de Pagamento';
$currentPage = 'gateways';

include __DIR__ . '/../includes/header.php';
?>
    <div class="app-container">
        <?php include __DIR__ . '/../includes/sidebar.php'; ?>

        <!-- Main Content -->
        <main class="main-content">
            <?php include __DIR__ . '/../includes/topbar.php'; ?>

            <div class="content-area">
                <div class="page-header">
                    <div>
                        <h2>
                            <iconify-icon icon="solar:card-transfer-bold"></iconify-icon>
                            Gateways de Pagamento
                        </h2>
                        <p>Configure os provedores de pagamento da plataforma</p>
                    </div>
                </div>

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

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

                <div class="gateways-grid">
                    <?php foreach ($gateways as $gateway): ?>
                    <div class="panel gateway-card <?= $gateway['is_active'] ? 'active-gateway' : '' ?>">
                        <div class="gateway-header">
                            <div class="gateway-info">
                                <img src="<?= $gatewayIcons[$gateway['name']] ?? '' ?>" 
                                     alt="<?= htmlspecialchars($gateway['display_name']) ?>" 
                                     class="gateway-icon"
                                     onerror="this.style.display='none'">
                                <div>
                                    <h3><?= htmlspecialchars($gateway['display_name']) ?></h3>
                                    <div class="gateway-badges">
                                        <?php if ($gateway['is_active']): ?>
                                        <span class="status-badge status-active">
                                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Ativo
                                        </span>
                                        <?php else: ?>
                                        <span class="status-badge status-inactive">Inativo</span>
                                        <?php endif; ?>
                                        
                                        <span class="status-badge <?= $gateway['environment'] === 'production' ? 'status-danger' : 'status-warning' ?>">
                                            <?= $gateway['environment'] === 'production' ? '🚀 Produção' : '🧪 Sandbox' ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <form method="POST" class="gateway-body">
                            <input type="hidden" name="action" value="update_credentials">
                            <input type="hidden" name="gateway_id" value="<?= $gateway['id'] ?>">
                            
                            <!-- Pagamentos da Plataforma SaaS -->
                            <?php if ($gateway["name"] === "mercadopago"): ?>
                            <div class="saas-section" style="margin-bottom: 1.5rem; padding: 1.25rem; background: linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(16, 185, 129, 0.05) 100%); border-radius: 12px; border: 1px solid rgba(16, 185, 129, 0.2);">
                                <h4 style="margin: 0 0 0.5rem; color: #10b981; display: flex; align-items: center; gap: 0.5rem; font-size: 1rem;">
                                    <iconify-icon icon="solar:buildings-bold"></iconify-icon>
                                    Pagamentos da Plataforma (SaaS)
                                </h4>
                                <p style="font-size: 0.8rem; color: var(--text-muted); margin-bottom: 1rem;">
                                    Credenciais para cobrar assinaturas e pagamentos da própria plataforma.
                                </p>
                            <?php endif; ?>
                            <div class="form-group">
                                <label class="form-label">Public Key</label>
                                <input type="text" 
                                       class="form-input" 
                                       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-with-btn">
                                    <input type="password" 
                                           class="form-input" 
                                           name="secret_key" 
                                           id="secret_<?= $gateway['id'] ?>"
                                           value="<?= htmlspecialchars($gateway['secret_key'] ?? '') ?>"
                                           placeholder="Access Token ou Secret Key">
                                    <button type="button" class="btn btn-icon" 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-input" 
                                       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>
                            <?php if ($gateway["name"] === "mercadopago"): ?>
                            </div><!-- End saas-section -->
                            <?php endif; ?>

                            <!-- OAuth Connect Section (Mercado Pago) - Para Lojistas -->
                            <?php if ($gateway["name"] === "mercadopago"): ?>
                            <div class="oauth-section" style="margin-top: 1.5rem; padding: 1.25rem; background: linear-gradient(135deg, rgba(0, 158, 227, 0.1) 0%, rgba(0, 158, 227, 0.05) 100%); border-radius: 12px; border: 1px solid rgba(0, 158, 227, 0.2);">
                                <h4 style="margin: 0 0 0.5rem; color: #009ee3; display: flex; align-items: center; gap: 0.5rem; font-size: 1rem;">
                                    <iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon>
                                    Pagamentos dos Lojistas (OAuth Connect)
                                </h4>
                                <p style="font-size: 0.8rem; color: var(--text-muted); margin-bottom: 1rem;">
                                    Permite que cada lojista conecte sua própria conta Mercado Pago para receber pagamentos diretamente.
                                </p>
                                
                                <div class="form-group" style="margin-bottom: 1rem;">
                                    <label class="form-label">Client ID (OAuth)</label>
                                    <input type="text" class="form-input" name="oauth_client_id" value="<?= htmlspecialchars($gateway['oauth_client_id'] ?? '') ?>" placeholder="Ex: 5248456368224763" style="font-family: monospace;">
                                    <small style="color: var(--text-muted);">APP_ID da aplicação no Mercado Pago Developers</small>
                                </div>
                                
                                <div class="form-group" style="margin-bottom: 1rem;">
                                    <label class="form-label">Client Secret (OAuth)</label>
                                    <div class="input-with-btn">
                                        <input type="password" class="form-input" name="oauth_client_secret" id="oauth_secret_<?= $gateway['id'] ?>" value="<?= htmlspecialchars($gateway['oauth_client_secret'] ?? '') ?>" placeholder="Client Secret" style="font-family: monospace;">
                                        <button type="button" class="btn btn-icon" onclick="togglePassword('oauth_secret_<?= $gateway['id'] ?>')">
                                            <iconify-icon icon="solar:eye-bold"></iconify-icon>
                                        </button>
                                    </div>
                                </div>
                                
                                <div class="form-group" style="margin-bottom: 0;">
                                    <label class="form-label">URL de Redirect</label>
                                    <div class="input-with-btn">
                                        <input type="text" class="form-input" value="https://dev.duolead.com.br/api/mercadopago-callback.php" readonly style="font-family: monospace; background: var(--bg-darker);">
                                        <button type="button" class="btn btn-icon" onclick="copyToClipboard('https://dev.duolead.com.br/api/mercadopago-callback.php')" title="Copiar">
                                            <iconify-icon icon="solar:copy-bold"></iconify-icon>
                                        </button>
                                    </div>
                                    <small style="color: var(--warning);">⚠️ Cadastre esta URL no Mercado Pago Developers → Sua App → URLs de Redirect</small>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <div class="action-buttons">
                                <button type="submit" class="btn btn-primary">
                                    <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>
                    <?php endforeach; ?>
                </div>

                <div class="panel" style="margin-top: 2rem;">
                    <div class="panel-header">
                        <h3>
                            <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                            Como funciona
                        </h3>
                    </div>
                    <div class="panel-body">
                        <ul class="info-list">
                            <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>
                </div>
            </div>
        </main>
    </div>

<style>
/* Gateways Grid */
.gateways-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 1.5rem;
}

@media (max-width: 768px) {
    .gateways-grid {
        grid-template-columns: 1fr;
    }
}

/* Gateway Card */
.gateway-card {
    padding: 0;
    overflow: hidden;
}

.gateway-card.active-gateway {
    border: 2px solid var(--success);
}

.gateway-header {
    padding: 1.25rem;
    background: var(--bg-input);
    border-bottom: 1px solid var(--border-light);
}

.gateway-info {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.gateway-icon {
    width: 48px;
    height: 48px;
    border-radius: var(--radius-md);
    background: white;
    padding: 8px;
    object-fit: contain;
}

.gateway-info h3 {
    margin: 0 0 0.5rem 0;
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--text-primary);
}

.gateway-badges {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.gateway-body {
    padding: 1.25rem;
}

/* Form Groups */
.form-group {
    margin-bottom: 1rem;
}

.form-label {
    display: block;
    font-size: 0.85rem;
    font-weight: 500;
    color: var(--text-muted);
    margin-bottom: 0.5rem;
}

/* Input with Button */
.input-with-btn {
    display: flex;
    gap: 0;
}

.input-with-btn .form-input {
    border-radius: var(--radius-md) 0 0 var(--radius-md);
    border-right: none;
}

.input-with-btn .btn-icon {
    border-radius: 0 var(--radius-md) var(--radius-md) 0;
    border: 1px solid var(--border-light);
    background: var(--bg-input);
    padding: 0 1rem;
    color: var(--text-muted);
    cursor: pointer;
    transition: all 0.2s;
}

.input-with-btn .btn-icon:hover {
    background: var(--bg-panel);
    color: var(--gold);
}

/* Status Badges */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    font-size: 0.75rem;
    padding: 0.25rem 0.6rem;
    border-radius: 50px;
    font-weight: 500;
}

.status-active {
    background: rgba(34, 197, 94, 0.15);
    color: var(--success);
}

.status-inactive {
    background: var(--bg-input);
    color: var(--text-muted);
}

.status-warning {
    background: rgba(245, 158, 11, 0.15);
    color: var(--warning);
}

.status-danger {
    background: rgba(239, 68, 68, 0.15);
    color: var(--danger);
}

/* Panel Header/Body */
.panel-header {
    padding: 1.25rem;
    border-bottom: 1px solid var(--border-light);
}

.panel-header h3 {
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 1rem;
    font-weight: 600;
    color: var(--text-primary);
}

.panel-body {
    padding: 1.25rem;
}

/* Info List */
.info-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.info-list li {
    padding: 0.5rem 0;
    color: var(--text-secondary);
    display: flex;
    align-items: flex-start;
    gap: 0.75rem;
    font-size: 0.9rem;
}

.info-list li::before {
    content: "•";
    color: var(--gold);
    font-weight: bold;
}

.info-list code {
    background: var(--bg-input);
    padding: 0.2rem 0.5rem;
    border-radius: var(--radius-sm);
    font-size: 0.8rem;
    color: var(--gold);
}

/* Alerts */
.alert {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1rem 1.25rem;
    border-radius: var(--radius-lg);
    margin-bottom: 1.5rem;
    font-size: 0.9rem;
}

.alert-success {
    background: rgba(34, 197, 94, 0.1);
    border: 1px solid rgba(34, 197, 94, 0.3);
    color: var(--success);
}

.alert-error {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.3);
    color: var(--danger);
}

.alert-warning {
    background: rgba(245, 158, 11, 0.1);
    border: 1px solid rgba(245, 158, 11, 0.3);
    color: var(--warning);
}

/* Button Success */
.btn-success {
    background: linear-gradient(135deg, var(--success), #16a34a);
    color: white;
}

.btn-success:hover {
    filter: brightness(1.1);
}
</style>

<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');

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        alert("URL copiada para a área de transferência!");
    }).catch(function(err) {
        prompt("Copie a URL:", text);
    });
}
    }
}
</script>

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