<?php

namespace App\Libs\Backoffice\Fields;

use Illuminate\Database\Eloquent\Model;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ColorPickerField extends BaseField
{

    public function __construct($config)
    {
        parent::__construct($config);
    }

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

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

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

                    if (!empty($languageModel)) {
                        $value[$locale] = $languageModel->$fieldName;
                    } else {
                        $value[$locale] = null;
                    }
                } else {
                    $value[$locale] = null;
                }
            }

        } else {
            if ($model->exists) {
                $value = $model->$fieldName;
            }
        }

        $validation = $this->getValidation();

        return [
            "name" => $this->getName(),
            'type' => ucfirst($this->getType()),
            "label" => $this->getLabel(),
            "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 getValidation()
    {
        $validation = parent::getValidation();
        $rule = 'regex:/^#?[a-fA-F0-9]{3,8}$/|nullable';

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


