<?php

//---------------------------- generate random number string  ----------
function generateRandomOTP($length = 6)
{
    PHP_VERSION < '4.2.0' && mt_srand((float)microtime() * 1000000);
    $hash = '';
    $chars = '123456789';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

//echo $mobile_code = generateRandomOTP(4);


function generateRandomString($length = 10)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

//echo $mobile_code = generateRandomString(4);

//------------------------- check user activate or not ---------------------
// function checkAccountActivateDeactivate($user_id){
// 	include('config.php');
// 	$check_active_all=$mysqli->prepare("SELECT active_flag FROM user_master WHERE user_id=? AND delete_flag ='no'");
// 	$check_active_all->bind_param("i",$user_id);
// 	$check_active_all->execute();
// 	$check_active_all->store_result();
// 	$check_active=$check_active_all->num_rows;
// 	if($check_active>0){
// 		$check_active_all->bind_result($active_flag_get);
// 		$check_active_all->fetch();
// 		if($active_flag_get == 'deactivate'){
// 			$active_status='deactivate';
// 		}
// 	}

// 	if(empty($active_status)){
// 		$active_status='activate';
// 	}
// 	return $active_status;
// }

//------------------------- check user activate or not ---------------------
function checkAccountActivateDeactivate($user_id)
{
    include('config.php');
    $active_status ='';
    // echo "SELECT active_flag FROM user_master WHERE user_id=$user_id AND delete_flag = 0";die;
    $check_active_all = $mysqli->prepare("SELECT active_flag FROM user_master WHERE user_id=? AND delete_flag = 0");
    $check_active_all->bind_param("i", $user_id);
    $check_active_all->execute();
    $check_active_all->store_result();
    $check_active = $check_active_all->num_rows;
    if ($check_active > 0) {
        $check_active_all->bind_result($active_flag_get);
        $check_active_all->fetch();

        if ($active_flag_get == 1) {
            $active_status = '1';
        }
    }

    return $active_status;
}

// $user_id=1;
// echo $active_status = checkAccountActivateDeactivate($user_id);

//----------------------------------------- safe json functions -------------------------
function jsonSendEncode($record)
{
    $data = safe_json_encode($record);
    echo $data;
    exit;
}

function jsonSendEncodeAdmin($record)
{
    $data = safe_json_encode($record);
    //echo $data;
    return $data;
}

function safe_json_encode($value)
{

    if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
        $encoded = json_encode($value, JSON_PRETTY_PRINT);
    } else {
        $encoded = json_encode($value);
    }

    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 = utf8ize($value);
            return safe_json_encode($clean);
        default:
            return 'Unknown error'; // or trigger_error() or throw new Exception()
    }
}


function utf8ize($mixed)
{
    if (is_array($mixed)) {
        foreach ($mixed as $key => $value) {
            $mixed[$key] = utf8ize($value);
        }
    } else if (is_string($mixed)) {
        return utf8_encode($mixed);
    }
    return $mixed;
}
//----------------------------------------- safe json functions end -------------------------

//---------------------------  upload file function --------------------
function uploadFile($file, $folder_name, $file_type)
{

    include_once('image_resize.php');

    $file_extension = strtolower(pathinfo(basename($file["name"]), PATHINFO_EXTENSION));

    $str = generateRandomString(15);
    $str2 = rand();
    $image_name = $str . $str2 . '.' . $file_extension;
    $upload_target = '../../webservice/' . $folder_name . "/" . $image_name;

    if (move_uploaded_file($file['tmp_name'], $upload_target)) {

        if ($file_type == 'image') {

            //-------------- IMAGE CROP 200X200 -------------------------------
            $new_width = '200';
            $new_height = '200';
            $uploadDir = '../../webservice/' . $folder_name;
            $moveToDir  = '../../webservice/' . $folder_name . '/200X200';
            // $img_result=createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir);

            //-------------- IMAGE CROP 400X400 -------------------------------
            $new_width = '400';
            $new_height = '400';
            $uploadDir = '../../webservice/' . $folder_name;
            $moveToDir  = '../../webservice/' . $folder_name . '/200X200';;
            // $img_result= createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir);

            //-------------- IMAGE CROP 800X800 -------------------------------
            $new_width = '700';
            $new_height = '700';
            $uploadDir = '../../webservice/' . $folder_name;
            $moveToDir  = '../../webservice/' . $folder_name . '/700X700';
            // $img_result= createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir);
        }

        return $image_name;
    } else {
        return 'error';
    }
}



