<?php

namespace twa\apilibs;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Throwable;

class apilib extends Controller
{
    public function __construct(){

    }

    public static function GetNofication($id){

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

        if(!$Notication){
            return response()->json([ "status" => "error", "message" => "the notification with id = ".$id." was not found in your database" ]);
        }
        $arr[0]=$Notication['type'];
        $arr[1]=$Notication['label'];
        $arr[2]=$Notication['text'];
        $arr[3]=$Notication['text'];

        return $arr;
    }




    public static function CheckRequiredVariables($arr){

        $err=0;
        $missingparams = [];
        foreach ($arr AS $var){
            if(request()->input($var)==NULL || request()->input($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 ProcessValues($values){
        return $values;
    }

    public static function ProcessRequired($values,$required_fields,$required_notifications = [ ]){
        $err=0;
        $missingparams = [];
        foreach ($arr AS $var){
            if(request()->input($var)==NULL || request()->input($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 APIDisplayResponse($nbr,$concat_nessage = "", $concat_debugger = "",$arr = false, $replace_dictionnary = false){
        $ObjectError = self::GetNofication($nbr);

        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 GetLang(){
        if (!request()->header('lang')) { $lang = "en"; }else{
            $lang = request()->header('lang');
        }

        return $lang;
    }



    public static function TWAPropertyExists($object , $property){
        if(!is_object($object)){
            return false;
        }else{
            try {
                return array_key_exists($property, $object->toArray());
            } catch (Throwable $e) {
                return false;
            }
        }
    }


    public static function checkIBAN($iban){
        $iban = strtolower(str_replace(' ','',$iban));
        $Countries = array('al'=>28,'ad'=>24,'at'=>20,'az'=>28,'bh'=>22,'be'=>16,'ba'=>20,'br'=>29,'bg'=>22,'cr'=>21,'hr'=>21,'cy'=>28,'cz'=>24,'dk'=>18,'do'=>28,'ee'=>20,'fo'=>18,'fi'=>18,'fr'=>27,'ge'=>22,'de'=>22,'gi'=>23,'gr'=>27,'gl'=>18,'gt'=>28,'hu'=>28,'is'=>26,'ie'=>22,'il'=>23,'it'=>27,'jo'=>30,'kz'=>20,'kw'=>30,'lv'=>21,'lb'=>28,'li'=>21,'lt'=>20,'lu'=>20,'mk'=>19,'mt'=>31,'mr'=>27,'mu'=>30,'mc'=>27,'md'=>24,'me'=>22,'nl'=>18,'no'=>15,'pk'=>24,'ps'=>29,'pl'=>28,'pt'=>25,'qa'=>29,'ro'=>24,'sm'=>27,'sa'=>24,'rs'=>22,'sk'=>24,'si'=>19,'es'=>24,'se'=>24,'ch'=>21,'tn'=>24,'tr'=>26,'ae'=>23,'gb'=>22,'vg'=>24);
        $Chars = array('a'=>10,'b'=>11,'c'=>12,'d'=>13,'e'=>14,'f'=>15,'g'=>16,'h'=>17,'i'=>18,'j'=>19,'k'=>20,'l'=>21,'m'=>22,'n'=>23,'o'=>24,'p'=>25,'q'=>26,'r'=>27,'s'=>28,'t'=>29,'u'=>30,'v'=>31,'w'=>32,'x'=>33,'y'=>34,'z'=>35);

        if(!isset($Countries[substr($iban,0,2)]) || !array_key_exists(substr($iban,0,2),$Countries)){
            return false;
        }

        if(strlen($iban) == $Countries[substr($iban,0,2)]){

            $MovedChar = substr($iban, 4).substr($iban,0,4);
            $MovedCharArray = str_split($MovedChar);
            $NewString = "";

            foreach($MovedCharArray AS $key => $value){
                if(!is_numeric($MovedCharArray[$key])){
                    $MovedCharArray[$key] = $Chars[$MovedCharArray[$key]];
                }
                $NewString .= $MovedCharArray[$key];
            }

            if(bcmod($NewString, '97') == 1)
            {
                return true;
            }
        }
        return false;
    }


    public static function ProcessAttributes($data){
        $return = [];

        foreach (request()->all() 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] != request()->input($parameter)) {
                                $remove = true;
                            }
                        } else {
                            if (!str_contains(json_encode($row->cms_attributes[$parameter]), '"'.request()->input($parameter).'"')) {
                                $remove = true;
                            }
                        }
                    }catch (Throwable $e){
                        $remove = true;
                    }
                }
            }else{
                $remove = false;
            }

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

        }
        return $return;
    }

}
