<?php


namespace App\Models\LocalizationManagement\Bootables;


use App\Models\LocalizationManagement\Address;
use App\Models\LocalizationManagement\City;
use App\Models\LocalizationManagement\Country;
use App\Models\LocalizationManagement\Quarter;
use App\Models\LocalizationManagement\State;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

trait Addressable {

    public static function bootAddressable(){

        static::deleted(function (self $model) {
            $model->addresses()->delete();
        });

    }

    public function addresses(){
        return $this->morphMany(
            Address::class,
            Address::MORPH_FUNCTION_NAME,
            Address::MORPH_TYPE_COLUMN,
            Address::MORPH_ID_COLUMN
        );
    }

    public function city(){
        return $this->belongsTo(
            City::class,
            'city_id'
        );
    }


    public function addAddress($data){
        $country_table = (new Country)->getTable();
        $city_table = (new City)->getTable();
        $state_table = (new State)->getTable();
        $quarter_table = (new Quarter)->getTable();

        $rules = [
            'title' => ['required',"min:4"],
            // 'provider_reference' =>  ['required','min:2',"unique:$payment_table,provider_reference"],
        ];

        if (isset($datas['country_id'])){
            $rules['country_id'] = [Rule::exists($country_table,"id")->withoutTrashed()];
        }
        if (isset($datas['state_id'])){
            $rules['state_id'] = [Rule::exists($state_table,"id")->withoutTrashed()];
        }
        if (isset($datas['city_id'])){
            $rules['city_id'] = [Rule::exists($city_table,"id")->withoutTrashed()];
        }
        if (isset($datas['quarter_id'])){
            $rules['quarter_id'] = [Rule::exists($quarter_table,"id")->withoutTrashed()];
        }

        $validation = Validator::make(
                            $data,
                            $rules,
                            Address::validations_messages(),
                            Address::validations_attributes()
                        ); // (boolean)

        if ($validation->passes()){

            if (!isset($datas['paid_at'])){
                $datas['paid_at'] = now();
            }
            $payment =  $this->payments()->create($datas);

            if (isset($datas['image'])){
                $payment->uploadFiles([$datas['image']]);
            }
            return $payment;

        }else{
            return $validation->errors()->all();
        }
    }

}
