<?php

namespace App\Core\Validator\PropertyWeb;

use App\Models\PropertyWeb;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Translation\Translator;
use Exception;
use App\Core\Validator\BaseValidator;

class PropertyWebCreateValidator extends BaseValidator
{

    public function __construct
    (
        Translator $translator,
        Container $container
    )
    {
        parent::__construct($translator, $container);
    }

    public function rules($params = null)
    {
        return
            [
                "property_id" => 'required|numeric',
                "domain" => 'required|min:5|max:50',
                "hasDomain" => "accepted",
                "checkDomain" => "accepted",
                "isValidDomain" => "accepted",
                "default_language" => 'required|min:2|max:10',
                "template_id" => 'required|numeric|min:1',
            ];
    }

    public function messages()
    {
        $thisMessages =
            [
                "checkDomain.accepted" => "This domain added before",
                "hasDomain.accepted" => "This property have added other domain before",
                "isValidDomain.accepted" => "Not validate domain name.",
            ];
        return array_merge(parent::messages() , $thisMessages);
    }

    public function checkDomain($params)
    {
        try {
            $domain = PropertyWeb::where('domain', $params['domain'])
                ->first();
            return $domain ? false : true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function hasDomain($params)
    {
        try {
            $domain = PropertyWeb::where('property_id', $params['property_id'])
                ->first();
            return $domain ? false : true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function validDomain($domainName)
    {
        try {
            return preg_match("/^(?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}$/", $domainName) ? true : false;
        } catch (Exception $e) {
            return false;
        }
    }


    public function validate(array $params, array $rules = [], array $messages = [], array $customAttributes = [])
    {
        $params["isValidDomain"] = $this->validDomain($params['domain']);
        $params["hasDomain"] = $this->hasDomain(['property_id' => $params["property_id"] ]);
        $params["checkDomain"] = $this->checkDomain(['domain' => $params["domain"] ]);
        return $this->make($params, $this->rules($params), $this->messages());
    }

}
