<?php
require_once '../controllers/controller_carrito.php';
require_once '../models/model_pedido.php';
require_once '../services/config_mercadopago.php';
require_once '../config/app_config.php';
require_once '../vendor/autoload.php';
use MercadoPago\Client\Preference\PreferenceClient;
use MercadoPago\MercadoPagoConfig;

if (!defined('MERCADOPAGO_ACCESS_TOKEN')) {
    error_log("Error: La constante MERCADOPAGO_ACCESS_TOKEN no está definida.");
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Error de configuración del Access Token de Mercado Pago']);
    exit();
}

MercadoPagoConfig::setAccessToken(MERCADOPAGO_ACCESS_TOKEN);
error_log("=== INICIO procesar_pedido.php ===");
error_log("Datos POST recibidos: " . print_r($_POST, true));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    session_start();
    try {
        $controller = new CarritoController();
        $cartItemsJson = $_POST['cartItems'] ?? '[]';
        $cartItems = json_decode($cartItemsJson, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("Formato inválido de los productos del carrito: " . json_last_error_msg());
        }
        if (empty($cartItems)) {
            throw new Exception("El carrito está vacío");
        }
        $totalAmount = $_POST['totalAmount'] ?? 0;
        if ($totalAmount <= 0) {
            $totalAmount = array_reduce($cartItems, function ($sum, $item) {
                $price = $item['price'] ?? $item['precio'] ?? 0;
                $quantity = $item['quantity'] ?? $item['qty'] ?? $item['cantidad'] ?? 1;
                return $sum + ($price * $quantity);
            }, 0);
        }
        $paymentMethod = $_POST['paymentMethod'] ?? 'cash';
        $orderData = [
            'fullName' => trim($_POST['fullName'] ?? ''),
            'phoneNumber' => trim($_POST['phoneNumber'] ?? ''),
            'addressText' => trim($_POST['addressText'] ?? ''),
            'references' => trim($_POST['references'] ?? ''),
            'deliveryRequested' => $_POST['deliveryRequested'] ?? '0',
            'totalAmount' => (float)$totalAmount,
            'cartItems' => $cartItemsJson,
            'decodedCartItems' => $cartItems,
            'orderDate' => $_POST['orderDate'] ?? date('Y-m-d H:i:s'),
            'latitude' => !empty($_POST['latitude']) ? (float)$_POST['latitude'] : null,
            'longitude' => !empty($_POST['longitude']) ? (float)$_POST['longitude'] : null,
            'paymentMethod' => $paymentMethod
        ];
        $result = $controller->processOrder($orderData);
        if ($result && isset($result['id_pedido'])) {
            if ($paymentMethod === 'mercadopago') {
                $items = [];
                foreach ($orderData['decodedCartItems'] as $item) {
                    if (isset($item['id'], $item['title'], $item['price'], $item['quantity']) && $item['quantity'] > 0) {
                        $items[] = [
                            'id' => $item['id'],
                            'title' => $item['title'],
                            'quantity' => (int)$item['quantity'],
                            'unit_price' => (float)$item['price'],
                            'currency_id' => 'MXN'
                        ];
                    }
                }
                
                // --- INICIO DEPURACIÓN VISUAL ---
                if (empty($items)) {
                    header('Content-Type: application/json');
                    echo json_encode([
                        'success' => false,
                        'message' => 'Error: El array de items para Mercado Pago está vacío.',
                        'debug_decodedCartItems' => $orderData['decodedCartItems']
                    ]);
                    exit();
                }

                $pedidoCreado = (new \Pedido())->getPedidoById($result['id_pedido']);
                $costoEnvio = (float)($pedidoCreado['costo_envio_aplicado'] ?? 0);
                if ($costoEnvio > 0) {
                    $items[] = [
                        'id' => 'envio',
                        'title' => 'Envío a domicilio',
                        'quantity' => 1,
                        'unit_price' => $costoEnvio,
                        'currency_id' => 'MXN',
                    ];
                }

                $baseUrl = APP_BASE_URL;
                $returnUrl = $baseUrl . '/services/mercado_pago_return.php?id=' . $result['id_pedido'];
                $webhookUrl = $baseUrl . '/services/mercadopago_webhook.php';

                $client = new PreferenceClient();

                $preference = $client->create([
                    'items' => $items,
                    'payer' => [
                        'name' => $orderData['fullName'],
                        'email' => 'pedidos@taqueriaelmexicano.com',
                        'phone' => ['number' => $orderData['phoneNumber']]
                    ],
                    'back_urls' => [
                        'success' => $returnUrl,
                        'failure' => $returnUrl,
                        'pending' => $returnUrl,
                    ],
                    'notification_url' => $webhookUrl,
                    'external_reference' => (string)$result['id_pedido'],
                    'auto_return' => 'approved',
                    'binary_mode' => true,
                    'statement_descriptor' => 'TAQUERIA EL MEXICANO'
                ]);
                $controller->updatePedidoMercadoPagoId($result['id_pedido'], $preference->id);
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => true,
                    'message' => 'Preference created',
                    'preferenceId' => $preference->id,
                    'redirect_url' => $preference->init_point
                ]);
                exit();
            } else {
                $coordsParams = '';
                if (!empty($result['latitude']) && !empty($result['longitude'])) {
                    $coordsParams = "&lat=" . urlencode($result['latitude']) . "&lng=" . urlencode($result['longitude']);
                }
                header("Location: ../views/confirmacion_pedido.php?id=" . $result['id_pedido'] . $coordsParams);
                exit();
            }
        } else {
            throw new Exception("No se pudo obtener el ID del pedido después del procesamiento");
        }
    } catch (Exception $e) {
        error_log("Error en procesar_pedido.php: " . $e->getMessage());
        $paymentMethod = $_POST['paymentMethod'] ?? 'cash';
        if ($paymentMethod === 'mercadopago') {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        } else {
            $msg = urlencode($e->getMessage());
            header('Location: carrito.php?error=' . $msg);
        }
        exit();
    }
} else {
    header("Location: ../views/carrito.php");
    exit();
}
?>