<?php
/**
 * Store Checkout API
 * Cria checkout do Mercado Pago para lojistas conectados via OAuth
 */

header('Content-Type: application/json');

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/Payment/MercadoPagoOAuth.php';
require_once __DIR__ . '/../includes/Payment/PaymentGatewayInterface.php';
require_once __DIR__ . '/../includes/Payment/MercadoPagoAdapter.php';

use Payment\MercadoPagoOAuth;
use Payment\MercadoPagoAdapter;

try {
    $pdo = getDB();
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Dados inválidos');
    }
    
    $storeId = $input['store_id'] ?? null;
    $orderId = $input['order_id'] ?? null;
    $items = $input['items'] ?? [];
    $customerData = $input['customer'] ?? [];
    $totalAmount = $input['total'] ?? 0;
    
    if (!$storeId || !$orderId) {
        throw new Exception('Store ID e Order ID são obrigatórios');
    }
    
    // Get store info
    $storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
    $storeStmt->execute([$storeId]);
    $store = $storeStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$store) {
        throw new Exception('Loja não encontrada');
    }
    
    // Get store's MP integration
    $oauth = new MercadoPagoOAuth($pdo);
    $integration = $oauth->getIntegration($storeId);
    
    if (!$integration || !$integration['is_active']) {
        throw new Exception('Loja não tem integração Mercado Pago ativa');
    }
    
    // Decrypt access token
    $accessToken = $integration['mp_access_token'];
    
    if (!$accessToken) {
        throw new Exception('Token de acesso inválido');
    }
    
    // Create MP adapter with store's credentials
    $mpAdapter = new MercadoPagoAdapter($accessToken, '', 'production');
    
    // Build items for preference
    $preferenceItems = [];
    foreach ($items as $item) {
        $preferenceItems[] = [
            'title' => $item['name'] ?? 'Produto',
            'quantity' => (int)($item['quantity'] ?? 1),
            'unit_price' => (float)($item['price'] ?? 0)
        ];
    }
    
    // If no items, create single item with total
    if (empty($preferenceItems)) {
        $preferenceItems[] = [
            'title' => 'Pedido #' . $orderId,
            'quantity' => 1,
            'unit_price' => (float)$totalAmount
        ];
    }
    
    // Get store subdomain for URLs
    $storeSubdomain = $store['subdomain'] ?? $store['slug'];
    $baseUrl = "https://{$storeSubdomain}.duolead.com.br";
    
    $successUrl = $baseUrl . '/pedido/' . $orderId . '?payment=success';
    $failureUrl = $baseUrl . '/pedido/' . $orderId . '?payment=failed';
    
    // Create checkout session
    $result = $mpAdapter->createCheckoutSession(
        (float)$totalAmount,
        [
            'email' => $customerData['email'] ?? 'cliente@email.com',
            'name' => $customerData['name'] ?? 'Cliente',
            'external_reference' => 'order_' . $orderId . '_store_' . $storeId,
            'webhook_url' => 'https://duolead.com.br/api/webhook-store-payment.php'
        ],
        $preferenceItems,
        $successUrl,
        $failureUrl
    );
    
    if ($result['success']) {
        // Update order with payment info
        $updateStmt = $pdo->prepare("UPDATE orders SET 
            payment_method = 'mercadopago',
            payment_status = 'pending',
            mp_preference_id = ?
            WHERE id = ?");
        $updateStmt->execute([$result['preference_id'], $orderId]);
        
        echo json_encode([
            'success' => true,
            'checkout_url' => $result['checkout_url'],
            'preference_id' => $result['preference_id']
        ]);
    } else {
        throw new Exception($result['error'] ?? 'Erro ao criar checkout');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
