<?php

namespace App\Libs\Backoffice\Fields;

use App\Libs\Backoffice\Contracts\ListableField;
use App\Libs\Exception\InvalidConfigurationException;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class DatePickerField extends BaseField implements ListableField
{
    protected $allowedInputTypes = array("datetime", "date", "time");
    protected $inputType = "datetime";

    public function __construct($config)
    {

        parent::__construct($config);

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

    public function getInputType()
    {
        return $this->inputType;
    }

    public function setInputType($inputType = "datetime")
    {
        if (!in_array($inputType, $this->allowedInputTypes)) {
            throw new InvalidConfigurationException("The field {$this->getName()} has an invalid inputType. Allowed values are datetime, date or time");
        }

        $this->inputType = $inputType;
    }

    public function buildSelect(Builder $query)
    {
        if ($this->isMultiLanguage()) {
            $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["inputType"] = $this->inputType;
        return $array;
    }

    public function getData(Model $model, $enabled = true, $hidden = false){
        $fieldName = $this->getName();

        if($this->isMultiLanguage()) {
            $locales = LaravelLocalization::getSupportedLocales();

            foreach ($locales as $locale => $localeData) {
                if ($model->exists) {
                    $languageModel = $model->languages->findByLocale($locale);

                    if (!empty($languageModel)) {
                        $value[$locale] = $languageModel->$fieldName;
                        if ($value[$locale] && !is_string($value[$locale])) {
                            $value = $this->getInputType() == 'date' ? $value[$locale]->toDateString() : $value[$locale]->toDateTimeString();
                        }
                    } else {
                        $value[$locale] = '';
                    }
                } else {
                    $value[$locale] = '';
                }
            }

        } else {
            $value = $model->exists ? $model->$fieldName : null;
            if ($value && !is_string($value)) {
                $value = $this->getInputType() == 'date' ? $value->toDateString() : $value->toDateTimeString();
            }
        }

        $validation = $this->getValidation();

        return [
            'name' => $this->getName(),
            'type' => ucfirst($this->getType()),
            'inputType' => $this->getInputType(),
            'isMultilanguage' => $this->isMultiLanguage(),
            'label' => $this->getLabel(),
            'info' => $this->getInfo(),
            'value' => $value,
            'hide' => $hidden,
            'enabled' => $enabled,
            'conditions' => $this->conditions,
            'required' => $validation && str_contains($validation, 'required') ?: false,
        ];
    }

    public function getValidationDataValues($copyAllLang = false, $input = null)
    {
        $values = parent::getValidationDataValues($copyAllLang, $input);

        if (is_string($values) && empty($values)) {
            $values = null;
        } elseif (is_array($values)) {
            foreach ($values as &$value) {
                if (empty($value)) {
                    $value = null;
                }
            }
        }
        return $values;
    }

    public function getValidation()
    {
        $validation = parent::getValidation();

        switch ($this->getInputType()) {
            case "datetime":
                $rule = "date_format:Y-m-d H:i:s";
                break;
            case "date":
                $rule = "date_format:Y-m-d";
                break;
            case "time":
                $rule = "date_format:H:i:s";
                break;
        }

        if (empty($validation)) {
            return 'nullable|' . $rule;
        } else {
            return $validation . '|nullable|' . $rule;
        }
    }

    public function getListData()
    {
        return [
            'name' => $this->getName(),
            'type' => ucfirst($this->getType()),
            'label' => ucfirst($this->getLabel())
        ];
    }
}


