<?php
use Illuminate\Http\Response;

if (!function_exists('sendResponse')) {
    function sendResponse($result, $message, $code = 200)
    {
        $result = encryptable($result);
        $response = [
            'success' => true,
            'data' => $result,
            'message' => $message,
        ];

        return response()->json($response, $code)->withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ]);
    }
}

if (!function_exists('sendError')) {
    function sendError($error, $errorMessages = [], $code = 200)
    {
        if(!isJson($errorMessages)){
            $errorMessages = json_encode($errorMessages);
        }
        $response = [
            'success' => false,
            'data' => [],
            'message' => $error,
        ];

        if (!empty($errorMessages)) {
            $response['message'] .=  "\n Messages : \n";
            $response['message'] .=  $errorMessages;
        }

        return response()->json($response, $code)->withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ]);
    }
}


if (!function_exists('encryptable')) {
    function encryptable($json_array, $crypt = true,$data = array('id_', '_id')) {
        $json_array = json_decode(json_encode($json_array), true);
        array_walk_recursive($json_array, function (&$value, $key) use ($data, $crypt) {

            if (!is_array($value)) {
                $is_encryptable = false;
                if ($key === "id") {
                    $is_encryptable = true;
                } else {
                    foreach ($data as $word) {
                        if (strpos($key, $word) !== false) {
                            $is_encryptable = true;
                            break;
                        }
                    }
                }

                if ($is_encryptable) {
                    // now i can crypt it Or decrypt it deponding on the value of $crypt
                    if ($value !== null ) {
                        if ($key === "client_id") {
                            $value = client_secure_me($value, $crypt);
                        } else {
                            $value = secure_me($value, $crypt);
                        }

                    }
                }
            }
        });
        return $json_array;
    }
}



if (!function_exists('isJson')) {
    function isJson($string){
        return is_string($string) && is_array(json_decode($string, true)) ? true : false;
    }
}

if (!function_exists('encryptKeys')) {
    function encryptKeys($array){
        $encrypted = [];
        foreach($array as $key => $value){
            $encrypted[secure_me($key)] = $value;
        }

        return $encrypted;
    }
}
