<?php
include 'db.php';

$item_id = (int)$_POST['item_id'];
$components = $_POST['component_item_id'];
$quantities = $_POST['quantity'];

$conn->query("DELETE FROM bom_components WHERE bom_id IN (SELECT id FROM bom_master WHERE item_id = $item_id)");

$q = $conn->query("SELECT id FROM bom_master WHERE item_id = $item_id");
if ($q->num_rows > 0) {
    $bom_id = $q->fetch_assoc()['id'];
} else {
    $conn->query("INSERT INTO bom_master (item_id) VALUES ($item_id)");
    $bom_id = $conn->insert_id;
}

$stmt = $conn->prepare("INSERT INTO bom_components (bom_id, component_item_id, quantity) VALUES (?, ?, ?)");
foreach ($components as $i => $comp_id) {
    $qty = (float)$quantities[$i];
    $stmt->bind_param("iid", $bom_id, $comp_id, $qty);
    $stmt->execute();
}

// ✅ Calculate BOM cost
$total_bom_cost = 0;
foreach ($_POST['component_item_id'] as $i => $component_id) {
    $qty = floatval($_POST['quantity'][$i]);

    $res = $conn->query("SELECT cost_price FROM items WHERE id = $component_id");
    if ($row = $res->fetch_assoc()) {
        $component_cost = floatval($row['cost_price']);
        $total_bom_cost += $qty * $component_cost;
    }
}

// ✅ Update parent item cost_price
$item_id = intval($_POST['item_id']);
$update = $conn->prepare("UPDATE items SET cost_price = ? WHERE id = ?");
$update->bind_param("di", $total_bom_cost, $item_id);
$update->execute();


echo json_encode(['status' => 'ok']);
