<?php
// includes/functions.php

// Hitung HPP per Produk berdasarkan resep
function calculateProductHPP($pdo, $product_id) {
    $total_hpp = 0;
    $query = "SELECT r.usage_qty, i.price_per_unit 
              FROM recipes r 
              JOIN ingredients i ON r.ingredient_id = i.id 
              WHERE r.product_id = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$product_id]);
    
    foreach ($stmt->fetchAll() as $item) {
        $total_hpp += ($item['usage_qty'] * $item['price_per_unit']);
    }
    return $total_hpp;
}

// Update stok bahan baku
function updateStock($pdo, $product_id, $qty_produced) {
    $query = "SELECT ingredient_id, usage_qty FROM recipes WHERE product_id = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$product_id]);
    
    foreach ($stmt->fetchAll() as $r) {
        $reduction = $r['usage_qty'] * $qty_produced;
        $sql = "UPDATE ingredients SET stock_qty = stock_qty - ? WHERE id = ?";
        $pdo->prepare($sql)->execute([$reduction, $r['ingredient_id']]);
    }
}
?>