<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/database.php';

// Initialize response
$response = ['success' => false, 'message' => ''];

try {
    // Log the request for debugging
    error_log("Delete ingredient request received: " . file_get_contents('php://input'));
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['id'])) {
        throw new Exception('Invalid ingredient ID received: ' . json_encode($input));
    }
    
    $ingredientId = intval($input['id']);
    
    // Get user ID from session
    $user_id = null;
    $auth_token = $_COOKIE['rcp_auth'] ?? null;
    
    if ($auth_token) {
        $pdo = Database::getInstance()->getConnection();
        
        $stmt = $pdo->prepare("SELECT session_data FROM user_sessions WHERE session_id = ? AND expires_at > NOW()");
        $stmt->execute([$auth_token]);
        $session_data = $stmt->fetchColumn();
        
        if ($session_data) {
            $user = json_decode($session_data, true);
            $user_id = $user['user_id'] ?? null;
            error_log("User ID from session: " . $user_id);
        }
    }
    
    if (!$user_id) {
        throw new Exception('User not authenticated. Auth token: ' . ($auth_token ? 'present' : 'missing'));
    }
    
    // Verify ingredient exists
    $stmt = $pdo->prepare("SELECT id, name FROM ingredients WHERE id = ? AND user_id = ?");
    $stmt->execute([$ingredientId, $user_id]);
    $ingredient = $stmt->fetch();
    
    if (!$ingredient) {
        throw new Exception("Ingredient ID $ingredientId not found for user $user_id");
    }
    
    error_log("Attempting to delete ingredient: " . $ingredient['name']);
    
    // Delete ingredient
    $stmt = $pdo->prepare("DELETE FROM ingredients WHERE id = ? AND user_id = ?");
    $success = $stmt->execute([$ingredientId, $user_id]);
    
    if ($success) {
        $response['success'] = true;
        $response['message'] = 'Ingredient "' . $ingredient['name'] . '" deleted successfully';
        error_log("Ingredient deleted successfully");
    } else {
        $errorInfo = $stmt->errorInfo();
        throw new Exception('Database error: ' . ($errorInfo[2] ?? 'Unknown error'));
    }
    
} catch (Exception $e) {
    error_log("Delete ingredient error: " . $e->getMessage());
    $response['message'] = $e->getMessage();
}

// Clear any output buffers
while (ob_get_level()) {
    ob_end_clean();
}

echo json_encode($response);
exit;
?>