<?php

namespace Velis;

/**
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
class AllowedIdsFilter
{
    /**
     * This function ensures that a user can only modify items they have permissions for.
     * It will add new items specified by the user and remove those they have removed,
     * but ONLY within the limits of items the user IS ALLOWED to access.
     *
     * @param int|string[] $userAllowedIds
     * @param int|string[] $currentIds
     * @param int|string[] $inputIds
     * @return int[]
     */
    public function getUpdatedList(array $userAllowedIds, array $currentIds, array $inputIds): array
    {
        $userAllowedIds = array_map(intval(...), $userAllowedIds);
        $currentIds = array_map(intval(...), $currentIds);
        $inputIds = array_map(intval(...), $inputIds);

        // Create a result array with a current ids list
        $updatedIdsList = $currentIds;

        // Remove ids that are not in the new ids list
        $updatedIdsList = array_diff($updatedIdsList, array_diff($userAllowedIds, $inputIds));

        // Add new ids that are not yet in the assigned ids and are allowed for the user
        foreach ($inputIds as $category) {
            if (in_array($category, $userAllowedIds) && !in_array($category, $updatedIdsList)) {
                $updatedIdsList[] = $category;
            }
        }

        // Sort items for order
        sort($updatedIdsList);

        return $updatedIdsList;
    }
}
