<?php

namespace App\Services;

use Carbon\Carbon;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

class ManageLogging {

    public static function safe_json_encode($value, $options = 0, $depth = 512, $utfErrorFlag = false) {
        $encoded = json_encode($value, $options, $depth);
        switch (json_last_error()) {
            case JSON_ERROR_NONE:
                return $encoded;
            case JSON_ERROR_DEPTH:
                return 'Maximum stack depth exceeded'; // or trigger_error() or throw new Exception()
            case JSON_ERROR_STATE_MISMATCH:
                return 'Underflow or the modes mismatch'; // or trigger_error() or throw new Exception()
            case JSON_ERROR_CTRL_CHAR:
                return 'Unexpected control character found';
            case JSON_ERROR_SYNTAX:
                return 'Syntax error, malformed JSON'; // or trigger_error() or throw new Exception()
            case JSON_ERROR_UTF8:
                $clean = self::utf8ize($value);
                if ($utfErrorFlag) {
                    return 'UTF8 encoding error'; // or trigger_error() or throw new Exception()
                }
                return self::safe_json_encode($clean, $options, $depth, true);
            default:
                return 'Unknown error'; // or trigger_error() or throw new Exception()

        }
    }


    public function createLog($data)
    {
        $status = true;

        if(isset($data['card_number'])){
            $data['card_number'] = "XXXXXXX";
        }
        if(isset($data['expiry'])) {
            $data['expiry'] = "XXXXXXX";
        }

        try {
            self::getCommonLogData($data);
            $json_data = self::safe_json_encode($data,JSON_UNESCAPED_UNICODE);
            Log::info($json_data);
        } catch (\Exception $e) {
            $status = false;
        }
        return $status;

    }

    public function getCommonLogData(&$logData)
    {
        $logData['date_time'] = getCurrentDateTime();
        $logData['auth_user_ip'] = self::getClientIpAddress();
        $logData['auth_user_agent'] = self::getUserAgentInfo();
        if (auth()->user()) {
            $logData['auth_email'] = auth()->user()->email;
            $logData['auth_id'] = auth()->user()->id;
        }
    }


    public static function getClientIpAddress(){
        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if (isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';

        if (strlen($ipaddress) > 45){
            $ipaddress = substr($ipaddress, 0,45);
        }
        return $ipaddress;
    }

    public static function getServerIpAddress()
    {
        $ip = '';

        if (isset($_SERVER['HTTP_REFERER'])) {
            $addr = $_SERVER['HTTP_REFERER'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])){
            $addr = $_SERVER['REMOTE_ADDR'];
        } else {
            $addr = url()->previous();

        }

        if (strlen($addr) > 2) {
            $subAddr = substr($addr, 0, 3);
            if ($subAddr == 'htt' || $subAddr == 'www') {
                $host = parse_url($addr, PHP_URL_HOST);
                $currentServerHost = parse_url(config('app.url'), PHP_URL_HOST);
                if ($host != $currentServerHost){
                    $ip = gethostbyname($host);
                }

            } else {
                $ip = $addr;
            }
        }
//        $this->fileWrite("otp.txt", $ip.$addr, config('app.IS_OTP_FILE_WRITE_ENABLE'));
        return $ip;
    }


    public static function getUserAgentInfo(){
        $maxlength = 80;
        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : '';
        if (strlen($userAgent) < 80) {
            $maxlength = strlen($userAgent);
        }

        return substr($userAgent, 0, $maxlength);
    }


    public function nullRemovalMethod ($maybe_array, $replace_from, $replace_to)
    {
        if (!empty($maybe_array)) {
            if (is_array($maybe_array)) {
                foreach ($maybe_array as $key => $value) {
                    $maybe_array[$key] = $this->nullRemovalMethod($value, $replace_from, $replace_to);
                }
            }
        }

        return is_null($maybe_array) ? '' : $maybe_array;
    }
}
