<?php

namespace App\Libs\Backoffice\Generic\Fields;

use App\Facades\RequestContext;
use App\Libs\Contracts\Backoffice\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->latitude;
        }

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

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

        return $value;
    }

    public function toForm(Model $model, $enabled = true, $hidden = false)
    {
        $html = "";
        $value = array("lat" => null, "lng" => null, "zoom" => 1);

        if (!config("google.apiKey")) {
            return '<strong>ERROR: Please set the google API key first.</strong>';
        }

        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;
            }
        }

        $errors = RequestContext::get("errors");
        $hasErrors = false;
        if (!empty($errors) && !$errors->isEmpty()) {
            if ($errors->has("{$this->getName()}.lat") ||
                $errors->has("{$this->getName()}.lng") ||
                $errors->has("{$this->getName()}.zoom")) {
                $hasErrors = true;
            }
        }

        $html .= view(
            "admin.generic.components.forms.location",
            array(
                "id" => $this->getName(),
                "errorLatKey" => $this->getName().".lat",
                "errorLngKey" => $this->getName().".lng",
                "errorZoomKey" => $this->getName().".zoom",
                "hasErrors" => $hasErrors,
                "name" => $this->getName(),
                "label" => $this->getLabel(),
                "value" => $value,
                "hide" => $hidden,
                "enabled" => $enabled,
                "required" => $this->isRequired(),
                "parentHidden" => ($hidden && !empty($this->parent)),
                "parent" => $this->parent,
                "info" => $this->getInfo()
            ));


        return $html;
    }

    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|";
        }

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


        return $rules;
    }

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

        $rules = $this->getValidation();
        $fieldName = $this->getName();
        $validation["values"][$fieldName] = request()->input($fieldName);
        $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("google.apiKey");
        $scripts['locationPicker'] = path_asset('path.backoffice.js_path').'/view/generic/backend-location-picker.js';
        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;
    }
}
  

