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

$ref_no = $_POST['ref_no'] ?? '';
$product_id = $_POST['product_id'] ?? '';
$qty = $_POST['qty'] ?? '';
$sell = $_POST['sell_price'] ?? '';
$pur  = $_POST['purchase_price'] ?? '';
$supplier_id = $_POST['supplier_id'] ?? 0;

if(!$ref_no || !$product_id) exit('Invalid data');

try {
   
    $stmt = $conn->prepare("INSERT INTO purchase_lines 
        (ref_no, product_id, quantity, sell_price, purchase_price, purchase_date, supplier_id)
        VALUES (:ref_no, :product_id, :qty, :sell, :pur, NOW(), :supplier_id)");
    $stmt->bindValue(':ref_no', $ref_no);
    $stmt->bindValue(':product_id', $product_id);
    $stmt->bindValue(':qty', $qty);
    $stmt->bindValue(':sell', $sell);
    $stmt->bindValue(':pur', $pur);
    $stmt->bindValue(':supplier_id', $supplier_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 'New item added successfully';
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>
