<?php
/**
 * API - Criar Checkout de Assinatura
 * Integração com PaymentFactory para processar pagamentos
 */
header('Content-Type: application/json');

require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/Payment/PaymentFactory.php';

use Payment\PaymentFactory;

// Verificar autenticação
session_start();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Não autenticado']);
    exit;
}

// Verificar método
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Método não permitido']);
    exit;
}

try {
    $pdo = getDB();
    
    // Dados do request
    $input = json_decode(file_get_contents('php://input'), true);
    $planId = $input['plan_id'] ?? null;
    $paymentMethod = $input['payment_method'] ?? 'checkout'; // 'pix' ou 'checkout'
    
    if (!$planId) {
        throw new Exception('ID do plano não informado');
    }
    
    // Buscar dados do plano
    $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ? AND is_active = 1");
    $stmt->execute([$planId]);
    $plan = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$plan) {
        throw new Exception('Plano não encontrado ou inativo');
    }
    
    // Buscar dados do usuário
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Inicializar PaymentFactory
    $factory = new PaymentFactory($pdo);
    $gateway = $factory->create();
    
    // Preparar dados do cliente
    $customerData = [
        'email' => $user['email'] ?? '',
        'name' => $user['name'] ?? 'Cliente',
        'phone' => $user['phone'] ?? ''
    ];
    
    // Preparar item
    $items = [
        [
            'title' => 'Plano ' . $plan['name'],
            'description' => $plan['description'] ?? 'Assinatura mensal',
            'quantity' => 1,
            'unit_price' => (float) $plan['price_monthly']
        ]
    ];
    
    $amount = (float) $plan['price_monthly'];
    
    // URLs de callback
    $baseUrl = 'https://' . ($_SERVER['HTTP_HOST'] ?? 'dev.duolead.com.br');
    $successUrl = $baseUrl . '/pages/assinatura.php?status=success&plan=' . $planId;
    $failureUrl = $baseUrl . '/pages/assinatura.php?status=failure&plan=' . $planId;
    
    if ($paymentMethod === 'pix') {
        // Criar pagamento PIX
        $result = $gateway->createTransaction($amount, $customerData, $items, 'pix');
        
        // Salvar transação no banco
        $stmt = $pdo->prepare("
            INSERT INTO payment_transactions 
            (gateway_id, external_id, user_id, amount, status, type, metadata)
            VALUES (?, ?, ?, ?, 'pending', 'pix', ?)
        ");
        $stmt->execute([
            $factory->getActiveGateway()['id'] ?? 1,
            $result['transaction_id'] ?? null,
            $userId,
            $amount,
            json_encode([
                'plan_id' => $planId,
                'plan_name' => $plan['name'],
                'store_id' => $storeId
            ])
        ]);
        
        echo json_encode([
            'success' => true,
            'type' => 'pix',
            'qr_code' => $result['pix_qr_code'] ?? null,
            'qr_code_base64' => $result['pix_qr_code_base64'] ?? null,
            'pix_code' => $result['pix_copy_paste'] ?? null,
            'transaction_id' => $result['transaction_id'] ?? null,
            'expires_at' => $result['expiration_date'] ?? null
        ]);
    } else {
        // Criar sessão de checkout (cartão, boleto, etc via MercadoPago Checkout Pro)
        $result = $gateway->createCheckoutSession($amount, $customerData, $items, $successUrl, $failureUrl);
        
        // Salvar transação no banco
        $stmt = $pdo->prepare("
            INSERT INTO payment_transactions 
            (gateway_id, external_id, user_id, amount, status, type, metadata, checkout_url)
            VALUES (?, ?, ?, ?, 'pending', 'checkout', ?, ?)
        ");
        $stmt->execute([
            $factory->getActiveGateway()['id'] ?? 1,
            $result['preference_id'] ?? $result['transaction_id'] ?? null,
            $userId,
            $amount,
            json_encode([
                'plan_id' => $planId,
                'plan_name' => $plan['name'],
                'store_id' => $storeId
            ]),
            $result['checkout_url'] ?? $result['init_point'] ?? null
        ]);
        
        echo json_encode([
            'success' => true,
            'type' => 'redirect',
            'checkout_url' => $result['checkout_url'] ?? $result['init_point'] ?? null,
            'preference_id' => $result['preference_id'] ?? $result['transaction_id'] ?? null
        ]);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
