<?php
include 'db.php';
include 'auth.php';
require_right('Add Purchase');

$vendor_id     = $_POST['vendor_id'];
$purchase_date = $_POST['purchase_date'];
$reference     = $_POST['reference_no'];
$discount      = floatval($_POST['discount']);
$shipping      = floatval($_POST['shipping']);
$status        = $_POST['status'];
$notes         = $_POST['notes'];

$item_ids      = $_POST['item_id'];
$quantities    = $_POST['quantity'];
$cost_prices   = $_POST['price'];
$retail_prices = $_POST['retail_price'];

$total = 0;
$tax_total = 0;

foreach ($item_ids as $i => $item_id) {
    $qty = floatval($quantities[$i]);
    $cost_price = floatval($cost_prices[$i]);
    $retail_price = floatval($retail_prices[$i]);
    $subtotal = $qty * $cost_price;

   $res = $conn->query("SELECT i.name, i.cost_price, i.retail_price, tr.rate FROM items i LEFT JOIN tax_rates tr ON i.tax_rate_id = tr.id WHERE i.id = $item_id");

    $row = $res->fetch_assoc();
    $item_name = $row['name'];
    $old_cost_price = floatval($row['cost_price']);
    $old_retail_price = floatval($row['retail_price']);
    $taxRate = floatval($row['rate']);

    $taxAmount = ($taxRate / 100) * $subtotal;
    $total += $subtotal;
    $tax_total += $taxAmount;
    

    if ($old_cost_price != $cost_price || $old_retail_price != $retail_price) {
        $stmt_history = $conn->prepare("INSERT INTO price_history (item_id, item_name, vendor_id, old_cost_price, new_cost_price, old_retail_price, new_retail_price, changed_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $user = 'admin';
        $stmt_history->bind_param("isidddds", $item_id, $item_name, $vendor_id, $old_cost_price, $cost_price, $old_retail_price, $retail_price, $user);
        $stmt_history->execute();
    }

    $conn->query("UPDATE items SET cost_price = $cost_price, retail_price = $retail_price WHERE id = $item_id");
}

$net = $total + $tax_total + $shipping - $discount;

$stmt = $conn->prepare("INSERT INTO purchases (purchase_number, vendor_id, purchase_date, total_amount, tax_amount, discount_amount, net_amount, payment_method, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, 'cash', ?, NOW())");
$stmt->bind_param("sssdidds", $reference, $vendor_id, $purchase_date, $total, $tax_total, $discount, $net, $status);
$stmt->execute();
$purchase_id = $stmt->insert_id;

foreach ($item_ids as $i => $item_id) {
    $qty = floatval($quantities[$i]);
    $cost_price = floatval($cost_prices[$i]);
    $subtotal = $qty * $cost_price;

    $stmt2 = $conn->prepare("INSERT INTO purchase_items (purchase_id, item_id, item_name, quantity, unit_cost, total_cost, tax_rate) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt2->bind_param("iisdidd", $purchase_id, $item_id, $item_name, $qty, $cost_price, $subtotal, $taxRate);
    $stmt2->execute();
}

header("Location: purchase-list.php?success=1");
exit;

?>
