<?php
namespace App\Http\Helpers;

use Illuminate\Support\Facades\Cache;

class General
{
    public function __construct()
    {

    }

    public static function storeCachePerviousQuery($query = '', $name = '')
    {   
        $query_string = urldecode(preg_replace('/(%5B)\d+(%5D=)/i', '$1$2', http_build_query($query)));
        Cache::put($name, $query_string, 1800);
    }

    public static function getCachePerviousQuery($name = '')
    {   
        return Cache::get($name);
    }

    public static function returnTokenData($object = [], $token = '')
    {
        $data = (object)[
            'status' => true,
            'access_token' => $token,
            'data' => $object
        ];

        return $data;
    }

    public static function returnNotFoundData()
    {
        $data = (object)[
            'status' => false,
            'errors' => [config('error_code.exist_error')]
        ];

        return $data;
    }

    public static function returnErrorData($error = [])
    {
        $data = (object)[
            'status' => false,
            'errors' => $error
        ];

        return $data;
    }

    public static function returnData($object = [], $query_string = '')
    {
        if ($query_string) {
            $data = (object)[
                'status' => true,
                'pervious_query' => $query_string,
                'data' => $object
            ];
        }
        else {
            $data = (object)[
                'status' => true,
                'data' => $object
            ];
        }

        return $data;
    }

    public static function paginationGenerator($data = [], $params = [], $extract = [])
    {   
        $pagination = [];

        $data->appends($params)->links();
        $pagination = [
            'status' => true,
            'total' => $data->total(),
            'has_more_page' => $data->hasMorePages(),
            'query_string' => urldecode(preg_replace('/(%5B)\d+(%5D=)/i', '$1$2', http_build_query($params))),
            'page' => [
                'next_page' =>  urldecode(preg_replace('/(%5B)\d+(%5D=)/i', '$1$2', $data->nextPageUrl())),
                'pervious_page' =>  urldecode(preg_replace('/(%5B)\d+(%5D=)/i', '$1$2', $data->previousPageUrl())),
            ],
            'data' => $extract
        ];

        return $pagination;
    }

    public static function returnMimeType($file = [])
    {
        $f = finfo_open();
        $mime_type = finfo_file($f, $file[0], FILEINFO_MIME_TYPE);
        return $mime_type;
    }

    public static function returnQueryString($params = [])
    {
        $query_string = urldecode(preg_replace('/(%5B)\d+(%5D=)/i', '$1$2', http_build_query($params)));
        return $query_string;
    }

    public static function seoURL($string)
    {
        //Lower case everything
        $string = strtolower($string);
        //Remove all url format string
        $string =preg_replace("/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i", "", $string);
       
        $string = preg_replace("~[^\p{L}\n\s_]+~u", "", $string);
        
        //Clean up multiple dashes or whitespaces
        $string = preg_replace("/[\s-]+/", " ", $string);
        //Trim first - avoid spaces on beginning or end of the text
        $string = trim($string);

        // Check whether is English
        $match = preg_match('/^[A-Za-z0-9 _]+$/', $string);

        $isEnglish = $match == 1;

        if ($isEnglish == 1) {
            $string = mb_substr($string, 0, 60);
            $strArray = explode(" ",$string);
            if (sizeof($strArray) != 1) {
                // unset($strArray[intval(sizeof($strArray))-1]);
            }
            $string = implode(' ',$strArray);

        }else{
            $string = mb_substr($string, 0, 20,'UTF8');
        }

        //Convert whitespaces and underscore to dash
        $string = preg_replace("/[\s_]/", "-", $string);

        //Check empty string
        if (empty($string)) {
            $string = 'untitled';
        }
        return $string;
    }
    
    public static function shortenNumber($number){
        if ($number < 1000) {
            $nformat = number_format($number);
        }else if ($number < 1000000) {
            // Anything less than a million
            $nformat = number_format($number/1000,1) . 'k';
        } else if ($number < 1000000000) {
            // Anything less than a billion
            $nformat = number_format($number / 1000000, 3) . 'm';
        } else {
            // At least a billion
            $nformat = number_format($number / 1000000000, 3) . 'b';
        }
        
        return $nformat;
    }

    public static function getExcerpt($str, $maxLength = 60, $startPos = 0) 
    {
        $str = strip_tags($str);
        $str = html_entity_decode($str, ENT_QUOTES);
        $excerpt = $str;
        if(strlen($str) > $maxLength) {
            $excerpt = '';

            $excerpt = mb_substr($str, $startPos, $maxLength-3, 'UTF-8');

            $excerpt .= '...';
        } 
        return $excerpt;
    }

    public static function convertDayTime($date_time)
    {
        $date_time =  date('Y-m-d H:i:s', strtotime($date_time));
        $dteStart = new \DateTime(date('Y-m-d H:i:s'));
        $dteEnd   = new \DateTime($date_time); 
        $dteDiff  = $dteStart->diff($dteEnd);

        if($dteEnd->format('Y') < $dteStart->format('Y')) {
            return 'Active ' . $dteEnd->format('d M Y');
        }
        elseif($dteDiff->days > 0) { //already posted one day
            return 'Active ' . $dteEnd->format('d M');
        }
        elseif($dteDiff->format('%H') > 0) { //already posted one hours
            $text = $dteDiff->format('%h') != 1 ? 'hrs ago' : 'hr ago';
            return 'Active ' . $dteDiff->format('%h') . $text;
        }
        elseif($dteDiff->format('%I') > 0) { //already posted one min
            return 'Active ' . $dteDiff->format('%i') . ' mins ago';
        }
        else{
            return 'Active ' . $dteDiff->format('%s') . ' sec ago'; //already posted one sec
        }
    }
}

