<?php
/**
 * Delete Recipe API
 */
require_once '../guard.php';
require_once __DIR__ . '/../../includes/database.php';

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

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

$input = json_decode(file_get_contents('php://input'), true);

if (empty($input['id'])) {
    echo json_encode(['success' => false, 'message' => 'Recipe ID is required']);
    exit();
}

try {
    $db = Database::getInstance();
    $conn = $db->getConnection();
    
    // Check ownership (unless superuser)
    if ($_SESSION['user_role'] !== 'superuser') {
        $checkStmt = $conn->prepare("SELECT created_by, name FROM recipes WHERE id = ?");
        $checkStmt->execute([$input['id']]);
        $recipe = $checkStmt->fetch();
        
        if (!$recipe || $recipe['created_by'] != $_SESSION['user_id']) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Access denied']);
            exit();
        }
    } else {
        $checkStmt = $conn->prepare("SELECT name FROM recipes WHERE id = ?");
        $checkStmt->execute([$input['id']]);
        $recipe = $checkStmt->fetch();
    }
    
    if (!$recipe) {
        echo json_encode(['success' => false, 'message' => 'Recipe not found']);
        exit();
    }
    
    // Delete recipe (cascades to related tables via foreign keys)
    $deleteStmt = $conn->prepare("DELETE FROM recipes WHERE id = ?");
    $deleteStmt->execute([$input['id']]);
    
    // Log activity
    $logStmt = $conn->prepare("INSERT INTO activity_log (unit_id, created_by, type, label) VALUES (?, ?, 'recipe', ?)");
    $logStmt->execute([$_SESSION['unit_id'], $_SESSION['user_id'], "Deleted recipe: " . $recipe['name']]);
    
    echo json_encode(['success' => true, 'message' => 'Recipe deleted successfully']);
    
} catch (Exception $e) {
    error_log("Recipe delete error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?>