<?php


namespace App\Utility;


use Cake\Datasource\ConnectionManager;
use Cake\Filesystem\File;
use Cake\Log\Log;
use phpDocumentor\Reflection\Types\This;

//use Illuminate\Support\Facades\DB;

class ManageLog
{

    public function userLog($data){
        $userType = $_SESSION['userType'];

        if ($userType == CRM_USER_INDICATOR) {
            $data['action_by_type'] = 'CRMUSER';
        } else if ($userType == CMS_USER_INDICATOR) {
            $data['action_by_type'] = 'MEMBER';
        } else if ($userType == CONTACT_USER_INDICATOR) {
            $data['action_by_type'] = 'CONTACT_USER';
        }

        $auth_user = $_SESSION['Auth']['User'];

        if(!empty($auth_user)){
            $data['auth_user_data'] = $auth_user;
            unset($data['auth_user_data']['password']);
            unset($data['auth_user_data']['reset_password_token']);
            unset($data['auth_user_data']['backup_old_password']);
        }
        $data['auth_user_ip'] = $this->get_client_ip();
        $data['auth_user_agent'] = $this->getUserAgent();
        if($data['request']['html_content']) {
            $data['request']['html_content'] = "HTML_CONTENT";
        }

        self::createLog($data);
    }
    public static function createLog($data){

        //use Cake\Log\Log;
        \Cake\Log\Log::write("info", json_encode($data));
    }

    public function getUserAgent() {
        $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 get_client_ip() {
        $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 queryLog($file = "query")
    {
        $connection = ConnectionManager::get('default');
        $filepath = LOGS.$file.'.log';
        gc_collect_cycles();
        if (file_exists($filepath))
            unlink($filepath);
        $query_count = 0;
        $connection->
        DB::listen(function ($query) use (&$query_count, $file) {
            $sql = self::formatQuery($query->bindings, $query->sql);
            File::append(
                storage_path("/logs/$file.log"),
                PHP_EOL . ++$query_count . '. ' . $sql . PHP_EOL . 'Execution Time = ' . $query->time . PHP_EOL
            );

            $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
            foreach ($backtrace as $trace) {
                if (array_key_exists('file', $trace) && array_key_exists('line', $trace)) {
                    if (strpos($trace['file'], 'vendor') == false
                        && strpos($trace['file'], 'Middleware') == false
                        && strpos($trace['file'], 'public') == false
                        && strpos($trace['file'], 'server') == false) {
                        File::append(
                            storage_path("/logs/$file.log"),
                            $trace['file'] . ' ' . $trace['line'] . PHP_EOL
                        );
                    }
                }
            }
        });
    }

    */

    public static function formatQuery($bindings, $naked_sql)
    {

        $parted = explode('?', $naked_sql);
        if (count($bindings) > 0) {
            $final = '';
            foreach ($parted as $key => $part) {

                if (next($parted)) {
                    $value = $bindings[$key];
                    if (is_string($value)) {
                        $final .= $part . "'" . $value . "'";
                    } elseif (is_object($value)) {
                        $final .= $part . current((array)$value);
                    } else {

                        $final .= $part . $value;
                    }
                } else {
                    if (isset($bindings[$key])) {
                        $value = $bindings[$key];
                        if (is_string($value)) {
                            $final .= $part . "'" . $value . "'";
                        } elseif (is_object($value)) {
                            $final .= $part . current((array)$value);
                        } else {

                            $final .= $part . $value;
                        }
                    } else {
                        $final .= $part;
                    }

                }

            }
            $sql = $final . ';';
        } else {
            $sql = $naked_sql;
        }
        return $sql;
    }

    public static function getQueryLog($file = "query")
    {

        $conn = ConnectionManager::get('default');

        $filepath = LOGS.$file.'.log';

        if (file_exists($filepath))
            unlink($filepath);

        Log::config('queries', [
            'className' => 'File',
            'path' => LOGS,
            'file' => $file.'.log',
            'scopes' => ['queriesLog']
        ]);

        $conn->logQueries(true);


    }

}