<?php

namespace LaraBB\Application\Traits;

/**
 *
 */
trait Request
{
    /**
     * @param string $identifier
     * @param array $except
     * @return array
     */
    public function getRules(string $identifier, array $except = []): array
    {
        $rules = config('application.validation.rules.' . $identifier);
        $parts = explode('.', $identifier);
        $field = $parts[1] ?? null;

        // Mappe Einzelfeld-Regel so, als wären es mehrere Felder
        if(!is_null($field)) {
            $rules = [$field => $rules];
        }

        // Baue neues Regel-Array mit Regel-Bezeichner als Indizes auf
        $rulesWithNameIndices = [];
        foreach($rules as $field => $fieldRules) {
            foreach($fieldRules as $index => $rule) {
                $ruleWithParamters = explode(':', $rule);
                $ruleIndex         = count($ruleWithParamters) > 1 ? $ruleWithParamters[0] : $rule;

                $rulesWithNameIndices[$field][$ruleIndex] = $rule;
            }
        }

        return collect($rulesWithNameIndices)->except($except)->map(function($rules) {
            return implode('|', $rules);
        })->toArray();
    }

    /**
     * @param string $identifier
     * @param array $except
     * @return array
     */
    public function getMessages(string $identifier, array $except = []): array
    {
        $messages = config('application.validation.messages.' . $identifier);
        $parts    = explode('.', $identifier);
        $field    = $parts[1] ?? null;

        return collect($messages)->except($except)->mapWithKeys(function($message, $key) use($field) {
            // Messages für einzelnes Feld wurde angefordert ($mixedMessage = string)
            if(!is_null($field)) {
                return [$field . '.' . $key => $message];
            }

            $messageItems = [];
            foreach($message as $messageKey => $messageValue) {
                $messageItems[$key . '.' . $messageKey] = $messageValue;
            }

            return $messageItems;
        })->toArray();
    }
}
