<?php
session_start();
header('Content-Type: application/json');
require_once 'shikanisha.kts.php';

// Check if the database connection is set
if (!$conn) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed.']);
    exit();
}

// Get data from POST request
$food_id = $_POST['food_id'];
$name = $_POST['name'];
$price = $_POST['price'];
$category = $_POST['category'];

// Initialize flags
$ingredientsUpdated = false;
$foodUpdated = false;

// Check if food items are set in session
if (!isset($_SESSION['food_items']) || !is_array($_SESSION['food_items'])) {
    echo json_encode(['status' => 'error', 'message' => 'No ingredients data found in session.']);
    exit();
}

// Start transaction
mysqli_begin_transaction($conn);

try {
    // Calculate total cost price from session data
    $totalCostPrice = 0;
    foreach ($_SESSION['food_items'] as $item) {
        $totalCostPrice += $item['cost_price'] * $item['quantity_required'];
    }

    // Delete existing ingredients for the food item
    $deleteSql = "DELETE FROM food_ingredients WHERE food_id = ?";
    $stmt = $conn->prepare($deleteSql);
    if ($stmt === false) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }
    $stmt->bind_param('i', $food_id);
    $stmt->execute();
    $stmt->close();
    
    // Set flag for ingredients update
    $ingredientsUpdated = true;

    // Insert updated ingredients from session
    $insertSql = "INSERT INTO food_ingredients (food_id, ingredient_id, quantity_required, cost_price) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($insertSql);
    if ($stmt === false) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }

    foreach ($_SESSION['food_items'] as $item) {
        $stmt->bind_param('iiid', $food_id, $item['ingredient_id'], $item['quantity_required'], $item['cost_price']);
        $stmt->execute();

        if ($stmt->affected_rows <= 0) {
            throw new Exception('Failed to insert new ingredients.');
        }
    }
    $stmt->close();

    // Update food details
    $updateSql = "UPDATE food SET name = ?, price = ?, cost_price = ?, category = ? WHERE food_id = ?";
    $stmt = $conn->prepare($updateSql);
    if ($stmt === false) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }
    $stmt->bind_param('sddsi', $name, $price, $totalCostPrice, $category, $food_id);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        // Set flag for food update
        $foodUpdated = true;
    }
    $stmt->close();

    // Commit transaction
    mysqli_commit($conn);

    // Clear session data
    unset($_SESSION['food_items']);

    if ($foodUpdated && $ingredientsUpdated) {
        echo json_encode(['status' => 'success', 'message' => 'Food and ingredients updated successfully.']);
    } elseif ($foodUpdated) {
        echo json_encode(['status' => 'success', 'message' => 'Food details updated successfully.']);
    } elseif ($ingredientsUpdated) {
        echo json_encode(['status' => 'success', 'message' => 'Ingredients updated successfully.']);
    } else {
        echo json_encode(['status' => 'success', 'message' => 'No changes detected.']);
    }
} catch (Exception $e) {
    // Rollback transaction
    mysqli_rollback($conn);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    error_log("SQL Error: " . $e->getMessage());
} finally {
    $conn->close();
}
?>
