<?php

namespace App\Libs\Backoffice\Generic\Fields;

use App\Libs\Contracts\Backoffice\ListableField;
use App\Libs\Contracts\Backoffice\SearchableField;
use App\Models\GenericBackoffice\WebsiteObject;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class TextBoxField extends BaseField implements ListableField, SearchableField
{
    private $maxLength = null;
    private $nullable = false;
    private $woMultilang = false;

    public function __construct($config)
    {

        parent::__construct($config);

        if (!empty($config["maxLength"])) {
            $this->maxLength = $config["maxLength"];
        }

        if (!empty($config["woMultilang"])) {
            $this->woMultilang = $config["woMultilang"];
        }

        if (!empty($config["nullable"])) {
            $this->nullable = $config["nullable"];
        }
    }

    public function getMaxLength()
    {
        return $this->maxLength;
    }

    public function setMaxLength($maxLength = null)
    {
        $this->maxLength = $maxLength;
    }

    public function getNullable()
    {
        return $this->nullable;
    }

    public function setNullable($nullable = false)
    {
        $this->nullable = $nullable;
    }

    public function buildSelect(Builder $query)
    {
        if ($this->isMultiLanguage()) {
            if ($this->woMultilang) {
                //Not very nice hardcode, but...
                $tablePrefix = 'website_objects_lang';
            } else {
                $tablePrefix = $query->getModel()->languages()->getRelated()->getTable();
            }
        } else {
            $tablePrefix = $query->getModel()->getTable();
        }

        $query->addSelect("{$tablePrefix}.{$this->name}");
        return $query;
    }

    public function buildWhere(Builder $query, $searchPhrase)
    {
        if (empty($searchPhrase) || !$this->isSearchable()) {
            return $query;
        }

        if ($this->isMultiLanguage()) {
            $tablePrefix = $query->getModel()->languages()->getRelated()->getTable();
        } else {
            $tablePrefix = $query->getModel()->getTable();
        }

        $query->orWhere("{$tablePrefix}.{$this->name}", 'like', "%{$searchPhrase}%");
        return $query;
    }

    public function buildOrder(Builder $query, $sortOrder = "asc")
    {
        if ($this->isMultiLanguage()) {
            $tablePrefix = $query->getModel()->languages()->getRelated()->getTable();
        } else {
            $tablePrefix = $query->getModel()->getTable();
        }

        $query->orderBy("{$tablePrefix}.{$this->getName()}", $sortOrder);
        return $query;
    }

    public function toArray()
    {
        $array = parent::toArray();
        $array["maxLength"] = $this->maxLength;
        return $array;
    }

    public function toGridHeader()
    {
        return '<th data-column-id="'.$this->getName().'">'.ucfirst($this->getLabel()).'</th>';
    }

    public function toForm(Model $model, $enabled = true, $hidden = false)
    {
        $html = "";
        if ($this->isMultiLanguage()) {
            $locales = LaravelLocalization::getSupportedLocales();
            $defaultLocale = LaravelLocalization::getDefaultLocale();

            foreach ($locales as $locale => $localeData) {
                $fieldName = $this->getName();
                $name = $fieldName."[{$locale}]";
                $id = $fieldName."_{$locale}";
                $errorKey = $fieldName.".".$locale;
                $value = null;

                if ($model->exists) {
                    if ($this->woMultilang) {
                        $wo = WebsiteObject::find($model->website_object_id);
                        $languageModel = $wo->languages->findByLocale($locale);
                    } else {
                        $languageModel = $model->languages->findByLocale($locale);
                    }
                    if (!empty($languageModel)) {
                        $value = $languageModel->$fieldName;
                    }
                }

                $html .= view(
                    "admin.generic.components.forms.textbox",
                    array(
                        "id" => $id,
                        "errorKey" => $errorKey,
                        "name" => $name,
                        "label" => $this->getLabel(),
                        "value" => $value,
                        "maxLength" => $this->getMaxLength(),
                        "language" => $locale,
                        "defaultLang" => $defaultLocale,
                        "hide" => ($hidden || $locale != $defaultLocale),
                        "enabled" => $enabled,
                        "parentHidden" => ($hidden && !empty($this->parent)),
                        "parent" => $this->parent,
                        "info" => $this->getInfo()
                    ));
            }
        } else {
            $fieldName = $this->getName();
            $value = null;

            if ($model->exists) {
                $value = $model->$fieldName;
            }
            $html .= view(
                "admin.generic.components.forms.textbox",
                array(
                    "id" => $this->getName(),
                    "errorKey" => $this->getName(),
                    "name" => $this->getName(),
                    "label" => $this->getLabel(),
                    "value" => $value,
                    "maxLength" => $this->getMaxLength(),
                    "hide" => $hidden,
                    "enabled" => $enabled,
                    "parentHidden" => ($hidden && !empty($this->parent)),
                    "parent" => $this->parent,
                    "info" => $this->getInfo()
                ));
        }

        return $html;
    }

    public function getSearchStructure(Model $model, $view = false)
    {
        $searchData = array();
        $fieldName = $this->getName();
        if ($this->isMultiLanguage()) {
            foreach ($model->languages as $languageModel) {
                if (!empty($languageModel->$fieldName)) {
                    $value = $languageModel->$fieldName;
                    $searchData[$languageModel->language_id] = $languageModel->$fieldName;
                }
            }
        } else {
            if (!empty($model->$fieldName)) {
                $languages = LaravelLocalization::getSupportedLocales();
                foreach ($languages as $locale => $localeData) {
                    $searchData[$locale] = $model->$fieldName;
                }
            }
        }
        return $searchData;
    }

    public function getValidationData($copyAllLang = false)
    {
        $validation = array(
            "rules" => array(),
            "values" => array(),
            "labels" => array()
        );

        $rules = $this->getValidation();
        $fieldName = $this->getName();
        request()->merge(array($fieldName => $this->_preValidation(request()->input($fieldName))));

        if ($this->nullable && request()->input($fieldName) === '') {
            $fieldValue = null;
        } else {
            $fieldValue = request()->input($fieldName);
        }

        if ($this->isMultiLanguage() && $copyAllLang) {

            $defaultLocale = LaravelLocalization::getDefaultLocale();
            $allLocales = LaravelLocalization::getSupportedLocales();

            foreach ($allLocales as $locale => $localeData) {
                if ($locale == $defaultLocale) {
                    continue;
                }

                if (empty($fieldValue[$locale])) {
                    $fieldValue[$locale] = $fieldValue[$defaultLocale];
                }
            }

        }

        $validation["values"][$fieldName] = $fieldValue;

        if (!empty($rules)) {
            if ($this->isMultiLanguage()) {
                $locales = LaravelLocalization::getSupportedLanguagesKeys();

                $validation["rules"] = generateLangRules(
                    array($fieldName => $rules),
                    $locales);

                $validation["labels"] = generateLangLabels(
                    $fieldName, $this->getLabel(), $locales);
            } else {
                $validation["labels"][$fieldName] = $this->getLabel();
                $validation["rules"][$fieldName] = $this->getValidation();
            }
        }

        return $validation;
    }
}
  

