<?php
include 'includes/config.php';

$id        = $_POST['id'];
$productId = $_POST['product_id'];
$qty       = $_POST['quantity'];
$price     = $_POST['sell_price'];
$purchasePrice = $_POST['purchase_price'] ?? 0;
$barcode   = $_POST['barcode'] ?? '';

try {
    $conn->beginTransaction();

    $stmt = $conn->prepare("
        UPDATE purchase_lines 
        SET product_id = ?, 
            quantity = ?, 
            sell_price = ?, 
            purchase_price = ?, 
            pp_without_discount = ? 
        WHERE id = ?
    ");
    $stmt->execute([$productId, $qty, $price, $purchasePrice, $purchasePrice, $id]);

    if (!empty($barcode)) {
        $stmt_barcode = $conn->prepare("UPDATE products SET barcode=? WHERE id=?");
        $stmt_barcode->execute([$barcode, $productId]);
    }

    $conn->commit();
    echo "Purchase line updated successfully!";
} catch (Exception $e) {
    $conn->rollBack();
    echo "Error: " . $e->getMessage();
}
?>
