<?php
// buy_process.php
require 'config/db.php';


if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }

$product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
$qty = isset($_POST['qty']) ? (int)$_POST['qty'] : 1;
if ($qty < 1) $qty = 1;

$buyer_id = $_SESSION['user_id'];

try {
    $pdo->beginTransaction();

    // 1. Bloquear y obtener producto
    $stmt_p = $pdo->prepare("SELECT * FROM products WHERE id = ? FOR UPDATE");
    $stmt_p->execute([$product_id]);
    $product = $stmt_p->fetch();

    if (!$product || $product['stock'] < $qty || $product['status'] !== 'available') {
        throw new Exception("Stock insufficient or item unavailable.");
    }

    // 2. Bloquear y obtener comprador
    $stmt_b = $pdo->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
    $stmt_b->execute([$buyer_id]);
    $buyer = $stmt_b->fetch();

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

    if ($buyer['balance'] < $total_cost) {
        throw new Exception("Insufficient balance for this quantity.");
    }

    // 3. MOVIMIENTOS FINANCIEROS
    $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?")->execute([$total_cost, $buyer_id]);
    $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$total_cost, $product['seller_id']]);

    // 4. ACTUALIZAR STOCK Y ESTADO
    $new_stock = $product['stock'] - $qty;
    $status = ($new_stock <= 0) ? 'sold' : 'available';
    $pdo->prepare("UPDATE products SET stock = ?, status = ? WHERE id = ?")->execute([$new_stock, $status, $product_id]);

    // 5. REGISTRAR VENTA (Con cantidad)
    $pdo->prepare("INSERT INTO sales (product_id, seller_id, buyer_id, quantity, amount, created_at) VALUES (?, ?, ?, ?, ?, NOW())")
        ->execute([$product_id, $product['seller_id'], $buyer_id, $qty, $total_cost]);

    $pdo->commit();
    header("Location: dashboard.php?success=bought");

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    header("Location: product_view.php?id=$product_id&error=" . urlencode($e->getMessage()));
}