<?php
/**
 * API de Pedidos - MontaLoja
 * Com integração Evolution API para notificações WhatsApp
 */

error_reporting(E_ALL);
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(["success" => false, "error" => "PHP Error: $errstr in $errfile line $errline"], JSON_UNESCAPED_UNICODE);
    exit;
});
set_exception_handler(function($e) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(["success" => false, "error" => "Exception: " . $e->getMessage()], JSON_UNESCAPED_UNICODE);
    exit;
});

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit;
}

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/plan-limits.php';
require_once __DIR__ . '/../includes/whatsapp/EvolutionAPI.php';

try {
    $pdo = getDB();
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'Database error'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (session_status() === PHP_SESSION_NONE) {
    session_name('montaloja_session');
    session_start();
}

/**
 * Enviar notificação WhatsApp via Evolution API
 */
function sendWhatsAppNotification($pdo, $storeId, $instanceName, $phone, $message) {
    $logFile = __DIR__ . '/notification_debug.log';
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - sendWhatsAppNotification called\n", FILE_APPEND);
    file_put_contents($logFile, "  storeId: $storeId, instanceName: $instanceName, phone: $phone\n", FILE_APPEND);
    try {
        // Buscar configuração global da Evolution API
        $globalStmt = $pdo->prepare("SELECT integration_type, api_url, api_key FROM whatsapp_config WHERE store_id = 0");
        $globalStmt->execute();
        $globalConfig = $globalStmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$globalConfig || ($globalConfig['integration_type'] ?? 'evolution') === 'api_send' || empty($globalConfig['api_url']) || empty($globalConfig['api_key'])) {
            return ['success' => false, 'error' => 'Evolution API não configurada ou desativada'];
        }
        
        $api = new EvolutionAPI($globalConfig['api_url'], $globalConfig['api_key'], $instanceName);
        file_put_contents($logFile, "  API URL: " . $globalConfig['api_url'] . "\n", FILE_APPEND);
        
        // Verificar se a instância está conectada
        $status = $api->getConnectionState();
        file_put_contents($logFile, "  Connection status: " . json_encode($status, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);
        
        $isConnected = false;
        if ($status['success']) {
            // Verificar em ambas as estruturas possíveis
            if (isset($status['data']['state']) && $status['data']['state'] === 'open') {
                $isConnected = true;
            } elseif (isset($status['data']['instance']['state']) && $status['data']['instance']['state'] === 'open') {
                $isConnected = true;
            }
        }
        
        if (!$isConnected) {
            file_put_contents($logFile, "  NOT CONNECTED - aborting\n", FILE_APPEND);
            return ['success' => false, 'error' => 'WhatsApp não conectado'];
        }
        file_put_contents($logFile, "  CONNECTED - sending message\n", FILE_APPEND);
        
        // Enviar mensagem
        $result = $api->sendText($phone, $message);

        if ($result['success']) {
            file_put_contents($logFile, "  SENT SUCCESSFULLY to $phone\n", FILE_APPEND);
        } else {
            file_put_contents($logFile, "  SEND FAILED: " . json_encode($result, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);
        }

        return $result;
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

/**
 * Buscar template de notificação e processar variáveis
 */
function getNotificationMessage($pdo, $storeId, $statusTrigger, $variables) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM whatsapp_order_notifications WHERE store_id = ? AND status_trigger = ? AND enabled = 1");
        $stmt->execute([$storeId, $statusTrigger]);
        $notification = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$notification || empty($notification['message_template'])) {
            return null;
        }
        
        // Substituir variáveis no template
        $message = $notification['message_template'];
        foreach ($variables as $key => $value) {
            $message = str_replace('{' . $key . '}', $value, $message);
        }
        // Normalizar \n literais em quebras de linha reais
        $message = str_replace('\n', "\n", $message);
        
        // Processar template do dono
        $ownerMessage = $notification['owner_message_template'] ?? '';
        foreach ($variables as $key => $value) {
            $ownerMessage = str_replace('{' . $key . '}', $value, $ownerMessage);
        }
        // Normalizar \n literais em quebras de linha reais
        $ownerMessage = str_replace('\n', "\n", $ownerMessage);

        return [
            'message' => $message,
            'owner_message' => $ownerMessage,
            'send_to_customer' => (bool)$notification['send_to_customer'],
            'send_to_owner' => (bool)$notification['send_to_owner']
        ];
    } catch (Exception $e) {
        return null;
    }
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$storeId = $_GET['store_id'] ?? $_POST['store_id'] ?? null;

if (!$storeId) {
    echo json_encode(['success' => false, 'error' => 'Store ID required'], JSON_UNESCAPED_UNICODE);
    exit;
}

// POST - Criar pedido
if ($method === 'POST' && $action === 'create') {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) $input = $_POST;

    $items = $input['items'] ?? [];
    if (is_string($items)) {
        $items = json_decode($items, true) ?: [];
    }
    
    $customerName = trim($input['customer_name'] ?? '');
    $customerPhone = preg_replace('/[^0-9]/', '', $input['customer_phone'] ?? '');
    $customerEmail = trim($input['customer_email'] ?? '');
    $deliveryAddress = trim($input['delivery_address'] ?? '');
    $notes = trim($input['notes'] ?? '');
    $customerId = $_SESSION['customer_id'] ?? null;
    $saveAddress = $input['save_address'] ?? false;

    if (empty($items)) {
        echo json_encode(['success' => false, 'error' => 'Carrinho vazio'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    if (empty($customerName) && empty($customerPhone)) {
        echo json_encode(['success' => false, 'error' => 'Nome e telefone obrigatórios'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // Buscar dados da loja
    $storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
    $storeStmt->execute([$storeId]);
    $store = $storeStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$store) {
        echo json_encode(['success' => false, 'error' => 'Loja não encontrada'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $pdo->beginTransaction();

    $totalAmount = 0;
    $validItems = [];
    $itemsList = [];

    foreach ($items as $item) {
        $productId = intval($item['id'] ?? 0);
        $quantity = intval($item['quantity'] ?? 1);
        if ($productId <= 0 || $quantity <= 0) continue;

        $stmt = $pdo->prepare("SELECT id, name, price, stock_quantity, image_url FROM products WHERE id = ? AND store_id = ? AND is_active = 1");
        $stmt->execute([$productId, $storeId]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$product) continue;
        if ($product['stock_quantity'] < $quantity) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'error' => "Estoque insuficiente para: {$product['name']}"], JSON_UNESCAPED_UNICODE);
            exit;
        }

        $validItems[] = [
            'product_id' => $productId,
            'name' => $product['name'],
            'quantity' => $quantity,
            'unit_price' => floatval($product['price']),
            'options' => $item['options'] ?? $item['variations'] ?? null,
            'image_url' => $product['image_url'] ?? null
        ];
        $totalAmount += floatval($product['price']) * $quantity;
        $itemsList[] = "{$quantity}x {$product['name']}";
    }

    if (empty($validItems)) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'error' => 'Nenhum item válido'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $expiresAt = date('Y-m-d H:i:s', strtotime('+24 hours'));

    // Verificar limite de pedidos do mês
    $orderLimit = canReceiveOrder($pdo, $storeId);
    if (!$orderLimit['allowed']) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'error' => $orderLimit['message']], JSON_UNESCAPED_UNICODE);
        exit;
    }
    // Gerar token único para consulta do pedido (guests)
    $trackingToken = md5(uniqid(mt_rand(), true));
    $stmt = $pdo->prepare("INSERT INTO orders (store_id, customer_id, customer_name, customer_phone, customer_email, delivery_address, total_amount, status, payment_method, notes, expires_at, tracking_token, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', 'whatsapp', ?, ?, ?, NOW(), NOW())");
    $stmt->execute([$storeId, $customerId, $customerName, $customerPhone, $customerEmail ?: null, $deliveryAddress ?: null, $totalAmount, $notes ?: null, $expiresAt, $trackingToken]);

    $orderId = $pdo->lastInsertId();

    foreach ($validItems as $item) {
        $stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, unit_price, options) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$orderId, $item['product_id'], $item['quantity'], $item['unit_price'], $item['options'] ? json_encode($item['options'], JSON_UNESCAPED_UNICODE) : null]);

        $stmt = $pdo->prepare("UPDATE products SET stock_quantity = stock_quantity - ? WHERE id = ?");
        $stmt->execute([$item['quantity'], $item['product_id']]);
    }

    $pdo->commit();

    // Criar notificação de novo pedido no dashboard
    try {
        $firstProductName = $validItems[0]['name'] ?? 'Produto';
        $firstProductImage = $validItems[0]['image_url'] ?? null;
        $totalProducts = count($validItems);
        
        // Montar mensagem da notificação
        if ($totalProducts === 1) {
            $notifMessage = "Novo pedido: {$validItems[0]['quantity']}x {$firstProductName}";
        } else {
            $notifMessage = "Novo pedido: {$firstProductName} e mais " . ($totalProducts - 1) . " produto(s)";
        }
        $notifMessage .= " - Total: R$ " . number_format($totalAmount, 2, ',', '.');
        
        $notifStmt = $pdo->prepare("
            INSERT INTO notifications (store_id, type, title, message, link, icon, image_url, is_read, created_at)
            VALUES (?, 'order', 'Novo Pedido', ?, ?, 'solar:bag-check-bold', ?, 0, NOW())
        ");
        $notifStmt->execute([
            $storeId,
            $notifMessage,
            "/pages/pedidos/ver.php?id={$orderId}",
            $firstProductImage
        ]);
    } catch (Exception $e) {
        // Não impede o pedido se falhar a notificação
    }


    // Salvar novo endereço se solicitado
    if ($saveAddress && $customerId && !empty($saveAddress['cep']) && !empty($saveAddress['street'])) {
        try {
            $stmtAddr = $pdo->prepare("INSERT INTO customer_addresses (customer_id, store_id, label, cep, street, number, complement, neighborhood, city, state, is_default, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NOW())");
            $stmtAddr->execute([
                $customerId,
                $storeId,
                'Entrega',
                $saveAddress['cep'],
                $saveAddress['street'],
                $saveAddress['number'] ?? '',
                $saveAddress['complement'] ?? '',
                $saveAddress['neighborhood'] ?? '',
                $saveAddress['city'] ?? '',
                $saveAddress['state'] ?? ''
            ]);
        } catch (Exception $e) {
            // Ignorar erro ao salvar endereço - não impede o pedido
        }
    }

    $whatsapp = preg_replace('/[^0-9]/', '', $store['whatsapp_number'] ?? $store['whatsapp'] ?? '');
    $instanceName = $store['slug'];

    // Preparar variáveis para o template
    $templateVariables = [
        'cliente' => $customerName,
        'pedido' => $orderId,
        'valor' => number_format($totalAmount, 2, ',', '.'),
        'itens' => implode(', ', $itemsList),
        'endereco' => $deliveryAddress ?: 'Não informado',
        'loja' => $store['name'],
        'telefone' => $customerPhone
    ];

    // Obter configuração global para ver o tipo de integração ativo
    $globalStmt = $pdo->prepare("SELECT integration_type FROM whatsapp_config WHERE store_id = 0");
    $globalStmt->execute();
    $globalConfig = $globalStmt->fetch(PDO::FETCH_ASSOC);
    $isEvolution = ($globalConfig['integration_type'] ?? 'evolution') === 'evolution';

    // Buscar template de notificação
    $notificationResult = getNotificationMessage($pdo, $storeId, 'pending', $templateVariables);

    // Montar mensagem genérica (fallback ou principal)
    $fallbackMessage = "🛒 *PEDIDO #$orderId*\n\n";
    $fallbackMessage .= "👤 *Cliente:* $customerName\n📱 *Telefone:* $customerPhone\n";
    if ($deliveryAddress) $fallbackMessage .= "📍 *Endereço:* $deliveryAddress\n";
    $fallbackMessage .= "\n*Itens:*\n";
    foreach ($validItems as $item) {
        $subtotal = $item['unit_price'] * $item['quantity'];
        $fallbackMessage .= "• {$item['quantity']}x {$item['name']} - R$ " . number_format($subtotal, 2, ',', '.') . "\n";
    }
    $fallbackMessage .= "\n💰 *Total:* R$ " . number_format($totalAmount, 2, ',', '.') . "\n";
    if ($notes) $fallbackMessage .= "\n📝 *Obs:* $notes\n";

    // Mensagem para o API Send
    $apiSendMessage = $fallbackMessage;
    if ($notificationResult && !empty($notificationResult['owner_message'])) {
        $apiSendMessage = $notificationResult['owner_message'];
    } elseif ($notificationResult && !empty($notificationResult['message'])) {
        $apiSendMessage = $notificationResult['message'];
    }

    // Tentar enviar via Evolution API
    $evolutionSent = false;
    $logFile = __DIR__ . '/notification_debug.log';
    
    if ($isEvolution) {
        file_put_contents($logFile, "\n=== " . date('Y-m-d H:i:s') . " ORDER CREATE ===\n", FILE_APPEND);
        file_put_contents($logFile, "storeId: $storeId, instanceName: $instanceName, customerPhone: $customerPhone\n", FILE_APPEND);
        file_put_contents($logFile, "notificationResult: " . ($notificationResult ? "found" : "null") . "\n", FILE_APPEND);
        
        $sentToOwner = false;
        
        if ($notificationResult && (!empty($notificationResult['message']) || !empty($notificationResult['owner_message']))) {
            // Enviar para o cliente se configurado
            if ($notificationResult['send_to_customer'] && $customerPhone && !empty($notificationResult['message'])) {
                $sendResult = sendWhatsAppNotification($pdo, $storeId, $instanceName, $customerPhone, $notificationResult['message']);
            }
            
            // Enviar para o dono da loja se configurado
            if ($notificationResult['send_to_owner'] && $whatsapp) {
                $ownerMsg = !empty($notificationResult['owner_message']) ? $notificationResult['owner_message'] : $fallbackMessage;
                $res = sendWhatsAppNotification($pdo, $storeId, $instanceName, $whatsapp, $ownerMsg);
                if ($res['success']) $sentToOwner = true;
            }
        } else {
            // Se não tem template, envia a mensagem genérica para o dono da loja
            if ($whatsapp) {
                $res = sendWhatsAppNotification($pdo, $storeId, $instanceName, $whatsapp, $fallbackMessage);
                if ($res['success']) $sentToOwner = true;
            }
        }
        
        // Se a API está ativada, marcamos como sent para não redirecionar para a URL
        $evolutionSent = true; 
    }

    // Enviar mensagem raw para o JavaScript montar a URL client-side
    // O browser lida nativamente com Unicode/emojis no encodeURIComponent
    echo json_encode([
        'success' => true,
        'order_id' => $orderId,
        'total' => $totalAmount,
        'whatsapp_phone' => $whatsapp,
        'whatsapp_message' => $apiSendMessage,
        'notification_sent' => $evolutionSent,
        'tracking_token' => $trackingToken
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// GET - Buscar pedido
if ($method === 'GET' && $action === 'get') {
    $orderId = intval($_GET['order_id'] ?? 0);
    if (!$orderId) {
        echo json_encode(['success' => false, 'error' => 'Order ID required'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? AND store_id = ?");
    $stmt->execute([$orderId, $storeId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        echo json_encode(['success' => false, 'error' => 'Order not found'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $stmt = $pdo->prepare("SELECT oi.*, p.name as product_name FROM order_items oi LEFT JOIN products p ON oi.product_id = p.id WHERE oi.order_id = ?");
    $stmt->execute([$orderId]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['success' => true, 'order' => $order, 'items' => $items], JSON_UNESCAPED_UNICODE);
    exit;
}

// GET - Listar pedidos
if ($method === 'GET' && $action === 'list') {
    $status = $_GET['status'] ?? null;
    $sql = "SELECT * FROM orders WHERE store_id = ?";
    $params = [$storeId];
    if ($status) {
        $sql .= " AND status = ?";
        $params[] = $status;
    }
    $sql .= " ORDER BY created_at DESC LIMIT 50";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['success' => true, 'orders' => $orders], JSON_UNESCAPED_UNICODE);
    exit;
}

// PUT - Atualizar status (com notificação)
if ($method === 'PUT' && $action === 'update_status') {
    $input = json_decode(file_get_contents('php://input'), true);
    $orderId = intval($input['order_id'] ?? 0);
    $newStatus = $input['status'] ?? '';

    $validStatuses = ['pending', 'confirmed', 'preparing', 'shipped', 'delivered', 'cancelled', 'canceled'];
    if (!in_array($newStatus, $validStatuses)) {
        echo json_encode(['success' => false, 'error' => 'Invalid status'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // Buscar dados do pedido
    $orderStmt = $pdo->prepare("SELECT o.*, s.name as store_name, s.slug as store_slug FROM orders o JOIN stores s ON o.store_id = s.id WHERE o.id = ? AND o.store_id = ?");
    $orderStmt->execute([$orderId, $storeId]);
    $order = $orderStmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        echo json_encode(['success' => false, 'error' => 'Order not found'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // Atualizar status
    $stmt = $pdo->prepare("UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ? AND store_id = ?");
    $stmt->execute([$newStatus, $orderId, $storeId]);

    // Buscar itens do pedido para a mensagem
    $itemsStmt = $pdo->prepare("SELECT oi.quantity, p.name FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = ?");
    $itemsStmt->execute([$orderId]);
    $orderItems = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
    $itemsList = array_map(fn($i) => "{$i['quantity']}x {$i['name']}", $orderItems);

    // Preparar variáveis para o template
    $templateVariables = [
        'cliente' => $order['customer_name'],
        'pedido' => $orderId,
        'valor' => number_format($order['total_amount'], 2, ',', '.'),
        'itens' => implode(', ', $itemsList),
        'endereco' => $order['delivery_address'] ?: 'Não informado',
        'loja' => $order['store_name'],
        'telefone' => $order['customer_phone']
    ];

    // Tentar enviar notificação
    $notificationResult = getNotificationMessage($pdo, $storeId, $newStatus, $templateVariables);
    
    if ($notificationResult && !empty($notificationResult['message']) && $notificationResult['send_to_customer']) {
        sendWhatsAppNotification($pdo, $storeId, $order['store_slug'], $order['customer_phone'], $notificationResult['message']);
    }

    echo json_encode(['success' => true], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode(['success' => false, 'error' => 'Invalid action'], JSON_UNESCAPED_UNICODE);
