<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/Payment/PaymentFactory.php';



$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Método não permitido.';
    echo json_encode($response);
    exit;
}

$pdo = getDB();

try {
    // Validar dados
    $businessType = $_POST['business_type'] ?? 'retail';
    $storeName = trim($_POST['store_name'] ?? '');
    $subdomain = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', trim($_POST['subdomain'] ?? '')));
    $ownerName = trim($_POST['owner_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $planId = $_POST['plan_id'] ?? 'free';
    $paymentMethod = $_POST['payment_method'] ?? 'credit_card';

    // Validações
    if (empty($storeName)) throw new Exception('Nome da loja é obrigatório.');
    if (strlen($subdomain) < 3) throw new Exception('O endereço deve ter no mínimo 3 caracteres.');
    if (empty($ownerName)) throw new Exception('Seu nome é obrigatório.');
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) throw new Exception('E-mail inválido.');
    if (strlen($password) < 6) throw new Exception('A senha deve ter no mínimo 6 caracteres.');
    if ($password !== $confirmPassword) throw new Exception('As senhas não conferem.');

    // Verificar subdomínio
    $checkSubdomain = $pdo->prepare("SELECT id FROM stores WHERE subdomain = ?");
    $checkSubdomain->execute([$subdomain]);
    if ($checkSubdomain->fetch()) throw new Exception('Este endereço já está em uso.');

    // Verificar email
    $checkEmail = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $checkEmail->execute([$email]);
    if ($checkEmail->fetch()) throw new Exception('Este e-mail já está cadastrado.');

    // Buscar plano
    $planStmt = $pdo->prepare("SELECT * FROM plans WHERE id = ? AND is_active = 1");
    $planStmt->execute([$planId]);
    $plan = $planStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$plan || $plan['price_monthly'] <= 0) {
        throw new Exception('Plano inválido para pagamento.');
    }

    // Gerar token único
    $token = bin2hex(random_bytes(32));
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    $expiresAt = date('Y-m-d H:i:s', strtotime('+24 hours'));

    // Salvar cadastro pendente
    $insertPending = $pdo->prepare("
        INSERT INTO pending_registrations 
        (token, business_type, store_name, subdomain, owner_name, phone, email, password_hash, plan_id, payment_method, expires_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $insertPending->execute([
        $token, $businessType, $storeName, $subdomain, $ownerName, 
        preg_replace('/\D/', '', $phone), $email, $passwordHash, $planId, $paymentMethod, $expiresAt
    ]);
    $pendingId = $pdo->lastInsertId();

    // Criar preferência de pagamento no MercadoPago
    $factory = new \Payment\PaymentFactory($pdo);
    $gateway = $factory->getActiveGateway();
    
    if (!$factory->hasActiveGateway()) {
        throw new Exception('Nenhum gateway de pagamento ativo.');
    }

    $adapter = $factory->create();
    $baseUrl = 'https://dev.duolead.com.br';

    $checkoutResult = $adapter->createCheckoutSession(
        (float) $plan['price_monthly'],
        [
            'email' => $email,
            'name' => $ownerName,
            'external_reference' => $token,
            'webhook_url' => $baseUrl . '/api/webhook-registration.php'
        ],
        [
            ['title' => 'Plano ' . $plan['name'] . ' - MontaLoja', 'quantity' => 1, 'unit_price' => (float) $plan['price_monthly']]
        ],
        $baseUrl . '/pages/cadastro/payment-success.php?token=' . $token,
        $baseUrl . '/pages/cadastro/payment-failed.php?token=' . $token
    );

    if (!$checkoutResult['success']) {
        throw new Exception('Erro ao criar pagamento: ' . ($checkoutResult['error'] ?? 'Erro desconhecido'));
    }

    // Atualizar com preference_id
    $updatePending = $pdo->prepare("UPDATE pending_registrations SET preference_id = ? WHERE id = ?");
    $updatePending->execute([$checkoutResult['preference_id'], $pendingId]);

    $response['success'] = true;
    $response['checkout_url'] = $checkoutResult['checkout_url'];
    $response['token'] = $token;

} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
