<?php
namespace twa\apilibs\traits;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use twa\apilibs\controllers\ValuesProcessingController;

trait APITrait {

    public function ProcessValues($values,$debug = false){
        try { $values = collect($values->get()); }catch (\Throwable $e){ $values = collect($values); }
        $request = request()->all();
        foreach ($request AS $key => $value){
            if(!isset($values[$key])){ $values[$key] = $value; }
        }
        foreach (request()->header() AS $key => $value){
            if(!isset($values[$key]) && array_key_exists(0,$value)){ $values[$key] = $value[0]; }
        }

        return (new ValuesProcessingController($values));
    }

    public function ProcessRequired($values,$required_fields,$required_headers = [],$required_notifications = [ ]){
        $err=0;
        $missingparams = [];

        foreach ($required_headers AS $var){
            if(!$values->get($var) && !request()->header($var)){
                array_push($missingparams,$var);
                $err=1;
            }
        }
        if($err==1){
            return self::APIDisplayResponse(0,". Those values can be passed in the Headers. The fields that you have missed are: ".implode(',',$missingparams),"");
        }

        foreach ($required_fields AS $var){
            if(!$values->get($var)){
                array_push($missingparams,$var);
                $err=1;
            }
        }
        if($err==1){
            return self::APIDisplayResponse(0,". The fields that you have missed are: ".implode(',',$missingparams),"");
        }else{
            return true;
        }
    }


    public static function GetNofication($id){

        $Notication = DB::table(config('apilibs.tables.notifications','notifications'))->where('id','=',$id)->where('cancelled',0)->first();

        if(!$Notication){
            return response([ "status" => "error", "message" => "the notification with id = ".$id." was not found in your database" ],400);
        }

        $arr[0]=$Notication->type;
        if(isset($Notication->{'label_'.app()->getLocale()})){
            $arr[1]=$Notication->{'label_'.app()->getLocale()};
        }else{
            $arr[1]=$Notication->label;
        }

        if(isset($Notication->{'text_'.app()->getLocale()})){
            $arr[2]=$Notication->{'text_'.app()->getLocale()};
            $arr[3]=$Notication->{'text_'.app()->getLocale()};
        }else{
            $arr[2]=$Notication->text;
            $arr[3]=$Notication->text;
        }

        return response($arr,200);
    }


    public static function APIDisplayResponse($nbr,$concat_nessage = "", $concat_debugger = "",$arr = false, $replace_dictionnary = false){
        $ObjectError = self::GetNofication($nbr);
        if($ObjectError->getStatusCode() != 200){
            dd($ObjectError->getOriginalContent());
        }else{
            $ObjectError = $ObjectError->getOriginalContent();
        }

        if($replace_dictionnary && is_array($replace_dictionnary) && count($replace_dictionnary)){
            foreach ($replace_dictionnary AS $key => $item){
                $ObjectError[2] = str_replace('%'.$key.'%',$item,$ObjectError[2]);
            }
        }

        $returnarr[$ObjectError[0]]['code']=intval($nbr);
        $returnarr[$ObjectError[0]]['title']= $ObjectError[1];
        $returnarr[$ObjectError[0]]['message']= $ObjectError[2].$concat_nessage;
        $returnarr[$ObjectError[0]]['debugger']= $ObjectError[3].$concat_debugger;

        if(!isset($_REQUEST['No400']) && $ObjectError[0]=="error"){ $code = 400; }else{ $code = 200; }
        if(!$arr){
            return response()->json($returnarr, $code);
        }else{
            return $returnarr;
        }


    }

    public static function APIDisplayCustomResponse($number, $type = "error", $title = "", $message = "", $debugger = "", $arr = false){

        $returnarr[$type]['code']=$number;
        $returnarr[$type]['title']= $title;
        $returnarr[$type]['message']= $message;
        $returnarr[$type]['debugger']= $debugger;

        if($type == "error"){
            $code = 400;
        }else{
            $code = 200;
        }

        if(!$arr){
            return response()->json($returnarr, $code);
        }else{
            return $returnarr;
        }

    }



    public static function ProcessAttributes($data, $values = []){
        $return = [];
        foreach ($values->get() AS $key => $request){
            if(str_contains($key,'attributes_') === true){
                $JsonParameters[] = $key;
            }
        }

        foreach ($data as $row) {
            $remove = false;
            if(isset($JsonParameters) && count($JsonParameters)>0) {
                foreach ($JsonParameters as $parameter) {
                    try{
                        if (is_array($row->cms_attributes[$parameter]) === false) {
                            if ($row->cms_attributes[$parameter] != $values->get($parameter)) {
                                $remove = true;
                            }
                        } else {
                            if (!str_contains(json_encode($row->cms_attributes[$parameter]), '"'.$values->get($parameter).'"')) {
                                $remove = true;
                            }
                        }
                    }catch (\Throwable $e){
                        $remove = true;
                    }
                }
            }else{
                $remove = false;
            }

            if ($remove === false) {
                $return[] = $row;
            }

        }
        return $return;
    }
}
