<?php
include('../config/config.php'); // Ensure DB connection is established

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    $id = isset($_POST['id']) ? $_POST['id'] : '';

    switch ($action) {
        case 'add':
            if (!isset($_POST['recipe_name']) || !isset($_POST['recipe_details'])) {
                echo "Error: Required fields are missing.";
                exit();
            }

            $recipe_name = $_POST['recipe_name'];
            $recipe_details = $_POST['recipe_details'];

            $stmt = $conn->prepare("INSERT INTO recipes (recipe_name, recipe_details, status) VALUES (?, ?, 'active')");
            $stmt->bind_param("ss", $recipe_name, $recipe_details);

            echo $stmt->execute() ? "Recipe added successfully!" : "Error: " . $stmt->error;
            $stmt->close();
            break;

        case 'edit':
            if (!isset($_POST['id']) || !isset($_POST['recipe_name']) || !isset($_POST['recipe_details'])) {
                echo "Error: Required fields are missing.";
                exit();
            }

            $recipe_name = $_POST['recipe_name'];
            $recipe_details = $_POST['recipe_details'];

            $stmt = $conn->prepare("UPDATE recipes SET recipe_name=?, recipe_details=? WHERE id=?");
            $stmt->bind_param("ssi", $recipe_name, $recipe_details, $id);

            echo $stmt->execute() ? "Recipe updated successfully!" : "Error: " . $stmt->error;
            $stmt->close();
            break;

        case 'delete':
            if (!isset($_POST['id'])) {
                echo "Error: Missing Recipe ID.";
                exit();
            }

            $stmt = $conn->prepare("UPDATE recipes SET status='inactive' WHERE id=?");
            $stmt->bind_param("i", $id);

            echo $stmt->execute() ? "Recipe deleted successfully!" : "Error: " . $stmt->error;
            $stmt->close();
            break;
    }

    $conn->close();
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {
    $id = $_GET['id'];
    $stmt = $conn->prepare("SELECT recipe_name, recipe_details FROM recipes WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($recipe_name, $recipe_details);

    if ($stmt->fetch()) {
        echo json_encode(array(
            "recipe_name" => $recipe_name,
            "recipe_details" => $recipe_details
        ));
    } else {
        echo json_encode(array("error" => "No data found"));
    }

    $stmt->close();
    $conn->close();
}
?>
