<?php
if(!function_exists('convert_idr'))
{
    function convert_idr($angka){
        
        $hasil_rupiah = "IDR " . number_format($angka,0,',','.');
        return $hasil_rupiah;
     
    }
}
if(!function_exists('gojekStatus'))
{
    function gojekStatus($param){
        $result = "";
        
        if($param == "Finding Driver"){
            $result = "<span class='label label-info'>Finding Driver</span>";
        } else if($param == "Driver Allocated") {
            $result = "<span class='label label-info'>Driver Allocated</span>";
        } else if($param == "Enroute Pickup") {
            $result = "<span class='label label-info'>Enroute Pickup</span>";
        } else if($param == "Item Picked") {
            $result = "<span class='label label-warning'>Item Picked</span>";
        } else if($param == "Enroute Drop") {
            $result = "<span class='label label-warning'>Enroute Drop</span>";
        } else if($param == "On Hold") {
            $result = "<span class='label label-danger'>On Hold</span>";
        } else if($param == "Rejected") {
            $result = "<span class='label label-danger'>Rejected</span>";
        } else if($param == "Driver not found") {
            $result = "<span class='label label-danger'>Driver not found</span>";
        } else if($param == "Cancelled") {
            $result = "<span class='label label-danger'>Cancelled</span>";
        } else if($param == "Completed") {
            $result = "<span class='label label-success'>Completed</span>";
        }

        return $result;
    }
}
if(!function_exists('check_access'))
{
    function check_access($param,$slug){
        $result = "false";
        $slug_array = explode(',',$slug);
        if (in_array($param, $slug_array)) {
            $result = "true";
        }
        return $result;
    }
}
if(!function_exists('checkOrderType'))
{
    function checkOrderType($param){
        $result = "";
        
        if($param == "website"){
            $result = "Website";
        } else if($param == "marketplace") {
            $result = "Marketplace";
        } else if($param == "wholesale") {
            $result = "Wholesale";
        } else if($param == "store") {
            $result = "Store";
        } else if($param == "deptstore") {
            $result = "Deptstore";
        } else if($param == "consignment") {
            $result = "Consignment";
        } else if($param == "sample") {
            $result = "Sample";
        } else if($param == "employee") {
            $result = "Employee Purchase";
        } else if($param == "retur") {
            $result = "Retur";
        } else if($param == "reject") {
            $result = "Reject";
        } else if($param == "endorsement") {
            $result = "Endorsement";
        } else if($param == "purchasing") {
            $result = "Purchasing";
        } else if($param == "other") {
            $result = "Other";
        } else if($param == "expo") {
            $result = "Expo";
        } else if($param == "office") {
            $result = "Office";
        } else if($param == "modern") {
            $result = "Modern Trade";
        } else if($param == "surabaya") {
            $result = "Surabaya";
        } else if($param == "sirclo") {
            $result = "Sirclo";
        } else if($param == "outright") {
            $result = "Marketplace Outright";
        }

        return $result;
    }
}
if(!function_exists('generate_order_token'))
{
    function generate_order_token(){
        $result = "";
        
        date_default_timezone_set("Asia/Jakarta");
        $now = date("dny");
        $result = "OTK".$now."-".strtoupper(substr(sha1(mt_rand()),17,4));

        return $result;
    }
}
if(!function_exists('checkVia'))
{
    function checkVia($string){
        $result = "";
        
        if($string == 'self'){
            $result = "Self Pick Up";
        } else if($string == 'warehouse'){
            $result = "Warehouse Fleet";
        } else {
            $result = "3rd Party";
        }

        return $result;
    }
}
if(!function_exists('encrypt_key'))
{
    function encrypt_key($string){
        $result = "";

        $encrypt_method = "AES-256-CBC";
        $secret_key = 'warehouse key';
        $secret_iv = 'warehouse iv';
        // hash
        $key = hash('sha256', $secret_key);
    
        // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
        $iv = substr(hash('sha256', $secret_iv), 0, 16);

        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $result = base64_encode($output);


        return $result;
    }
}
if(!function_exists('decrypt_key'))
{
    function decrypt_key($string){
        $result = "";

        $encrypt_method = "AES-256-CBC";
        $secret_key = 'warehouse key';
        $secret_iv = 'warehouse iv';
        // hash
        $key = hash('sha256', $secret_key);
    
        // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
        $iv = substr(hash('sha256', $secret_iv), 0, 16);
        $result = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);

        return $result;
    }
}
if(!function_exists('multipleSelectJobArray'))
{
    function multipleSelectJobArray($id, $datas, $param){
        $selected = "";
        for($i=0; $i < count($datas); $i++){
            $selected .= $id == $datas[$i][$param] ? "selected" : "";
        }
        return $selected;
    }
}
if(!function_exists('labelPublish'))
{
    function labelPublish($status){
        return $status != "Publish" ? "<span class='label bg-yellow'>Not Publish</span>" : "<span class='label bg-green'>Publish</span>";
    }
}
if(!function_exists('checkStatus'))
{
    function checkStatus($status){
        return $status != "Publish" ? "danger" : "";
    }
}
if(!function_exists('cleanSpace'))
{
    function cleanSpace($string) {
        $string = trim($string);
        while(strpos($string,' ')){
            $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
        }
        return $string;
    }
}
if(!function_exists('smtp_mail_attachment'))
{
    function smtp_mail_attachment($to, $from_url, $from, $from_password, $from_name, $subject, $body, $reply, $attachments){
        global $error;
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPDebug = '';
        $mail->Debugoutput = 'html'; // debugging: 1 = errors and messages, 2 = messages only
        $mail->Host = $from_url;
        $mail->Port = 465;
        $mail->SMTPSecure = 'ssl';
        $mail->SMTPAuth = true;
        $mail->Username = $from;
        $mail->Password = $from_password; 
        $mail->setFrom($from, $from_name);
        $mail->addReplyTo($reply, $from_name);
        $mail->Subject = $subject;
        $mail->isHTML(true); //Send HTML or Plain Text email
        $mail->Body = $body;
        if(is_array($to)){
            for($i=0; $i<count($to); $i++){
                $mail->AddAddress($to[$i]);
            }
        }else{
            $mail->AddAddress($to);
        }
        //Attachments
        if($attachments != ""){
            $mail->addAttachment($attachments);
        }
        //check email send
        if(!$mail->Send()) {
            $error = 'Mail error: '.$mail->ErrorInfo;
            return false;
        } else {
            $error = 'Message sent!';
            return true;
        }
    }
}
if(!function_exists('smtp_mail_tes'))
{
    function smtp_mail_tes($to, $from_url, $from, $from_password, $from_name, $subject, $body, $reply){
        global $error;
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPDebug = '1'; // debugging: 1 = errors and messages, 2 = messages only
        //$mail->Debugoutput = 'html';
        $mail->Host = $from_url;
        $mail->Port = 465;
        //$mail->Port = 587;
        $mail->SMTPSecure = 'ssl';
        //$mail->SMTPSecure = 'tls';
        $mail->SMTPAuth = true;
        $mail->Username = $from;
        $mail->Password = $from_password; 
        $mail->setFrom($from, $from_name);
        $mail->addReplyTo($reply, $from_name);
        $mail->Subject = $subject;
        $mail->isHTML(true); //Send HTML or Plain Text email
        $mail->Body = $body;
        //$mail->AddAddress($to);
        if(is_array($to)){
            for($i=0; $i<count($to); $i++){
                $mail->AddAddress($to[$i]);
            }
        }else{
            $mail->AddAddress($to);
        }
        //check email send
        if(!$mail->Send()) {
            $error = 'Mail error: '.$mail->ErrorInfo;
            return false;
        } else {
            $error = 'Message sent!';
            return true;
        }
    }
}
if(!function_exists('smtp_mail'))
{
    function smtp_mail($to, $from_url, $from, $from_password, $from_name, $subject, $body, $reply){
        global $error;
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPDebug = ''; // debugging: 1 = errors and messages, 2 = messages only
        //$mail->Debugoutput = 'html';
        $mail->Host = $from_url;
        $mail->Port = 465;
        //$mail->Port = 587;
        $mail->SMTPSecure = 'ssl';
        //$mail->SMTPSecure = 'tls';
        $mail->SMTPAuth = true;
        $mail->Username = $from;
        $mail->Password = $from_password; 
        $mail->setFrom($from, $from_name);
        $mail->addReplyTo($reply, $from_name);
        $mail->Subject = $subject;
        $mail->isHTML(true); //Send HTML or Plain Text email
        $mail->Body = $body;
        //$mail->AddAddress($to);
        if(is_array($to)){
            for($i=0; $i<count($to); $i++){
                $mail->AddAddress($to[$i]);
            }
        }else{
            $mail->AddAddress($to);
        }
        //check email send
        if(!$mail->Send()) {
            $error = 'Mail error: '.$mail->ErrorInfo;
            return false;
        } else {
            $error = 'Message sent!';
            return true;
        }
    }
}
if(!function_exists('simple_smtp'))
{
    function simple_smtp($to, $from_url, $from, $from_password, $from_name, $subject, $body){
        global $error;
        $mail = new PHPMailer(); // create a new object
        $mail->IsSMTP(); // enable SMTP
        $mail->SMTPDebug = ''; // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth = true; // authentication enabled
        $mail->SMTPSecure = ''; // secure transfer enabled REQUIRED for Gmail
        $mail->Host = $from_url;
        $mail->Port = 587;
        $mail->Username = $from;
        $mail->Password = $from_password;
        $mail->SetFrom($from, $from_name);
        $mail->Subject = $subject;
        $mail->isHTML(true); //Send HTML or Plain Text email
        $mail->Body = $body;
        $mail->AddAddress($to);
        if(!$mail->Send()) {
            $error = 'Mail error: '.$mail->ErrorInfo;
            return false;
        } else {
            $error = 'Message sent!';
            return true;
        }
    }
}
if(!function_exists('generateRandomString'))
{
    function generateRandomString($length){
        $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $charactersLength = strlen($characters);
        $randomString = "";
        for($i = 0; $i < $length; $i++){
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
}
if(!function_exists('create_session'))
{
    function create_session($id, $fname, $code, $email, $image){
        $_SESSION['userData'] = array();
        $_SESSION['userData']['id'] = $id;
        $_SESSION['userData']['name'] = $fname;
        $_SESSION['userData']['img'] = $image;
        $_SESSION['userData']['auth_code'] = $code;
        $_SESSION['userData']['email'] = $email;
    }
}
if(!function_exists('relative_time'))
{
    function relative_time($ts)
    {
        if(!ctype_digit($ts))
            $ts = strtotime($ts);
        $diff = time() - $ts;
        if($diff == 0)
            return 'now';
        elseif($diff > 0)
        {
            $day_diff = floor($diff / 86400);
            if($day_diff == 0)
            {
                if($diff < 60) return 'just now';
                if($diff < 120) return '1 minute ago';
                if($diff < 3600) return floor($diff / 60) . ' minutes ago';
                if($diff < 7200) return '1 hour ago';
                if($diff < 86400) return floor($diff / 3600) . ' hours ago';
            }
            if($day_diff == 1) return 'Yesterday';
            if($day_diff < 7) return $day_diff . ' days ago';
            if($day_diff < 31) return ceil($day_diff / 7) . ' weeks ago';
            if($day_diff < 60) return 'last month';
            return date('F Y', $ts);
        }
        else
        {
            $diff = abs($diff);
            $day_diff = floor($diff / 86400);
            if($day_diff == 0)
            {
                if($diff < 120) return 'in a minute';
                if($diff < 3600) return 'in ' . floor($diff / 60) . ' minutes';
                if($diff < 7200) return 'in an hour';
                if($diff < 86400) return 'in ' . floor($diff / 3600) . ' hours';
            }
            if($day_diff == 1) return 'Tomorrow';
            if($day_diff < 4) return date('l', $ts);
            if($day_diff < 7 + (7 - date('w'))) return 'next week';
            if(ceil($day_diff / 7) < 4) return 'in ' . ceil($day_diff / 7) . ' weeks';
            if(date('n', $ts) == date('n') + 1) return 'next month';
            return date('F Y', $ts);
        }
    }
}
if(!function_exists('end_session'))
{
    function end_session(){
        foreach($_SESSION['userData'] as $value){
            unset($value);
        }
        unset($_SESSION['userData']);
    }
}
if(!function_exists('generate_code'))
{
    function generate_code($length=6,$type=1){
        $key = '';
        switch($type){
            case 2:
            $pattern = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
            break;
            case 3:
            $pattern = "12345678901234567890123456789012345678901234567890";
            break;
            default:
            $pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
            break;
        }
        for($i=0;$i<$length;$i++){
            $key .= $pattern[rand(0,35)];
        }
        return strtoupper($key);
    }
}
if(!function_exists('getBatch'))
{
    function getBatch($page){
        $test = 10;
        $batch =1;
        $flag = false;
        while(!$flag){
          if($page > $test){
              $test = $test + 10;
              $batch++;
          }else{
              $flag = true;
          }
      }
      return $batch;
    }
}
if(!function_exists('clean'))
{
    function clean($string) {
        $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
        $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
        $string = strtolower($string); // Convert to lowercase
        return $string;
    }
}
if(!function_exists('encode'))
{
   function encode($param){
        $new_result = $param;
        if($param != null){
            $result = clean($param);
            $new_result = rawurlencode($result);
        }
        return $new_result;
    }
}
if(!function_exists('decode'))
{
    function decode($param){
        $new_result = $param;
        if($param != null){
           $new_result = str_replace('-',' ',$param);
       }
       return $new_result;
    }
}
if(!function_exists('isSelected'))
{
    function isSelected($real_value, $data){
        $text = "";
        if($real_value == $data){
           $text = " selected";
       }
       return $text;
    }
}
if(!function_exists('checkImage'))
{
    function checkImage($photoThmb) {
        if ($photoThmb == null) {
            $temp = "img/img-empty.png";
        } else {
            $temp = "$photoThmb";
        }
        return $temp;
    }
}
if(!function_exists('nowDate'))
{
    function nowDate() {
        $date = date_create("", timezone_open('Asia/Jakarta'));
        $date = date_format($date, 'Y-m-d');
        return $date;
    }
}
if(!function_exists('nowDateComplete'))
{
    function nowDateComplete() {
        $date = date_create("", timezone_open('Asia/Jakarta'));
        $date = date_format($date, 'jS F Y - g:i A');
        return $date;
    }
}
if(!function_exists('check_input'))
{
    //Function To check and secure the login info from hacker attack
    function check_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = addslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES);
        return $data;
    }
}
if(!function_exists('getDocType'))
{
    //Function get the extension of the document source
    function getDocType($data) {
        $data = substr($data, -5);
        $pos = strpos($data, ".");
        if ($pos !== false) {
            $data = substr($data, $pos + 1);
            if ($data == "pdf" || $data == "doc" || $data == "docx") {
                return $data;
            } else {
                return "link";
            }
        } else {
            return "link";
        }
    }
}
if(!function_exists('charLength'))
{
    //function to put 3dots after lengthy string
    function charLength($data, $length) {
        $strLength = strlen($data);
        if ($strLength > $length) {
            $data = substr(strip_tags($data), 0, $length) . "...";
        }
        return $data;
    }
}
if(!function_exists('correctDisplay'))
{
    function correctDisplay($data) {
        $data = htmlspecialchars_decode(stripslashes($data), ENT_QUOTES);
        return $data;
    }
}
if(!function_exists('checkVideoSource'))
{
    //function
    function checkVideoSource($data) {
        $findme = "youtube.com/watch?v=";
        $findme2 = "youtu.be/";
        $pos = strpos($data, $findme);
        $pos2 = strpos($data, $findme2);
        $dataLength = strlen($data);
        if ($pos !== false) {
            $findAmp = stripos($data, '&');
            if ($findAmp === false) {
                $data = str_replace("youtube.com/watch?v=", "youtube.com/embed/", $data);
                return $data;
            } else {
                $lengthTrimmed = $dataLength - ($findAmp);
                $data = substr($data, 0, -$lengthTrimmed);
                $data = str_replace("youtube.com/watch?v=", "youtube.com/embed/", $data);
                return $data;
            }
        } else if ($pos2 !== false) {
            $data = str_replace("youtu.be/", "youtube.com/embed/", $data);
            return $data;
        } else {
            return $data;
        }
    }
}
if(!function_exists('encodeURLslash'))
{
    function encodeURLslash($data) {
        $data = str_replace("/", "&slash", $data);
        return $data;
    }
}
if(!function_exists('decodeURLslash'))
{
    function decodeURLslash($data) {
        $data = str_replace("&slash", "/", $data);
        return $data;
    }
}
if(!function_exists('encodeURLspace'))
{
    function encodeURLspace($data) {
        $data = str_replace(" ", "%20", $data);
        return $data;
    }
}
if(!function_exists('curPageURL'))
{
    function curPageURL() {
        $pageURL = 'http';
        if ($_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }
}
if(!function_exists('doHash'))
{
    function doHash($secData, $salt) {
    //creates a random 5 character sequence
        $secData = hash('sha256', $salt . $secData);
        return $secData;
    }
}
?>