<?php

namespace App\Libs\Backoffice\Generic;

use App\Libs\Facades\Localization;

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

    public function input(
        $type,
        $field,
        $label,
        $allLangs = true,
        $data = null,
        $errors = null,
        $fieldIndex = null,
        $other = null
    ) {
        if ($allLangs) {
            $availLangs = Localization::getSupportedLanguages();
            $defaultLang = Localization::getDefaultLocale();
        } else {
            $website = Localization::getWebsite();
            $availLangs = $website->languages;
            $defaultLang = $website->getDefaultLanguage()->id;
        }

        // Checks for validation errors
        $hasError = false;

        if (!empty($errors)) {
            $messages = $errors->getMessages();
            foreach ($availLangs as $lang) {
                if (isset($messages[($field.'.'.$lang->id)])) {
                    $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
        ));
    }
}
