<?php

namespace App\Core\Validator\PropertyPaymentMapping;

use App\Models\PaymentType;
use App\Models\Currency;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Translation\Translator;

use App\Core\Validator\BaseValidator;

use Exception;

class PropertyPaymentMappingCreateValidator extends BaseValidator
{


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

    }

    public function rules($params = null)
    {
        return
            [
                'property_id' => 'required|numeric',
                'payment_type_id' => 'required|numeric',
                'currency' => 'required',
                'is_default' => 'required|boolean',
                'fields' => 'required|array',
                'check_fields' => 'accepted',
                'check_currencies' => 'accepted',
            ];

    }


    public function messages()
    {
        $thisMessages = [];
        return array_merge(parent::messages() , $thisMessages);
    }

    public function checkFields($params)
    {
        try {
            $fields = PaymentType::where('status',  1)
                ->where('id', $params['payment_type_id'])
                ->first();
            if(!$fields){
                throw new Exception ('fields error');
            }
            $fields = json_decode($fields['params']);
            $apiKeys = $params['fields'];
            $requiredKeys = collect($fields)->keys()->all() ;
            foreach ($requiredKeys as $key) {
                if(!isset($apiKeys[$key])){
                    throw new Exception('field error') ;
                }
            }
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function checkCurrencies($params)
    {
        try {
            $currencies = Currency::get('code')->toArray() ;
            if(!$currencies){
                throw new Exception ('currency error');
            }

            $apiCurrency = $params['currency'];
            $requiredCurrencies = collect($currencies)->keyBy('code')->keys()->all() ;

            $arraySearch = in_array($apiCurrency, $requiredCurrencies) ;
            if(!$arraySearch){
                throw new Exception ('valid currency error');
            }
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function validate(array $params, array $rules = [], array $messages = [], array $customAttributes = [])
    {
        $params["check_fields"] = $this->checkFields($params);
        $params["check_currencies"] = $this->checkCurrencies($params);

        return $this->make($params, $this->rules($params), $this->messages());
    }

}
