<?php

namespace App\Libs\Backoffice\Fields;

use App\Libs\Backoffice\Contracts\SavableField;
use MatanYadaev\EloquentSpatial\Objects\Point;
use Illuminate\Database\Eloquent\Model;

class LocationField extends BaseField implements SavableField
{

    protected $required = false;

    public function __construct($config)
    {
        unset($config["multiLanguage"]);
        unset($config["validation"]);
        unset($config["preValidation"]);
        unset($config["inList"]);
        unset($config["search"]);
        unset($config["sort"]);

        parent::__construct($config);

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

    public function isRequired()
    {
        return $this->required;
    }

    public function setRequired($required)
    {
        $this->required = $required;
    }

    public function getLatName()
    {
        return $this->getName()."_lat";
    }

    public function getLngName()
    {
        return $this->getName()."_lng";
    }

    public function getZoomName()
    {
        return $this->getName()."_zoom";
    }

    public function getCurrentValue(Model $model)
    {
        $value = array("lat" => null, "lng" => null, "zoom" => 1);

        $fieldName = $this->getName();
        $latName = $this->getLatName();
        $lngName = $this->getLngName();
        $zoomName = $this->getZoomName();

        if (request()->has($latName)) {
            $value["lat"] = request()->input($latName);
        } elseif ($model->exists && !is_null($model->$fieldName)) {
            $value["lat"] = $model->$fieldName->getLat();
        }

        if (request()->has($lngName)) {
            $value["lng"] = request()->input($lngName);
        } elseif ($model->exists && !is_null($model->$fieldName)) {
            $value["lng"] = $model->$fieldName->getLng();
        }

        if (request()->has($zoomName)) {
            $value["zoom"] = request()->input($zoomName);
        } elseif ($model->exists) {
            $value["zoom"] = $model->$zoomName;
        }

        return $value;
    }

    public function getData(Model $model, $enabled = true, $hidden = false) {

        $value = array("lat" => null, "lng" => null, "zoom" => 1);

        if ($model->exists) {
            $fieldName = $this->getName();
            $zoomName = $this->getZoomName();

            $value["lat"] = is_null($model->$fieldName) ? null : $model->$fieldName->latitude;
            $value["lng"] = is_null($model->$fieldName) ? null : $model->$fieldName->longitude;

            if (!is_null($model->$zoomName)) {
                $value["zoom"] = $model->$zoomName;
            }
        }

        $googleKey = config("services.google.apiKey");

        return [
            "name" => $this->getName(),
            "type" => ucfirst($this->getType()),
            "label" => $this->getLabel(),
            "info" => $this->getInfo(),
            "value" => $value,
            "hide" => $hidden,
            "enabled" => $enabled,
            "required" => $this->isRequired(),
            "conditions" => $this->conditions,
            "googleKey" => $googleKey
        ];
    }

    public function save(Model $model, $values)
    {
        $fieldName = $this->getName();
        $zoomName = $this->getZoomName();

        if (empty($values["lat"]) || empty($values["lng"])) {
            $model->$fieldName = null;
            $model->$zoomName = null;
        } else {
            $model->$fieldName = new Point($values["lat"], $values["lng"]);
            $model->$zoomName = $values["zoom"];
        }
    }

    public function getValidation($isZoom = false)
    {
        $rules = "";
        if ($this->isRequired()) {
            $rules = "required|";
        } else {
            $rules = "nullable|";
        }

        if ($isZoom) {
            $rules .= "integer|min:0";
        } else {
            $rules .= "numeric";
        }


        return $rules;
    }

    public function getValidationDataRules($model = null, $prefix = '')
    {
        $validation = array(
            "rules" => array(),
            "labels" => array()
        );

        $fieldName = $prefix . $this->getName();
        $validation["rules"][$fieldName.".lat"] = $this->getValidation();
        $validation["rules"][$fieldName.".lng"] = $this->getValidation();
        $validation["rules"][$fieldName.".zoom"] = $this->getValidation(true);
        $validation["labels"][$fieldName.".lat"] = strtolower(trans("backend.latitude"));
        $validation["labels"][$fieldName.".lng"] = strtolower(trans("backend.longitude"));
        $validation["labels"][$fieldName.".zoom"] = "zoom";

        return $validation;
    }

    public static function getScript()
    {
        $googleKey = config("services.google.apiKey");

        if (!empty($googleKey)) {
            $scripts['googleMap'] = 'https://maps.googleapis.com/maps/api/js?key='.$googleKey;
        }

        return $scripts;
    }

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


