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

$id   = $_POST['id'] ?? '';
$qty  = $_POST['qty'] ?? '';
$sell = $_POST['sell_price'] ?? '';
$pur  = $_POST['purchase_price'] ?? '';

if(!$id) exit('Invalid ID');

try {

    $stmt = $conn->prepare("SELECT product_id FROM purchase_lines WHERE id = :id");
    $stmt->bindValue(':id', $id);
    $stmt->execute();
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

    if(!$product) exit('Product not found');
    $product_id = $product['product_id'];

    $stmt = $conn->prepare("UPDATE purchase_lines 
                            SET quantity=:qty, sell_price=:sell, purchase_price=:pur 
                            WHERE id=:id");
    $stmt->bindValue(':qty', $qty);
    $stmt->bindValue(':sell', $sell);
    $stmt->bindValue(':pur', $pur);
    $stmt->bindValue(':id', $id);
    $stmt->execute();

    $stmt = $conn->prepare("UPDATE variations 
                            SET default_purchase_price = :pur, dpp_inc_tax = :pur_inc,
                                default_sell_price = :sell, sell_price_inc_tax = :sell_inc
                            WHERE product_id = :product_id");
    $stmt->bindValue(':pur', $pur);
    $stmt->bindValue(':pur_inc', $pur); 
    $stmt->bindValue(':sell', $sell);
    $stmt->bindValue(':sell_inc', $sell); 
    $stmt->bindValue(':product_id', $product_id);
    $stmt->execute();

    echo 'Item and Variation Updated';
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>
