<?php
/**
 * Página de sucesso após pagamento
 * Verifica status, cria loja se necessário e faz auto-login
 */
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/Payment/PaymentFactory.php';

use Payment\PaymentFactory;

$token = $_GET['token'] ?? '';
$pdo = getDB();

if (empty($token)) {
    header('Location: /pages/cadastro/');
    exit;
}

// Buscar registro pendente
$stmt = $pdo->prepare("SELECT * FROM pending_registrations WHERE token = ?");
$stmt->execute([$token]);
$pending = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$pending) {
    header('Location: /pages/cadastro/?error=invalid_token');
    exit;
}

// Se já foi processado, verificar se loja existe e fazer login
if ($pending['status'] === 'paid') {
    $userStmt = $pdo->prepare("SELECT u.*, s.subdomain FROM users u JOIN stores s ON u.store_id = s.id WHERE u.email = ?");
    $userStmt->execute([$pending['email']]);
    $user = $userStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user) {
        // Auto-login
        session_start();
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['store_id'] = $user['store_id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['user_email'] = $user['email'];
        $_SESSION['user_role'] = $user['role'];
        
        header('Location: /dashboard.php?welcome=1');
        exit;
    }
}

// Se ainda pendente, verificar pagamento no MercadoPago
if ($pending['status'] === 'pending') {
    // Verificar parâmetros de retorno do MercadoPago
    $paymentId = $_GET['payment_id'] ?? null;
    $paymentStatus = $_GET['status'] ?? null;
    
    if ($paymentStatus === 'approved' || $paymentId) {
        // Criar loja manualmente se webhook ainda não processou
        try {
            createStoreFromPending($pdo, $token, $pending);
            
            // Fazer login
            $userStmt = $pdo->prepare("SELECT u.*, s.subdomain FROM users u JOIN stores s ON u.store_id = s.id WHERE u.email = ?");
            $userStmt->execute([$pending['email']]);
            $user = $userStmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                session_start();
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['store_id'] = $user['store_id'];
                $_SESSION['user_name'] = $user['name'];
                $_SESSION['user_email'] = $user['email'];
                $_SESSION['user_role'] = $user['role'];
                
                header('Location: /dashboard.php?welcome=1');
                exit;
            }
        } catch (Exception $e) {
            error_log("Error creating store: " . $e->getMessage());
        }
    }
}

function createStoreFromPending($pdo, $token, $pending) {
    // Verificar se já existe
    $checkStore = $pdo->prepare("SELECT id FROM stores WHERE subdomain = ?");
    $checkStore->execute([$pending['subdomain']]);
    if ($checkStore->fetch()) {
        return; // Já existe
    }

    $baseDomain = 'duolead.com.br';
    $storeTypeMap = ['retail' => 'clothing_store', 'service' => 'barbershop', 'food' => 'restaurant', 'other' => 'other'];
    $storeType = $storeTypeMap[$pending['business_type']] ?? 'other';

    $pdo->beginTransaction();

    try {
        // Criar loja
        $insertStore = $pdo->prepare("
            INSERT INTO stores (name, type, business_type, slug, subdomain, whatsapp_number, email, plan_id, status, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW())
        ");
        $insertStore->execute([
            $pending['store_name'], $storeType, $pending['business_type'], $pending['subdomain'], 
            $pending['subdomain'], $pending['phone'], $pending['email'], $pending['plan_id']
        ]);
        $storeId = $pdo->lastInsertId();

        // Criar usuário
        $insertUser = $pdo->prepare("
            INSERT INTO users (store_id, name, email, password_hash, phone, role, is_active, created_at)
            VALUES (?, ?, ?, ?, ?, 'owner', 1, NOW())
        ");
        $insertUser->execute([
            $storeId, $pending['owner_name'], $pending['email'], $pending['password_hash'], $pending['phone']
        ]);
        $userId = $pdo->lastInsertId();

        // Atualizar loja com owner
        $updateStore = $pdo->prepare("UPDATE stores SET owner_user_id = ? WHERE id = ?");
        $updateStore->execute([$userId, $storeId]);

        // Marcar registro como pago
        $updatePending = $pdo->prepare("UPDATE pending_registrations SET status = 'paid' WHERE token = ?");
        $updatePending->execute([$token]);

        $pdo->commit();

    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
}

// Se chegou aqui, mostrar página de aguardando
$pageTitle = 'Processando Pagamento';
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?> - MontaLoja</title>
    <script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.8/dist/iconify-icon.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Inter', sans-serif; background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; }
        .container { background: white; padding: 3rem; border-radius: 16px; text-align: center; max-width: 400px; }
        .spinner { animation: spin 1s linear infinite; font-size: 3rem; color: #CCA43B; margin-bottom: 1rem; }
        @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        h2 { margin-bottom: 0.5rem; }
        p { color: #666; margin-bottom: 1rem; }
    </style>
</head>
<body>
    <div class="container">
        <iconify-icon icon="solar:refresh-bold" class="spinner"></iconify-icon>
        <h2>Processando seu pagamento...</h2>
        <p>Aguarde enquanto confirmamos seu pagamento. Você será redirecionado automaticamente.</p>
    </div>
    <script>
        // Reload page every 3 seconds to check payment status
        setTimeout(() => location.reload(), 3000);
    </script>
</body>
</html>
