<?php
// process_purchase.php
require_once 'config/db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) {
    die("Error: User not logged in");
}

$buyer_id   = $_SESSION['user_id'];
$product_id = $_POST['product_id'] ?? null;
$qty        = isset($_POST['qty']) ? (int)$_POST['qty'] : 1;

if (!$product_id) {
    header("Location: index.php?error=no_product");
    exit;
}

try {
    $pdo->beginTransaction();

    // 1. OBTENER PRODUCTO Y BLOQUEAR FILA (Seguridad contra compras simultáneas)
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? FOR UPDATE");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();

    if (!$product) throw new Exception("Product not found.");
    if ($product['stock'] < $qty) throw new Exception("Not enough stock available.");

    $total_price = $product['price'] * $qty;

    // 2. VERIFICAR SALDO EN EL LEDGER (Créditos - Débitos)
    $stmt_b = $pdo->prepare("SELECT SUM(CASE WHEN entry_type = 'credit' THEN amount ELSE -amount END) FROM ledger WHERE user_id = ?");
    $stmt_b->execute([$buyer_id]);
    $balance = $stmt_b->fetchColumn() ?: 0.00;

    if ($balance < $total_price) {
        throw new Exception("Insufficient balance. Current: $" . number_format($balance, 2));
    }

    // 3. INSERTAR EN TABLA ORDERS (Estado inicial: pending)
    $stmt_o = $pdo->prepare("
        INSERT INTO orders (product_id, buyer_id, seller_id, quantity, total_price, status, created_at) 
        VALUES (?, ?, ?, ?, ?, 'pending', NOW())
    ");
    $stmt_o->execute([
        $product_id, 
        $buyer_id, 
        $product['seller_id'], 
        $qty, 
        $total_price
    ]);
    $order_id = $pdo->lastInsertId();

    // 4. REGISTRAR EN LEDGER (Débito de Escrow)
    $stmt_l = $pdo->prepare("
        INSERT INTO ledger (user_id, amount, entry_type, category, description) 
        VALUES (?, ?, 'debit', 'purchase_escrow', ?)
    ");
    $desc_ledger = "Escrow Lock for Order #" . $order_id;
    $stmt_l->execute([$buyer_id, $total_price, $desc_ledger]);

    // 5. LÓGICA DE AUTO-ENTREGA: EXTRAER LÍNEAS ÚNICAS
    $delivery_content = "";
    $updated_stock_text = $product['auto_delivery_content'];

    if (!empty($product['auto_delivery_content'])) {
        // Convertimos el bloque de texto en array, limpiando espacios y saltos de línea
        $all_items = explode("\n", str_replace("\r", "", $product['auto_delivery_content']));
        $all_items = array_values(array_filter($all_items, 'trim')); // Quitamos líneas vacías

        // Tomamos solo la cantidad comprada (1 línea = 1 unidad)
        $items_for_buyer = array_slice($all_items, 0, $qty);
        $delivery_content = implode("\n", $items_for_buyer);

        // Guardamos lo que sobra para el próximo comprador
        $remaining_items = array_slice($all_items, $qty);
        $updated_stock_text = implode("\n", $remaining_items);
    }

    // 6. ACTUALIZAR PRODUCTO (Bajar stock y remover líneas entregadas)
    $stmt_s = $pdo->prepare("UPDATE products SET stock = stock - ?, auto_delivery_content = ? WHERE id = ?");
    $stmt_s->execute([$qty, $updated_stock_text, $product_id]);

    // 7. GENERAR RECIBO PROFESIONAL PARA EL CHAT
    $receipt = "🚀 **VVAULT SECURE PAYMENT**\n";
    $receipt .= "━━━━━━━━━━━━━━━━━━━━━━━━\n";
    $receipt .= "🆔 **Order:** #{$order_id}\n";
    $receipt .= "📦 **Item:** {$product['title']}\n";
    $receipt .= "🔢 **Qty:** {$qty}\n";
    $receipt .= "💰 **Total:** $" . number_format($total_price, 2) . " USD\n";

    if (!empty($delivery_content)) {
        $receipt .= "\n🔑 **YOUR UNIQUE DELIVERED ITEMS:**\n";
        $receipt .= "```\n" . $delivery_content . "\n```\n";
        $receipt .= "⚠️ *These items are unique to you. Do not share them.*\n";
    }

    $receipt .= "━━━━━━━━━━━━━━━━━━━━━━━━\n";
    $receipt .= "🛡️ **ESCROW PROTECTION ACTIVE**\n";
    $receipt .= "Funds are secured by VVault. Please confirm delivery in 'My Orders' to release payment to the seller.";

    // 8. INSERTAR MENSAJE EN EL CHAT (El sistema notifica automáticamente)
    $stmt_msg = $pdo->prepare("
        INSERT INTO messages (sender_id, receiver_id, product_id, order_id, message, created_at) 
        VALUES (?, ?, ?, ?, ?, NOW())
    ");
    // El remitente es el buyer_id para que el vendedor vea la notificación en su chat
    $stmt_msg->execute([$buyer_id, $product['seller_id'], $product_id, $order_id, $receipt]);

    // 9. FINALIZAR TRANSACCIÓN
    $pdo->commit();
    header("Location: my_orders.php?success=purchased&id=" . $order_id);
    exit;

} catch (Exception $e) {
    // Si algo falla, se revierte todo (dinero, stock e ítems de auto-entrega)
    if ($pdo->inTransaction()) $pdo->rollBack();
    header("Location: product.php?id=$product_id&error=" . urlencode($e->getMessage()));
    exit;
}