<?php
namespace FiloBlu\Flow\Model\Filters;

/**
 * Class ConcatCategories
 * @package FiloBlu\Flow\Model\Filters
 */
class ConcatCategories extends AbstractFilter {

    /**
     * @param $value
     * @param $args
     * @return string
     */
    public function filter($value,$args){

        $rowToConcat = $args['rows'];
        $separator = $args['separator'];
        $row_mapped = [];

        if (!is_array($rowToConcat) || empty($rowToConcat)) {
            return $value;
        }

        $row = $this->getRow();
        $multipleCategories = [];

        foreach($rowToConcat as $currentRow) {

            if (isset($row[$currentRow]) && $row[$currentRow] !== '') {
                if (strpos($row[$currentRow], '|') === false) {
                    $row_mapped[] = $row[$currentRow];
                }else {
                    $multipleCategories = explode('|', $row[$currentRow]);
                }
            }

        }

        if(count($multipleCategories)) {
            // Le categorie multiple (es.: Sandals|Heels) devono trovarsi all'ultimo livello che viene importato
            $part_value = implode($separator, $row_mapped);
            $list_categories = [];

            foreach ($multipleCategories as $_cat) {
                $list_categories[] = $part_value . $separator . trim($_cat);
            }

            return implode('|', $list_categories);
        }

        if (!count($row_mapped)) {
            return $value;
        }

        return implode($separator,$row_mapped);
    }

}

