<?php
namespace App\Fun;
use App\SessionModel;
use App\User;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use Auth;


class Fun{

    # If we work on localhost please set $configFolderStyle = "";
    # else if we start desploy on server please set $configFolerStyle = "public/"
//    private static $configFolerStyle = "";
    private static $configFolerStyle = "public/";

    private static $configBackFunction = "/";


    //    function create defualt images for user
    private  static $defualtImg = 'defualt.png';

    public static function url($url){
        return URL::asset(self::$configFolerStyle.$url);
    }


    public static function back($url){
        return URL::asset(self::$configBackFunction.$url);
    }

    /**
     *   convert 1 to skkskdfdfdfdfdfk
     **/
    public  static  function decrypt($string){
        return Crypt::decrypt($string);
    }

    /**
     * conver skkskdfdfdfdfdfk to 1
     *
     */
    public  static  function encrypt($string){
        return Crypt::encrypt($string);
    }

    /**
     * @Auth : phen
     * @return string
     *
     * ICon status Active
     */
    public static function iconActive(){
        $img = '<img src="'.self::url('images/icons/active.png').'" status="1" width="25px" height="25px" alt="status" ';
        return  $img;
    }


    /**
     * @Auth Phen
     * @return string
     *
     * ICon status Deactive
     */
    public static function iconDeActive(){
        $img = '<img src="'.self::url('images/icons/deactive.png').'" status="0" width="25px" height="25px" alt="status" ';
        return   $img;
    }


    public static function generateSlug($object=""){
        $Slug = str_replace(" ", "-", $object);
        $date=date("Y-m-d H:i:s");
        $search = array("-"," ",":");
        $newDate = str_replace($search,"",$date);
        //        $newSlug = $Slug.'-'.$newDate;
        $newSlug = $object.'ABCDF'.$newDate.'news.html';
        return $newSlug;
    }


    /**
     * @Auth Phen
     * @param $table
     * @param $field
     * @return int
     *
     * @function : Generate id of database to string when we want 0001 ..... 0010
     */
    public static function generateID($table, $field,$Digit=4){
        $max = DB::table($table)->max($field);
        $increas = $max+1;
        (string)$increas;
        while(strlen($increas) < $Digit){
            $increas = "0".$increas;
        }
        return ($increas);
    }


    public static function validateError($validate){
        return response()->json(['status' => 'error', 'errors' => $validate->errors()]);
    }

    public static function success(){
        return ['status'=>'success'];
    }

    public static function failed(){
        return ['status'=>'failed'];
    }

    public static function noPermission(){
        return response()->json(['status'=>'noPermission'],200);
    }

    /**
     *
     * @Auth Leng Phen
     *
     * Please make sure you will update field name is    => islocked
     *
     * $tableFieldId   is the feild id the we use to update by $tableFieldId
     *
     */
    public static function IUpdateStatus($requestObj, $tableName, $tableFieldId ) {
        $id = Fun::decrypt($requestObj->id);
        $select = DB::table($tableName)->where($tableFieldId,$id)->first();
        $newStatus = "";
        if($select->islocked == 0){
            $newStatus = 1;
        }else if($select->islocked == 1) {
            $newStatus = 0;
        }
        DB::table($tableName)->where($tableFieldId,$id)->update([
            'islocked' => $newStatus
        ]);
        return ['status'=>$newStatus];
    }



    public static function lang(){
        $userAgent      = request()->header('User-Agent');
        $ip_addr        =  request()->ip();
        $lang           = SessionModel::where('ip_address',$ip_addr)->where('user_agent',$userAgent)->first();
        $l = Auth::user();
        if($lang == null){
            $insert = DB::table('sessions')->insert(
                [
                    'ip_address'=> $ip_addr,
                    'lang' => 'en',
                    'user_agent' => $userAgent
                ]
            );
        }
        if($l){
            App::setLocale($l->lang);
        }else{
            App::setLocale('km');
        }

        return $l->lang??'km';
    }



    /*
     * function defualt user images
     */
    public static function defualtUserProfile (){
        return self::$defualtImg;
    }

    /**
     *
     * Upload Image
     *
     */
    public static function uploadImage($file,$config) {
        $opacity=90;
//        $file_name = $file->getClientOriginalName();
        $file_temp = $file->getPathName();
        $extention = $file->getClientOriginalExtension();

        $rename = new Fun();
        $file_name = $rename->renameFileImage($file);
        if ($extention == 'jpeg' || $extention == 'jpg' || $extention == 'JPG'){
            $image = imagecreatefromjpeg($file_temp);
        }
        if ($extention == 'png' || $extention == 'PNG'){
            $image = imagecreatefrompng($file_temp);
        }
        if ($extention == 'gif'){
            $image = imagecreatefromgif($file_temp);
        }
        list($original_width,$original_height)=getimagesize($file_temp);
        for ($i=0; $i < count($config) ; $i++) {
            $userSetWidth=$config[$i][0];//$original_width;
            $userSetHeight=$config[$i][1];//$original_height;
            // height is follow userSetWidth
            $resize_height=($config[$i][0]*$original_height/$original_width);
            // set new width and height
            $tmp_min=imagecreatetruecolor($userSetWidth, $resize_height);
            imagecopyresampled($tmp_min,$image,0,0,0,0,$userSetWidth,$resize_height,$original_width,$original_height);
            // start upload file into folder
            imagejpeg($tmp_min,$config[$i][2]."/".$file_name,$opacity);
        }
        return $file_name;
    }

    public static function convertToStringSingle($Array = array()) {
         $fileImage = "";

            if($Array != " "){
                $fileImage = $Array;
            }
            if($Array == " "){
            $fileImage = $Array;

        }
        return $fileImage;
    }
    // multiple images
    public static function convertToStringMultiple($Array = array()) {
        $fileImage = "";
        for($a = 0; $a < 8; $a++){
            if($Array[$a] != " "){
                $fileImage .= $Array[$a]."||";
            }
        }

        for($b = 0; $b < 8; $b++){
            if($Array[$b] == " "){
                $fileImage .= $Array[$b]."||";
            }
        }
        return $fileImage;
    }

    public static function deleteImageFromDirecory($imageName, $originalDirecory, $binDirectory) {
        $file = $originalDirecory.DIRECTORY_SEPARATOR.$imageName;
        if(file_exists($file)) {
            //remove image into folder delete
            rename($file, $binDirectory.DIRECTORY_SEPARATOR.pathinfo($file, PATHINFO_BASENAME));
        }
    }

    public static function  renameFileImage($file){
        $fileRandom = "";
        for($i=0; $i < 30 ; $i++ ){
            $fileRandom .= chr(rand(97,122));
        }
        $date=date("Y-m-d H:i:s");
        $search = array(" ",":");
        $newDate = str_replace($search,"-",$date);
        //$fileName = $file['name'];
        $fileName = $file->getClientOriginalName();
        //$fileExtention = pathinfo($fileName, PATHINFO_EXTENSION);
        $fileExtention = $file->getClientOriginalExtension();
        $fileExtention = strtolower($fileExtention);
        $newfilename = $newDate."-".$fileRandom.".".$fileExtention;
        return $newfilename;
    }



    public static function getOneImage($obj,$position=0) {
        $imageArray = explode('||',$obj);
        return $imageArray[$position];
    }

}

