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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $_SESSION['user_id'];
    $ingredient_id = $_POST['ingredient_id'];
    $qty = (float)$_POST['qty'];
    $reason = trim($_POST['reason']);

    if ($qty <= 0) {
        die("Jumlah rusak tidak valid!");
    }

    try {
        $pdo->beginTransaction();

        // 1. Ambil harga per unit bahan untuk hitung kerugian (cost)
        $ing_stmt = $pdo->prepare("SELECT price_per_unit, stock_qty FROM ingredients WHERE id = ?");
        $ing_stmt->execute([$ingredient_id]);
        $ingredient = $ing_stmt->fetch();

        if (!$ingredient) {
            throw new Exception("Bahan baku tidak ditemukan.");
        }

        // Cek apakah stok cukup untuk dipotong
        if ($ingredient['stock_qty'] < $qty) {
            throw new Exception("Jumlah rusak melebihi stok yang ada di sistem!");
        }

        // Hitung total kerugian uang
        $total_cost = $qty * $ingredient['price_per_unit'];

        // 2. Simpan ke tabel waste_logs
        $log_stmt = $pdo->prepare("INSERT INTO waste_logs (ingredient_id, qty, total_cost, reason, user_id, waste_date) VALUES (?, ?, ?, ?, ?, NOW())");
        $log_stmt->execute([$ingredient_id, $qty, $total_cost, $reason, $user_id]);

        // 3. Potong stok dari tabel ingredients
        $upd_stmt = $pdo->prepare("UPDATE ingredients SET stock_qty = stock_qty - ? WHERE id = ?");
        $upd_stmt->execute([$qty, $ingredient_id]);

        $pdo->commit();
        header("Location: ../modules/staff/waste_input.php?status=success");

    } catch (Exception $e) {
        $pdo->rollBack();
        die("Gagal memproses data: " . $e->getMessage());
    }
}