<?php
/**
 * Pagamentos - Configuração de Gateway de Pagamento
 * Permite que lojistas conectem sua conta Mercado Pago via OAuth
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/Payment/MercadoPagoOAuth.php';

use Payment\MercadoPagoOAuth;

if (!isset($_SESSION['user_id']) || !isset($_SESSION['store_id'])) {
    header('Location: /pages/login.php');
    exit;
}

$pdo = getDB();
$storeId = $_SESSION['store_id'];
$userId = $_SESSION['user_id'];

// Buscar dados do usuário e loja
$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Verificar integração existente
$oauth = new MercadoPagoOAuth($pdo);
$integration = $oauth->getIntegration($storeId);

// Parse payment methods
$paymentMethods = json_decode($store['payment_methods'] ?? '{"whatsapp": true, "online": false}', true);
$whatsappEnabled = $paymentMethods['whatsapp'] ?? true;
$onlineEnabled = $paymentMethods['online'] ?? false;

// Handle form submission for payment methods
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_payment_methods') {
    $whatsappEnabled = isset($_POST['whatsapp_enabled']);
    $onlineEnabled = isset($_POST['online_enabled']);
    $paymentMethods = json_encode(['whatsapp' => $whatsappEnabled, 'online' => $onlineEnabled]);
    $updateStmt = $pdo->prepare("UPDATE stores SET payment_methods = ? WHERE id = ?");
    $updateStmt->execute([$paymentMethods, $storeId]);
    header('Location: /pages/pagamentos.php?success=methods_updated');
    exit;
}
$isConnected = $integration && $integration['is_active'];

// Gerar URL de autorização
$authUrl = $oauth->getAuthorizationUrl($storeId);

// Mensagens flash
$successMessage = $_GET['success'] ?? null;
$errorMessage = $_GET['error'] ?? null;

$pageTitle = 'Pagamentos';
include __DIR__ . '/../includes/dashboard-header.php';
?>
<?php include __DIR__ . '/../includes/responsive-styles.php'; ?>

<div class="dashboard-layout">
    <?php include __DIR__ . '/../includes/dashboard-sidebar.php'; ?>
    
    <main class="main-content">
        <div class="page-header">
            <div class="page-title">
                <h1><iconify-icon icon="solar:card-bold"></iconify-icon> Pagamentos</h1>
                <p class="page-subtitle">Configure como você receberá pagamentos na sua loja</p>
            </div>
        </div>

        <?php if ($successMessage === 'connected'): ?>
        <?php elseif ($successMessage === 'methods_updated'): ?>
        <div class="alert alert-success">
            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
            <span>Métodos de pagamento atualizados!</span>
        </div>
        <div class="alert alert-success">
            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
            <span>Conta Mercado Pago conectada com sucesso! Agora você pode receber pagamentos.</span>
        </div>
        <?php endif; ?>

        <?php if ($errorMessage): ?>
        <div class="alert alert-error">
            <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
            <span><?= htmlspecialchars($errorMessage === 'cancelled' ? 'Autorização cancelada pelo usuário.' : $errorMessage) ?></span>
        </div>
        <?php endif; ?>

        <!-- Payment Methods Selection -->
        <form method="POST" class="card payment-card" style="margin-bottom: 1.5rem;">
            <input type="hidden" name="action" value="update_payment_methods">
            <div class="payment-header">
                <div class="payment-brand">
                    <iconify-icon icon="solar:settings-bold" style="font-size: 1.5rem; color: var(--primary);"></iconify-icon>
                    <span style="font-size: 1.1rem; font-weight: 600;">Métodos de Pagamento</span>
                </div>
            </div>
            
            <div style="padding: 1rem 0;">
                <p style="color: var(--text-muted); margin-bottom: 1.5rem;">Escolha quais formas de pagamento estarão disponíveis para seus clientes</p>
                
                <!-- WhatsApp Option -->
                <div class="payment-method-option" style="display: flex; align-items: center; justify-content: space-between; padding: 1rem; border: 1px solid var(--border-color); border-radius: 12px; margin-bottom: 1rem; <?= $whatsappEnabled ? 'border-color: var(--primary); background: rgba(184, 148, 31, 0.05);' : '' ?>">
                    <div style="display: flex; align-items: center; gap: 1rem;">
                        <div style="width: 48px; height: 48px; background: rgba(37, 211, 102, 0.15); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <iconify-icon icon="logos:whatsapp-icon" style="font-size: 1.5rem;"></iconify-icon>
                        </div>
                        <div>
                            <div style="font-weight: 600;">Pagamento via WhatsApp</div>
                            <div style="font-size: 0.85rem; color: var(--text-muted);">Cliente combina pagamento via WhatsApp</div>
                        </div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" name="whatsapp_enabled" <?= $whatsappEnabled ? 'checked' : '' ?>>
                        <span class="toggle-slider-custom"></span>
                    </label>
                </div>
                
                <!-- Online Option -->
                <div class="payment-method-option" style="display: flex; align-items: center; justify-content: space-between; padding: 1rem; border: 1px solid var(--border-color); border-radius: 12px; <?= $onlineEnabled ? 'border-color: var(--primary); background: rgba(184, 148, 31, 0.05);' : '' ?>">
                    <div style="display: flex; align-items: center; gap: 1rem;">
                        <div style="width: 48px; height: 48px; background: rgba(0, 158, 227, 0.15); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <iconify-icon icon="solar:card-bold" style="font-size: 1.5rem; color: #009ee3;"></iconify-icon>
                        </div>
                        <div>
                            <div style="font-weight: 600;">Pagamento Online</div>
                            <div style="font-size: 0.85rem; color: var(--text-muted);">Cliente paga via Mercado Pago</div>
                        </div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" name="online_enabled" <?= $onlineEnabled ? 'checked' : '' ?>>
                        <span class="toggle-slider-custom"></span>
                    </label>
                </div>
            </div>
            
            <div style="text-align: right; padding-top: 1rem; border-top: 1px solid var(--border-color);">
                <button type="submit" class="btn btn-primary">
                    <iconify-icon icon="solar:diskette-bold"></iconify-icon>
                    Salvar Métodos
                </button>
            </div>
        </form>
        <div class="card payment-card">
            <div class="payment-header">
                <img src="/assets/img/payment/mercadopago-oficial.png" alt="Mercado Pago" class="payment-logo">
                
                <?php if ($isConnected): ?>
                <span class="status-badge status-active">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Conectado
                </span>
                <?php else: ?>
                <span class="status-badge status-inactive">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon> Não conectado
                </span>
                <?php endif; ?>
            </div>

            <?php if ($isConnected): ?>
            <div class="payment-connected">
                <div class="payment-info">
                    <div class="info-row">
                        <span class="info-label">ID da Conta:</span>
                        <span class="info-value"><?= htmlspecialchars($integration['mp_user_id'] ?? 'N/A') ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Conectado em:</span>
                        <span class="info-value"><?= date('d/m/Y H:i', strtotime($integration['connected_at'])) ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Status:</span>
                        <span class="info-value" style="color: var(--success);">Ativo e recebendo pagamentos</span>
                    </div>
                </div>
                
                <form action="/api/mercadopago-disconnect.php" method="POST" class="disconnect-form">
                    <button type="submit" class="btn btn-danger" onclick="return confirm('Tem certeza que deseja desconectar sua conta Mercado Pago?')">
                        <iconify-icon icon="solar:logout-2-bold"></iconify-icon>
                        Desconectar
                    </button>
                </form>
            </div>
            <?php else: ?>
            <div class="payment-disconnected">
                <div class="benefits-list">
                    <h3>Benefícios de conectar sua conta:</h3>
                    <ul>
                        <li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Receba pagamentos via Pix, cartão de crédito e boleto</li>
                        <li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Dinheiro cai direto na sua conta Mercado Pago</li>
                        <li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Proteção contra fraudes e chargebacks</li>
                        <li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Parcelamento em até 12x</li>
                        <li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Relatórios completos de vendas</li>
                    </ul>
                </div>
                
                <a href="<?= htmlspecialchars($authUrl) ?>" class="btn btn-primary btn-lg connect-btn">
                    <iconify-icon icon="solar:link-bold"></iconify-icon>
                    Conectar conta Mercado Pago
                </a>
                
                <p class="connect-note">
                    <iconify-icon icon="solar:shield-check-bold"></iconify-icon>
                    Conexão segura via OAuth. Não armazenamos sua senha.
                </p>
            </div>
            <?php endif; ?>
        </div>
    </main>
</div>

<style>
.payment-card {
    max-width: 700px;
}

.payment-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 1.5rem;
    border-bottom: 1px solid var(--border);
    margin-bottom: 1.5rem;
}

.payment-logo {
    height: 40px;
    object-fit: contain;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    border-radius: 50px;
    font-size: 0.85rem;
    font-weight: 600;
}

.status-active {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.status-inactive {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

.payment-connected {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}

.payment-info {
    background: var(--bg-darker);
    padding: 1rem 1.5rem;
    border-radius: 12px;
}

.info-row {
    display: flex;
    justify-content: space-between;
    padding: 0.75rem 0;
    border-bottom: 1px solid var(--border);
}

.info-row:last-child {
    border-bottom: none;
}

.info-label {
    color: var(--text-muted);
}

.info-value {
    font-weight: 600;
}

.disconnect-form {
    text-align: right;
}

.payment-disconnected {
    text-align: center;
}

.benefits-list {
    text-align: left;
    background: var(--bg-darker);
    padding: 1.5rem;
    border-radius: 12px;
    margin-bottom: 2rem;
}

.benefits-list h3 {
    margin-bottom: 1rem;
    font-size: 1rem;
}

.benefits-list ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.benefits-list li {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.5rem 0;
    color: var(--text);
}

.benefits-list iconify-icon {
    color: var(--success);
    font-size: 1.25rem;
}

.connect-btn {
    font-size: 1rem;
    padding: 1rem 2rem;
    margin-bottom: 1rem;
}

.connect-note {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    color: var(--text-muted);
    font-size: 0.85rem;
}

.connect-note iconify-icon {
    color: var(--success);
}

.alert {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1rem 1.5rem;
    border-radius: 12px;
    margin-bottom: 1.5rem;
}

.alert-success {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.alert-error {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

.btn-danger {
    background: #ef4444;
    color: white;
}

.btn-danger:hover {
    background: #dc2626;
}

.btn-lg {
    font-size: 1.1rem;
    padding: 1rem 2rem;
}

/* Toggle Switch for Payment Methods */
.toggle-switch {
    position: relative;
    display: inline-block;
    width: 52px;
    height: 28px;
}

.toggle-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider-custom {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #666;
    transition: 0.3s;
    border-radius: 28px;
}

.toggle-slider-custom:before {
    position: absolute;
    content: "";
    height: 22px;
    width: 22px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: 0.3s;
    border-radius: 50%;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.toggle-switch input:checked + .toggle-slider-custom {
    background-color: #B8941F;
}

.toggle-switch input:checked + .toggle-slider-custom:before {
    transform: translateX(24px);
}
</style>

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