<?php
require_once '../config/database.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = $_POST['product_id'];
    $ingredient_id = $_POST['ingredient_id'];
    $usage_qty = $_POST['usage_qty'];

    try {
        // Cek apakah bahan sudah ada di resep produk ini
        $check = $pdo->prepare("SELECT id FROM recipes WHERE product_id = ? AND ingredient_id = ?");
        $check->execute([$product_id, $ingredient_id]);
        
        if ($check->fetch()) {
            // Update jika sudah ada
            $stmt = $pdo->prepare("UPDATE recipes SET usage_qty = ? WHERE product_id = ? AND ingredient_id = ?");
            $stmt->execute([$usage_qty, $product_id, $ingredient_id]);
        } else {
            // Insert jika baru
            $stmt = $pdo->prepare("INSERT INTO recipes (product_id, ingredient_id, usage_qty) VALUES (?, ?, ?)");
            $stmt->execute([$product_id, $ingredient_id, $usage_qty]);
        }
        
        header("Location: ../modules/admin/recipes.php?status=success");
    } catch (PDOException $e) {
        die("Gagal simpan resep: " . $e->getMessage());
    }
}