<?php
include 'db.php';

$action = $_POST['action'] ?? '';

if($action=='list'){
    $res = $conn->query("
        SELECT p.id, p.perishable_id, per.name, per.unit, p.unit_cost, p.qty_per_person, p.composition
        FROM perishable_parameters p
        JOIN perishables per ON per.id = p.perishable_id
        ORDER BY per.name ASC
    ");
    $data = [];
    while($row = $res->fetch_assoc()){
        $data[] = $row;
    }
    echo json_encode($data);
    exit;
}

$id = intval($_POST['edit_id'] ?? 0);
$perishable_id = intval($_POST['perishable_id'] ?? 0);
$qty_per_person = floatval($_POST['qty_per_person'] ?? 0);
$composition = intval($_POST['composition'] ?? 1);
$unit_cost = floatval($_POST['unit_cost'] ?? 0);

if($action=='save'){
    if($id>0){
        $stmt = $conn->prepare("UPDATE perishable_parameters SET perishable_id=?, qty_per_person=?, composition=?, unit_cost=? WHERE id=?");
        $stmt->bind_param("idddi", $perishable_id, $qty_per_person, $composition, $unit_cost, $id);
        $stmt->execute();
        echo "Updated successfully!";
    } else {
        $stmt = $conn->prepare("INSERT INTO perishable_parameters (perishable_id, qty_per_person, composition, unit_cost) VALUES (?,?,?,?)");
        $stmt->bind_param("idid", $perishable_id, $qty_per_person, $composition, $unit_cost);
        $stmt->execute();
        echo "Saved successfully!";
    }
    exit;
}

if($action=='remove'){
    $remove_id = intval($_POST['id'] ?? 0);
    $conn->query("DELETE FROM perishable_parameters WHERE id=$remove_id");
    echo "Removed successfully!";
    exit;
}