<?php
// Include your database connection file
include('shikanisha.kts.php'); // Update with your actual database connection file

// Get the food ID from the POST request
$food_id = isset($_POST['food_id']) ? intval($_POST['food_id']) : 0;

if ($food_id > 0) {
    // Start a transaction
    $conn->begin_transaction();

    try {
        // Prepare the SQL query to delete from the food_ingredients table
        $query1 = "DELETE FROM food_ingredients WHERE food_id = ?";
        if ($stmt1 = $conn->prepare($query1)) {
            $stmt1->bind_param('i', $food_id);
            $stmt1->execute();
            $stmt1->close();
        } else {
            throw new Exception('Failed to prepare the SQL query for food_ingredients.');
        }

        // Prepare the SQL query to delete from the food table
        $query2 = "DELETE FROM food WHERE food_id = ?";
        if ($stmt2 = $conn->prepare($query2)) {
            $stmt2->bind_param('i', $food_id);
            $stmt2->execute();
            $stmt2->close();
        } else {
            throw new Exception('Failed to prepare the SQL query for food.');
        }

        // Commit the transaction
        $conn->commit();
        $response = [
            'status' => 'success',
            'message' => 'Food item and its ingredients deleted successfully.'
        ];
    } catch (Exception $e) {
        // Rollback the transaction
        $conn->rollback();
        $response = [
            'status' => 'error',
            'message' => $e->getMessage()
        ];
    }
} else {
    $response = [
        'status' => 'error',
        'message' => 'Invalid food ID.'
    ];
}

// Close the database connection
$conn->close();

// Output the response in JSON format
header('Content-Type: application/json');
echo json_encode($response);
?>
