<?php
include '../db.php';

header('Content-Type: application/json');

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$modifier_id = isset($input['modifier_id']) ? intval($input['modifier_id']) : 0;

if ($modifier_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid modifier ID']);
    exit;
}

try {
    // Check if modifier is used in any sales
    $check_stmt = $conn->prepare("SELECT COUNT(*) as count FROM sale_item_modifiers WHERE modifier_id = ?");
    $check_stmt->bind_param("i", $modifier_id);
    $check_stmt->execute();
    $result = $check_stmt->get_result()->fetch_assoc();
    
    if ($result['count'] > 0) {
        echo json_encode(['success' => false, 'message' => 'Cannot delete modifier. It has been used in previous orders.']);
        exit;
    }
    
    // Delete the modifier
    $stmt = $conn->prepare("DELETE FROM item_modifiers WHERE id = ?");
    $stmt->bind_param("i", $modifier_id);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Modifier deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting modifier: ' . $stmt->error]);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