function uploadFileMultiple($file_arr, $folder_name, $file_type)
{
    require_once('image_resize.php');
    //echo count($file_arr);
    //print_r($file_arr);
    $image_name_arr = array();
    for ($i = 0; $i < count($file_arr["name"]); $i++) {
        //echo '$file_arr["name"][$i]='.$file_arr["name"][$i];
        if ($file_arr["name"][$i] != '') {
            $file_extension = strtolower(pathinfo(basename($file_arr["name"][$i]), PATHINFO_EXTENSION));
            $str = generateRandomString(15);
            $str2 = rand();
            $image_name = $str . $str2 . '.' . $file_extension;
            $upload_target = '../../webservice/' . $folder_name . "/" . $image_name;
            if (move_uploaded_file($file_arr['tmp_name'][$i], $upload_target)) {
                if ($file_type == 'image') {
                    //-------------- IMAGE CROP 200X200 -------------------------------
                    $new_width = '200';
                    $new_height = '200';
                    $uploadDir = '../../webservice/' . $folder_name;
                    $moveToDir  = '../../webservice/' . $folder_name . '/200X200';
                    $img_result = createThumbnail($image_name, $new_width, $new_height, $uploadDir, $moveToDir);
                    //-------------- IMAGE CROP 400X400 -------------------------------
                    $new_width = '400';
                    $new_height = '400';
                    $uploadDir = '../../webservice/' . $folder_name;
                    $moveToDir  = '../../webservice/' . $folder_name . '/400X400';
                    $img_result = createThumbnail($image_name, $new_width, $new_height, $uploadDir, $moveToDir);
                    //-------------- IMAGE CROP 700X700 -------------------------------
                    $new_width = '700';
                    $new_height = '700';
                    $uploadDir = '../../webservice/' . $folder_name;
                    $moveToDir  = '../../webservice/' . $folder_name . '/700X700';
                    $img_result = createThumbnail($image_name, $new_width, $new_height, $uploadDir, $moveToDir);
                }

                //echo '$image_name=='.$image_name;
                $image_name_arr[] = $image_name;
                //return $image_name;

            } else {

                //echo 'error upload';
                //return 'error';

                //$image_name_arr[]='error';

            }
        }
    }

    // for loop closed

    if (count($file_arr["name"]) == count($image_name_arr)) {

        return $image_name_arr;
    } else {

        return 'error';
    }
}


function uploadFileMultiple1($file_arr, $folder_name, $file_type)
{
   // require_once('image_resize.php');
    //echo count($file_arr);
    //print_r($file_arr);
    $image_name_arr = array();
    for ($i = 0; $i < count($file_arr["name"]); $i++) {
        //echo '$file_arr["name"][$i]='.$file_arr["name"][$i];
        if ($file_arr["name"][$i] != '') {
            // $file_extension = strtolower(pathinfo(basename($file_arr["name"][$i]), PATHINFO_EXTENSION));
            // $str = generateRandomString(15);
            // $str2 = rand();
            $image_name = $file_arr["name"][$i];
            $upload_target = '../../webservice/' . $folder_name . "/" .$image_name;
            if (move_uploaded_file($file_arr['tmp_name'][$i], $upload_target)) {
                if ($file_type == 'image') {
                    //-------------- IMAGE CROP 200X200 -------------------------------
                    $new_width = '200';
                    $new_height = '200';
                    $uploadDir = '../../webservice/' . $folder_name;
                    $moveToDir  = '../../webservice/' . $folder_name . '/200X200';
                    //$img_result = createThumbnail($image_name, $new_width, $new_height, $uploadDir, $moveToDir);
                    //-------------- IMAGE CROP 400X400 -------------------------------
                    $new_width = '400';
                    $new_height = '400';
                    $uploadDir = '../../webservice/' . $folder_name;
                    $moveToDir  = '../../webservice/' . $folder_name . '/400X400';
                    //$img_result = createThumbnail($image_name, $new_width, $new_height, $uploadDir, $moveToDir);
                    //-------------- IMAGE CROP 700X700 -------------------------------
                    $new_width = '700';
                    $new_height = '700';
                    $uploadDir = '../../webservice/' . $folder_name;
                    $moveToDir  = '../../webservice/' . $folder_name . '/700X700';
                    //$img_result = createThumbnail($image_name, $new_width, $new_height, $uploadDir, $moveToDir);
                }

                //echo '$image_name=='.$image_name;
                $image_name_arr[] = $image_name;
                //return $image_name;

            } else {

                //echo 'error upload';
                //return 'error';

                //$image_name_arr[]='error';

            }
        }
    }

    // for loop closed

    if (count($file_arr["name"]) == count($image_name_arr)) {

        return $image_name_arr;
    } else {

        return 'error';
    }
}


/*
$file=$_FILES['image'];
$folder_name='images';
$file_type='image';
$upload_status=uploadFile($file, $folder_name, $file_type);
*/

// FUNCTION TO DEELTE THE FILE
/* 1. Why File Upload before data insert 2. why not after data successfully inserted 3. rename file name 4. server side check for image size and extension 5. maintain proper directory structure 5. unlink the files conditions and scenarios ?????????*/
function removeFile($dir, $filename)
{
    if ($filename != '') {
        $delFile = $dir . DIRECTORY_SEPARATOR . $filename;
        if (file_exists($delFile)) {
            unlink($delFile);
        }
    }
}


//--------------------------- Encode or decode ---------------------------------
//$skey   = "5SuPerEncKey2012"; // you can change it

function safe_b64encode($string)
{

    $data = base64_encode($string);
    $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
    return $data;
}

function safe_b64decode($string)
{
    $data = str_replace(array('-', '_'), array('+', '/'), $string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

function encode($value)
{

    return base64_encode($value);

    // if(!$value){ return false; }
    // $text = $value;
    // $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    // $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    // $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $GLOBALS['skey'], $text, MCRYPT_MODE_ECB, $iv);
    // return trim(safe_b64encode($crypttext)); 
}

function decode($value)
{

    return base64_decode($value);
    // GLOBAL $skey;

    // if(!$value) {return false;}
    // $crypttext = safe_b64decode($value); 
    // $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    // $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    // $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $GLOBALS['skey'], $crypttext, MCRYPT_MODE_ECB, $iv);
    // return trim($decrypttext);
}

/*echo $raj = encode('asin'),'<br>';
echo decode($raj);*/

//--------------------------- Encode or decode end ---------------------------------
