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

$response = ['success' => false, 'message' => '', 'deleted_count' => 0];

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['ids']) || !is_array($input['ids'])) {
        throw new Exception('Invalid input data');
    }
    
    // Get user ID from database 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;
        }
    }
    
    if (!$user_id) {
        throw new Exception('User not authenticated');
    }
    
    // Convert all IDs to integers and filter out invalid ones
    $ingredientIds = array_map('intval', $input['ids']);
    $ingredientIds = array_filter($ingredientIds, function($id) {
        return $id > 0;
    });
    
    if (empty($ingredientIds)) {
        throw new Exception('No valid ingredient IDs provided');
    }
    
    // Create placeholders for the IN clause
    $placeholders = str_repeat('?,', count($ingredientIds) - 1) . '?';
    
    // First, get the names of ingredients being deleted for the response message
    $stmt = $pdo->prepare("SELECT id, name FROM ingredients WHERE id IN ($placeholders) AND user_id = ?");
    $params = array_merge($ingredientIds, [$user_id]);
    $stmt->execute($params);
    $ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($ingredients)) {
        throw new Exception('No ingredients found for deletion');
    }
    
    // Delete the ingredients
    $stmt = $pdo->prepare("DELETE FROM ingredients WHERE id IN ($placeholders) AND user_id = ?");
    $success = $stmt->execute($params);
    
    if ($success) {
        $deletedCount = $stmt->rowCount();
        $response['success'] = true;
        $response['deleted_count'] = $deletedCount;
        $response['message'] = "Successfully deleted $deletedCount ingredient(s)";
    } else {
        throw new Exception('Failed to delete ingredients');
    }
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
exit;
?>