<?php

namespace App\Libs\Backoffice\Generic;

use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class MenuFormBuilder
{
    public function text(
        $field,
        $label,
        $allLangs = true,
        $data = null,
        $errors = null,
        $fieldIndex = null,
        $other = null,
        $readOnly = null
    ) {
        return $this->input('text', $field, $label, $allLangs, $data, $errors, $fieldIndex, $other, $readOnly);
    }

    public function input(
        $type,
        $field,
        $label,
        $allLangs = true,
        $data = null,
        $errors = null,
        $fieldIndex = null,
        $other = null,
        $readOnly = null
    ) {
        $availLangs = LaravelLocalization::getSupportedLanguagesKeys();
        $defaultLang = config('app.locale');

        // Checks for validation errors
        $hasError = false;

        if (!empty($errors)) {
            $messages = $errors->getMessages();
            foreach ($availLangs as $lang) {
                if (isset($messages[($field.'.'.$lang)])) {
                    $hasError = true;
                    break;
                }
            }
        }

        $fieldId = $fieldIndex ? $field."[$fieldIndex]" : $field;

        return view('admin.generic.form_parts.input_'.$type, array(
            'field' => $field,
            'fieldId' => $fieldId,
            'label' => $label,
            'availLangs' => $availLangs,
            'defaultLang' => $defaultLang,
            'data' => $data,
            'error' => $hasError,
            'other' => $other,
            'readOnly' => $readOnly
        ));
    }
}
