<?php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/database.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'DELETE') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

if (!isset($_GET['meal_id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Meal ID is required']);
    exit;
}

$mealId = (int)$_GET['meal_id'];

try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    
    $pdo->beginTransaction();
    
    // Delete meal costings first
    $stmt = $pdo->prepare("DELETE FROM meal_costings WHERE meal_id = ?");
    $stmt->execute([$mealId]);
    
    // Delete the meal
    $stmt = $pdo->prepare("DELETE FROM meals WHERE id = ?");
    $stmt->execute([$mealId]);
    
    $pdo->commit();
    
    echo json_encode(['success' => true, 'message' => 'Meal deleted successfully']);
    
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    error_log("delete_meal.php error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Failed to delete meal: ' . $e->getMessage()]);
}
?>