<?php
/**
 * Webhook para processar pagamentos de cadastro
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/Payment/PaymentFactory.php';

use Payment\PaymentFactory;

// Log para debug
file_put_contents(__DIR__ . '/../logs/webhook-registration.log', date('Y-m-d H:i:s') . " - Webhook received\n", FILE_APPEND);

$pdo = getDB();

// Ler dados do webhook
$input = file_get_contents('php://input');
$data = json_decode($input, true);

file_put_contents(__DIR__ . '/../logs/webhook-registration.log', date('Y-m-d H:i:s') . " - Data: " . $input . "\n", FILE_APPEND);

if (empty($data)) {
    http_response_code(400);
    exit('Invalid data');
}

try {
    // MercadoPago envia topics diferentes
    $topic = $data['topic'] ?? $data['type'] ?? '';
    $paymentId = null;

    if ($topic === 'payment' || $topic === 'payment.created' || $topic === 'payment.updated') {
        $paymentId = $data['data']['id'] ?? $data['id'] ?? null;
    }

    if (!$paymentId) {
        http_response_code(200);
        exit('OK - No payment to process');
    }

    // Buscar detalhes do pagamento no MercadoPago
    $factory = new PaymentFactory($pdo);
    $gateway = $factory->getActiveGateway();
    
    if (!$gateway) {
        throw new Exception('No active gateway');
    }

    $adapter = $factory->createAdapter($gateway);
    $paymentDetails = $adapter->getTransactionStatus($paymentId);

    if (!$paymentDetails['success']) {
        throw new Exception('Failed to get payment details');
    }

    $status = $paymentDetails['status'] ?? '';
    $externalReference = $paymentDetails['external_reference'] ?? '';

    file_put_contents(__DIR__ . '/../logs/webhook-registration.log', 
        date('Y-m-d H:i:s') . " - Payment ID: {$paymentId}, Status: {$status}, Ref: {$externalReference}\n", FILE_APPEND);

    // Se pagamento aprovado, criar a loja
    if ($status === 'approved' && !empty($externalReference)) {
        createStoreFromPending($pdo, $externalReference);
    }

    http_response_code(200);
    echo 'OK';

} catch (Exception $e) {
    file_put_contents(__DIR__ . '/../logs/webhook-registration.log', 
        date('Y-m-d H:i:s') . " - Error: " . $e->getMessage() . "\n", FILE_APPEND);
    http_response_code(500);
    echo 'Error: ' . $e->getMessage();
}

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

    if (!$pending) {
        throw new Exception('Pending registration not found or already processed');
    }

    $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();

        file_put_contents(__DIR__ . '/../logs/webhook-registration.log', 
            date('Y-m-d H:i:s') . " - Store created: ID {$storeId}, User ID: {$userId}\n", FILE_APPEND);

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