<?php
$errors = array();
if(!defined('datalist_db_encoding')) define('datalist_db_encoding', 'UTF-8');

function count_id($start=''){
  if($start!=''){
    $count = intval($start);  
  }else{  
    static $count = 1;
  }
  return $count++;
}

 /*--------------------------------------------------------------*/
 /* Function for Remove escapes special
 /* characters in a string for use in an SQL statement
 /*--------------------------------------------------------------*/
function escape($str){
  global $con;
  $escape = mysqli_real_escape_string($con,$str);
  return $escape;
}

/*--------------------------------------------------------------*/
/* Function for Remove html characters
/*--------------------------------------------------------------*/
function remove_junk($str){
  $str = nl2br(ltrim($str));
  $str = htmlspecialchars(strip_tags($str, ENT_QUOTES));
  return $str;
}

/*--------------------------------------------------------------*/
/* Function for Uppercase first character
/*--------------------------------------------------------------*/
function first_character($str){
  $val = str_replace('-'," ",$str);
  $val = ucfirst($val);
  return $val;
}


/*--------------------------------------------------------------*/
/* Function for DAY TO YEAR CONVERT
/*--------------------------------------------------------------*/
function daytoyearconvert($days){
$start_date = new DateTime();
$end_date = (new $start_date)->add(new DateInterval("P{$days}D") );
$dd = date_diff($start_date,$end_date);
if($dd->y==0 && $dd->d!=0){
  $data=$dd->m." months ".$dd->d." days";  
}else if($dd->m==0 && $dd->d!=0 && $dd->y==0){
     $data= $dd->d." days";  
}else if($dd->m==0 && $dd->d==0 && $dd->y!=0){
      $data= $dd->y." years";  
}else if($dd->m!=0 && $dd->d==0 && $dd->y==0){
    $data=$dd->m." months ";
}else{
     $data=$dd->y." years ".$dd->m." months ".$dd->d." days";
}
return $data;
}

/*--------------------------------------------------------------*/
/* Function for encription & decription
/*--------------------------------------------------------------*/

function encrypt ($pure_string, $encryption_key) {
$cipher     = 'ABA-256-AXE';
$options    = OPENSSL_RAW_DATA;
$hash_algo  = 'sha256';
$sha2len    = 32;
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($pure_string, $cipher, $encryption_key, $options, $iv);
$hmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);
return $iv.$hmac.$ciphertext_raw;
}

function decrypt ($encrypted_string, $encryption_key) {
$cipher     = 'ABA-256-AXE';
$options    = OPENSSL_RAW_DATA;
$hash_algo  = 'sha256';
$sha2len    = 32;
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($encrypted_string, 0, $ivlen);
$hmac = substr($encrypted_string, $ivlen, $sha2len);
$ciphertext_raw = substr($encrypted_string, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $encryption_key, $options, $iv);
$calcmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);
if(function_exists('hash_equals')) {
if (hash_equals($hmac, $calcmac)) return $original_plaintext;
} else {
if ($this->hash_equals_custom($hmac, $calcmac)) return $original_plaintext;
}
}

function hash_equals_custom($knownString, $userString) {
if (function_exists('mb_strlen')) {
$kLen = mb_strlen($knownString, '8bit');
$uLen = mb_strlen($userString, '8bit');
} else {
$kLen = strlen($knownString);
$uLen = strlen($userString);
}
if ($kLen !== $uLen) {
return false;
}
$result = 0;
for ($i = 0; $i < $kLen; $i++) {
$result |= (ord($knownString[$i]) ^ ord($userString[$i]));
}
return 0 === $result;
}

define('ENCRYPTION_KEY', '__^%&A@$&*!X@#$%^E&*^__');

//encrypt($string, ENCRYPTION_KEY);
//decrypt($encrypted, ENCRYPTION_KEY);

/*--------------------------------------------------------------*/
/* Function for Creting random string
/*--------------------------------------------------------------*/

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

/*--------------------------------------------------------------*/
/* Function for  Creat Random Password
/*--------------------------------------------------------------*/	
function randomPassword($length,$count, $characters) {
 
// $length - the length of the generated password
// $count - number of passwords to be generated
// $characters - types of characters to be used in the password
 
// define variables used within the function    
$symbols = array();
$passwords = array();
$used_symbols = '';
$pass = '';
 
// an array of different character types    
$symbols["lower_case"] = 'abcdefghijklmnopqrstuvwxyz';
$symbols["upper_case"] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$symbols["numbers"] = '1234567890';
$symbols["special_symbols"] = '!?~@#-_+<>[]{}';
 
$characters = split(",",$characters); // get characters types to be used for the passsword
foreach ($characters as $key=>$value) {
$used_symbols .= $symbols[$value]; // build a string with all characters
}
$symbols_length = strlen($used_symbols) - 1; //strlen starts from 0 so to get number of characters deduct 1
     
for ($p = 0; $p < $count; $p++) {
$pass = '';
for ($i = 0; $i < $length; $i++) {
$n = rand(0, $symbols_length); // get a random character from the string with all characters
$pass .= $used_symbols[$n]; // add the character to the password string
}
$passwords[] = $pass;
}
     
return $passwords; // return the generated password
	
//how to use
// generate one password using 5 upper and lower case characters
//randomPassword(5,1,"lower_case,upper_case");
 
// generate three passwords using 10 lower case characters and numbers
//randomPassword(10,3,"lower_case,numbers");
 
// generate five passwords using 12 lower case and upper case characters, numbers and special symbols
//randomPassword(12,5,"lower_case,upper_case,numbers,special_symbols");
}

/*----------------------------------------------------------------------------------*/
/* Function for welcome user
/*----------------------------------------------------------------------------------*/
function get_welmsg(){
//$ctime = strftime("%H:%M:%S", time());

$date = new DateTime();
$ctime = $date->format('Y-m-d');


$wel = '';
if ($ctime >= '18:00:00' and $ctime <= '20:59:59'){
$wel = 'Evening';
}elseif($ctime >= '21:00:00' and $ctime <= '23:59:59'){
$wel = 'Night';
}elseif($ctime >= '00:00:00' and $ctime <= '06:59:59'){
$wel = 'Midnight'; 
}elseif($ctime >= '07:00:00' and $ctime <= '11:59:59'){
$wel = 'Morning'; 
}elseif($ctime >= '12:00:00' and $ctime <= '17:59:59'){
$wel = 'Noon';
}
return $wel;
}

/*--------------------------------------------------------------*/
/* Function for read & write log
/*--------------------------------------------------------------*/

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';
return $ipaddress;
}

function get_client_mac(){
$mac = exec('getmac'); 
$mac = strtok($mac, ' ');
return $mac;    
}

function write_activity($uid,$fild,$title,$history,$btitle='',$bhistory=''){
global $con;
if($btitle!=''){$btitle="'".$btitle."'";}else{$btitle='NULL';}
if($bhistory!=''){$bhistory="'".$bhistory."'";}else{$bhistory='NULL';}    
$key=strtoupper($fild);
//$time = strftime("%Y-%m-%d %H:%M:%S", time());

$date = new DateTime();
$time = $date->format('Y-m-d');


$ibrid=$_SESSION['abrid'];
$ip=get_client_ip();
$mac=get_client_mac();    
$sql="INSERT INTO tbl_activity (uid,filds,title,btitle,activity,bactivity,acdtime,brid,ip,mac) VALUES ('$uid','$key','$title',$btitle,'$history',$bhistory,'$time','$ibrid','$ip','$mac')";
$result=mysqli_query($con,$sql) or die(mysqli_error($con));    
}

//key=U,A
function read_activity($uid,$fild,$key){
global $con;
$ibrid=$_SESSION['abrid'];    
$out='';
if($key=='A'){
$sql="SELECT DISTINCT CAST(acdtime AS DATE) AS date FROM tbl_activity WHERE filds='$fild' ORDER BY date DESC";    
}else{
$sql="SELECT DISTINCT CAST(acdtime AS DATE) AS date FROM tbl_activity WHERE uid='$uid' AND filds='$fild' AND brid='$ibrid' ORDER BY date DESC";    
}    
$result=mysqli_query($con,$sql) or die(mysqli_error($con));   
if($result->num_rows > 0) {
$out.='<div class="row">';
$out.='<div class="col-md-12">';
$out.='<div class="alert alert-history" style="background-color: transparent !important;border: 0px  !important;max-height:400px;min-height: 500px">';
$out.='<ul class="timeline">';     
while($row=mysqli_fetch_array($result)){    
$date=$row['date'];
if(get_fild_data('tbl_setting','1','sval')==0){    
$out.='<li ><span class="label label-success">'.date("d M Y", strtotime($row['date']));
$out.='</span></li>';
}else{
$out.='<li ><span class="label label-success">'.bnEngDate($row['date']);
$out.='</span></li>';    
}
if($key=='A'){
$sql="SELECT tbl_activity.uid,tbl_user.name,tbl_user.bname,CAST(tbl_activity.acdtime AS DATE) AS date FROM tbl_activity LEFT JOIN tbl_user ON tbl_user.id=tbl_activity.uid WHERE tbl_activity.filds='$fild' AND CAST(tbl_activity.acdtime AS DATE)='$date' GROUP BY CAST(tbl_activity.acdtime AS DATE) ORDER BY tbl_activity.acdtime DESC";   
}else{
$sql="SELECT tbl_activity.uid,tbl_user.name,tbl_user.bname,CAST(tbl_activity.acdtime AS DATE) AS date,tbl_activity.brid FROM tbl_activity LEFT JOIN tbl_user ON tbl_user.id=tbl_activity.uid WHERE tbl_activity.uid='$uid' AND tbl_activity.filds='$fild' AND CAST(tbl_activity.acdtime AS DATE)='$date' AND tbl_activity.brid='$ibrid' GROUP BY CAST(tbl_activity.acdtime AS DATE) ORDER BY tbl_activity.acdtime DESC";    
} 
$results=mysqli_query($con,$sql) or die(mysqli_error($con));
while($rows=mysqli_fetch_array($results)){ 
if($key=='A'){
$sql="SELECT tbl_activity.uid,tbl_user.name,tbl_user.bname,tbl_activity.title,tbl_activity.btitle,tbl_activity.bactivity,tbl_activity.activity,DATE_FORMAT(tbl_activity.acdtime, '%r') AS times FROM tbl_activity LEFT JOIN tbl_user ON tbl_user.id=tbl_activity.uid WHERE tbl_activity.filds='$fild' AND CAST(tbl_activity.acdtime AS DATE)='$date' ORDER BY tbl_activity.acdtime DESC";   
}else{
$sql="SELECT tbl_activity.uid,tbl_user.name,tbl_user.bname,tbl_activity.title,tbl_activity.btitle,tbl_activity.activity,tbl_activity.bactivity,DATE_FORMAT(tbl_activity.acdtime, '%r') AS times FROM tbl_activity LEFT JOIN tbl_user ON tbl_user.id=tbl_activity.uid WHERE tbl_activity.uid='$uid' AND tbl_activity.filds='$fild' AND CAST(tbl_activity.acdtime AS DATE)='$date' ORDER BY tbl_activity.acdtime DESC";    
}
$hist=mysqli_query($con,$sql) or die(mysqli_error($con));
while($his=mysqli_fetch_array($hist)){     
$out.='<li>';
if(get_fild_data('tbl_setting','1','sval')==0){
$time=$his['times'];
$title=$his['title'];
$acvity=$his['activity'];    
if($his['uid']==$uid){    
$person='You';
}else{
$person=$his['name'];    
}
}else{
$time=engToBn($his['times']);
if($his['btitle']!=''){
$title=$his['btitle'];    
}else{
$title=$his['title'];    
}
if($his['bactivity']!=''){
$acvity=$his['bactivity'];    
}else{
$acvity=$his['activity'];   
}         
if($his['uid']==$uid){    
$person='আপনি';
}else{
if($his['bname']!=''){    
$person=$his['bname'];
}else{
$person=$his['name'];    
}
}    
}    
$out.='<i class="fa fa-chevron-right bg-gray"></i>
<div class="timeline-item" style="background-color: transparent !important">
<span class="time"><i class="fa fa-clock-o"></i> '.$time; 
$out.='</span>';
$out.='<h3 class="timeline-header"> <a href="#">';
$out.=$person;         
$out.='</a></h3>
<div class="timeline-body">
<p class="timeline-title">'.$title;   
$out.='</p>'.$acvity;
$out.='</div></div></li>';
} 
}        
}
$out.='</ul></div>';    
$out.='</div></div>';    
}else{
$out='';    
}
return $out;       
}


/*--------------------------------------------------------------*/
/* Function number to word
/*--------------------------------------------------------------*/
function numtoword($number) {
   
    $hyphen      = '-';
    $conjunction = '  ';
    $separator   = ' ';
    $negative    = 'negative ';
    $decimal     = ' point ';
    $dictionary  = array(
        0  => 'Zero',
        1  => 'One',
        2  => 'Two',
        3  => 'Three',
        4  => 'Four',
        5  => 'Five',
        6  => 'Six',
        7  => 'Seven',
        8  => 'Eight',
        9  => 'Nine',
        10 => 'Ten',
        11 => 'Eleven',
        12 => 'Twelve',
        13 => 'Thirteen',
        14 => 'Fourteen',
        15 => 'Fifteen',
        16 => 'Sixteen',
        17 => 'Seventeen',
        18 => 'Eighteen',
        19 => 'Nineteen',
        20 => 'Twenty',
        21 => 'Twenty-One',
        22 => 'Twenty-Two',
        23 => 'Twenty-Three',
        24 => 'Twenty-Four',
        25 => 'Twenty-Five',
        26 => 'Twenty-Six',
        27 => 'Twenty-Seven',
        28 => 'Twenty-Eight',
        29 => 'Twenty-Nine',
        30 => 'Thirty',
        31 => 'Thirty-One',
        32 => 'Thirty-Two',
        33 => 'Thirty-Three',
        34 => 'Thirty-Four',
        35 => 'Thirty-Five',
        36 => 'Thirty-Six',
        37 => 'Thirty-Seven',
        38 => 'Thirty-Eight',
        39 => 'Thirty-Nine',
        40 => 'Forty',
        41 => 'Forty-One',
        42 => 'Forty-Two',
        43 => 'Forty-Three',
        44 => 'Forty-Four',
        45 => 'Forty-Five',
        46 => 'Forty-Six',
        47 => 'Forty-Seven',
        48 => 'Forty-Eight',
        49 => 'Forty-Nine',
        50 => 'Fifty',
        51 => 'Fifty-One',
        52 => 'Fifty-Two',
        53 => 'Fifty-Three',
        54 => 'Fifty-Four',
        55 => 'Fifty-Five',
        56 => 'Fifty-Six',
        57 => 'Fifty-Seven',
        58 => 'Fifty-Eight',
        59 => 'Fifty-Nine',
        60 => 'Sixty',
        61 => 'Sixty-One',
        62 => 'Sixty-Two',
        63 => 'Sixty-Three',
        64 => 'Sixty-Four',
        65 => 'Sixty-Five',
        66 => 'Sixty-Six',
        67 => 'Sixty-Seven',
        68 => 'Sixty-Eight',
        69 => 'Sixty-Nine',
        70 => 'Seventy',
        71 => 'Seventy-One',
        72 => 'Seventy-Two',
        73 => 'Seventy-Three',
        74 => 'Seventy-Four',
        75 => 'Seventy-Five',
        76 => 'Seventy-Six',
        77 => 'Seventy-Seven',
        78 => 'Seventy-Eight',
        79 => 'Seventy-Nine',
        80 => 'Eighty',
        81 => 'Eighty-One',
        82 => 'Eighty-Two',
        83 => 'Eighty-Three',
        84 => 'Eighty-Four',
        85 => 'Eighty-Five',
        86 => 'Eighty-Six',
        87 => 'Eighty-Seven',
        88 => 'Eighty-Eight',
        89 => 'Eighty-Nine',
        90 => 'Ninety',
        91 => 'Ninety-One',
        92 => 'Ninety-Two',
        93 => 'Ninety-Three',
        94 => 'Ninety-Four',
        95 => 'Ninety-Five',
        96 => 'Ninety-Six',
        97 => 'Ninety-Seven',
        98 => 'Ninety-Eight',
        99 => 'Ninety-Nine',
        100 => 'Hundred',
        1000                => 'Thousand',
        100000              => 'Lakhs',
        1000000             => 'Million',
        10000000            => 'Core',
        1000000000          => 'Billion',
        1000000000000       => 'Trillion',
        1000000000000000    => 'Quadrillion',
        1000000000000000000 => 'Quintillion'
    );
   
    if (!is_numeric($number)) {
        return false;
    }
   
    if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
        // overflow
        trigger_error(
            'numtoword only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
            E_USER_WARNING
        );
        return false;
    }

    if ($number < 0) {
        return $negative . numtoword(abs($number));
    }
   
    $string = $fraction = null;
   
    if (strpos($number, '.') !== false) {
        list($number, $fraction) = explode('.', $number);
    }
   
    switch (true) {
        case $number < 21:
            $string = $dictionary[$number];
            break;
        case $number < 100:
            $tens   = ((int) ($number / 10)) * 10;
            $units  = $number % 10;
            $string = $dictionary[$tens];
            if ($units) {
                $string .= $hyphen . $dictionary[$units];
            }
            break;
        case $number < 1000:
            $hundreds  = $number / 100;
            $remainder = $number % 100;
            $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
            if ($remainder) {
                $string .= $conjunction . numtoword($remainder);
            }
            break;
        case $number < 100000:
              $thousand  = $number / 1000;
              $tremainder = $number % 1000;
              $string = $dictionary[$thousand] . ' ' . $dictionary[1000];
              if ($tremainder) {
                  $string .= $conjunction . numtoword($tremainder);
              }
        break;
        case $number < 10000000:
          $lakhs  = $number / 100000;
          $lremainder = $number % 100000;
          $string = $dictionary[$lakhs] . ' ' . $dictionary[100000];
          if ($lremainder) {
              $string .= $conjunction . numtoword($lremainder);
          }
        break;
        case $number < 1000000000:
          $core  = $number / 10000000;
          $cremainder = $number % 10000000;
          $string = $dictionary[$core] . ' ' . $dictionary[10000000];
          if ($cremainder) {
              $string .= $conjunction . numtoword($cremainder);
          }
        break;
        default:
            $baseUnit = pow(1000, floor(log($number, 1000)));
            $numBaseUnits = (int) ($number / $baseUnit);
            $remainder = $number % $baseUnit;
            $string = numtoword($numBaseUnits) . ' ' . $dictionary[$baseUnit];
            if ($remainder) {
                $string .= $remainder < 100 ? $conjunction : $separator;
                $string .= numtoword($remainder);
            }
            break;
    }
   
    if (null !== $fraction && is_numeric($fraction)) {
        $string .= $decimal;
        $words = array();
        foreach (str_split((string) $fraction) as $number) {
            $words[] = $dictionary[$number];
        }
        $string .= implode(' ', $words);
    }
   
    return $string;
}

/*--------------------------------------------------------------*/
/* Function for convert local number
/*--------------------------------------------------------------*/
	
function asTaka($value) {
		if ($value<0) return "-".asTaka(-$value);
		return number_format($value, 2);
	}
	
function numtolocal($num,$symbol=''){
    if(setlocale(LC_MONETARY, 'en_BD'))
    if($symbol!=''){
        return $symbol.' '. asTaka($num);
        }else{
        return asTaka($num);    
        }     
    else {
    if (strpos($num, '.') !== false) {
    $epxnum=explode('.',$num);
        $num1=$epxnum['0'];
        $num2=$epxnum['1'];
    }else{
        $num1=$num;
        $num2='';
    }
        
      $explrestunits = "" ;
      if(strlen($num1)>3){
          $lastthree = substr($num1, strlen($num1)-3, strlen($num1));
          $restunits = substr($num1, 0, strlen($num1)-3); // extracts the last three digits
          $restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
          $expunit = str_split($restunits, 2);
          for($i=0; $i<sizeof($expunit); $i++){
              // creates each of the 2's group and adds a comma to the end;
              if($i==0)
              {
                  $explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
              }else{
                  $explrestunits .= $expunit[$i].",";
              }
          }
          if(strlen($num2)>0){
			$dd=$num2;
			$cn='.'.$dd;  
			$nen=number_format($cn,2);
			$epx=explode('.',$nen);	  
          $thecash = $explrestunits.$lastthree.'.'.$epx[1];
            }else{
            $thecash = $explrestunits.$lastthree;  
          }  
      } else {
          if(strlen($num2)>0){
			$dd=$num2;
			$cn='.'.$dd;  
			$nen=number_format($cn,2);
			$epx=explode('.',$nen);		
            $thecash = $num1.'.'.$epx[1];  
          }else{
            $thecash = $num1;  
          }
      }
        
if (strpos($thecash, '.') == false){
$thecash=$thecash.'.'.'00';  
}
        
if(substr($thecash,0,2)=='0,'){$thecash='-'.substr($thecash,2);}   
if($symbol!=''){
return $symbol.' '. $thecash;
}else{
return $thecash;    
}    
}
}
/*--------------------------------------------------------------*/
/* Function for convert local number to word
/*--------------------------------------------------------------*/
function conToword_local($number,$cname='',$cbroken=''){
    $number=floatval($number);
    $decimal = round($number - ($no = floor($number)), 2) * 100;
    $hundred = null;
    $digits_length = strlen($no);
    $i = 0;
    $str = array();
    $words = array(0 => '', 1 => 'one', 2 => 'two',
        3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six',
        7 => 'seven', 8 => 'eight', 9 => 'nine',
        10 => 'ten', 11 => 'eleven', 12 => 'twelve',
        13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen',
        16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
        19 => 'nineteen', 20 => 'twenty', 30 => 'thirty',
        40 => 'forty', 50 => 'fifty', 60 => 'sixty',
        70 => 'seventy', 80 => 'eighty', 90 => 'ninety');
    $digits = array('', 'hundred','thousand','lakh', 'crore');
    while( $i < $digits_length ) {
        $divider = ($i == 2) ? 10 : 100;
        $number = floor($no % $divider);
        $no = floor($no / $divider);
        $i += $divider == 10 ? 1 : 2;
        if ($number) {
            $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
            $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
            $str [] = ($number < 21) ? $words[$number].' '. $digits[$counter]. $plural.' '.$hundred:$words[floor($number / 10) * 10].' '.$words[$number % 10]. ' '.$digits[$counter].$plural.' '.$hundred;
        } else $str[] = null;
    }
    $Taka = implode('', array_reverse($str));
    $poisha = ($decimal) ? "." . ($words[$decimal / 10] . " " . $words[$decimal % 10]) . ' Poisha' : '';
    return ucwords(($Taka ? $Taka .'Taka Only' : '') . $poisha);
}

/*--------------------------------------------------------------*/
/* Function for get month name
/*--------------------------------------------------------------*/
function getMonthName($mon){
		
        $output='';
		if ($mon == 1){
          $output = 'January';  
        }elseif($mon == 2){
          $output = 'February';   
        }elseif($mon == 3){
          $output = 'March';   
        }elseif($mon == 4){
          $output = 'April';   
        }elseif($mon == 5){
          $output = 'May';   
        }elseif($mon == 6){
          $output = 'June';   
        }elseif($mon == 7){
          $output = 'July';   
        }elseif($mon == 8){
          $output = 'August';   
        }elseif($mon == 9){
          $output = 'September';   
        }elseif($mon == 10){
          $output = 'October';   
        }elseif($mon == 11){
          $output = 'November';   
        }elseif($mon == 12){
          $output = 'December';   
        }
return $output;
}

/*--------------------------------------------------------------*/
/* Function for Display Session Message
   Ex echo displayt_msg($message);
/*--------------------------------------------------------------*/
function save_msg($key,$msg){
	
	if (!isset($_SESSION['gmsg'])){
    $_SESSION['gmsg'] = array();
    }
	
	if(!empty($msg)){
	$_SESSION['gmsg'] = array();
	$_SESSION['gmsg'][0]['key'] =$key;
	$_SESSION['gmsg'][0]['msg'] =$msg;
	}
}

function display_msg(){
   $output = '';
   $type='';
   $symbol='';    
   if(isset($_SESSION['gmsg'])){
	   if(isset($_SESSION['gmsg'][0]['show'])==1){
		   unset($_SESSION['gmsg']);
	   }
   }
   if(isset($_SESSION['gmsg'])){
	   $key=$_SESSION['gmsg'][0]['key'];
	   $msg=$_SESSION['gmsg'][0]['msg'];
       if($key=='w'){$type='alert-warning';$symbol='zmdi zmdi-info-outline';}elseif($key=='s'){$type='alert-success';$symbol='zmdi zmdi-check';}elseif($key=='i'){$type='alert-info';$symbol='zmdi zmdi-info-outline';}elseif($key=='e'){$type='alert-danger';$symbol='zmdi zmdi-block';}
	   $output = '<div class="alert '.$type.' alert-dismissable" id="mymsg">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
				<i class="'.$symbol.' pr-15 pull-left"></i><p class="pull-left">'.$msg.'</p> 
				<div class="clearfix"></div>
				</div>';
	  return $output;
   } else {
     return "" ;
   }
}

/*--------------------------------------------------------------*/
/* Function for check delete depend
/*--------------------------------------------------------------*/
function delete_check($table,$key,$id,$type='',$val=''){
    global $con;
    if($type!=''){
    $sql="SELECT COUNT(*) AS rdata FROM ".$table." WHERE ".$key."='$id' AND ".$type."='$val'";    
    }else{
    $sql="SELECT COUNT(*) AS rdata FROM ".$table." WHERE ".$key."='$id'";    
    }
    $query=mysqli_query($con,$sql)or die(mysqli_error($con));
    $row=mysqli_fetch_array($query);
return $row['rdata'];    
}

/*--------------------------------------------------------------*/
/* Function for Get Limit
/*--------------------------------------------------------------*/
function get_limitpermision($table){
global $con;
$sql = "SELECT COUNT(*) AS rdata FROM ".$table;
$query=mysqli_query($con,$sql)or die(mysqli_error($con));
$row=mysqli_fetch_array($query);
return $row['rdata'];    
}
/*--------------------------------------------------------------*/
/* Read Any Fild Data From Any Table
/*--------------------------------------------------------------*/
function get_fild_data($table, $id = '', $fild, $sql = '') {
    global $con;
    if ($sql != '') {
        $query = "SELECT $fild AS rdata FROM $table WHERE $sql LIMIT 1";
        $stmt = $con->prepare($query);
    } else {
        $query = "SELECT $fild AS rdata FROM $table WHERE id = ? LIMIT 1";
        $stmt = $con->prepare($query);
        $stmt->bind_param("s", $id);
    }

    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    if (isset($row['rdata']) && ($row['rdata'] > 0 || !empty($row['rdata']))) {
        return $row['rdata'];
    } else {
        return 0;
    }
}


/*--------------------------------------------------------------*/
/* Function for get employee code
/*--------------------------------------------------------------*/

function get_empcode($dip){
    global $con;
    $legid='';
    $sgid='';
    $code='';
    $smax=0;
    $lmax=0;
    $sql="SELECT id FROM tbl_employe ORDER BY id DESC LIMIT 1";
    $result=mysqli_query($con,$sql) or die(mysqli_error($con));
	$row=mysqli_fetch_array($result);
    if($row['id']!=''){
    $lmax=intval($row['id']);
    }else{
    $lmax=0;    
    }
    $smax=intval($dip);
    $legid=str_pad($lmax+1, 3, '0', STR_PAD_LEFT);
    $sgid=str_pad($smax, 2, '0', STR_PAD_RIGHT);
    $code='EM-'.$sgid.$legid;
    return $code;
}

/*--------------------------------------------------------------*/
/* Function for get ledger code
/*--------------------------------------------------------------*/

function get_ledgercode($grid){
    global $con;
    $legid='';
    $sgid='';
    $code='';
    $smax=0;
    $lmax=0;
    $sql="SELECT COALESCE((SELECT RIGHT(code,3) FROM tbl_acledger WHERE grid='$grid' ORDER BY RIGHT(code,3) DESC LIMIT 1),0) AS rdata";
    $result=mysqli_query($con,$sql) or die(mysqli_error($con));
	$row=mysqli_fetch_array($result);
    $lmax=intval($row['rdata']);
    $smax=intval($grid);
    $legid=str_pad($lmax+1, 3, '0', STR_PAD_LEFT);
    $grid=str_pad($smax, 3, '0', STR_PAD_RIGHT);
    $code=$grid.$legid;
    return $code;
}

/*--------------------------------------------------------------*/
/* Function for code (CU=Customer,SU=Supplier,PU=Product)
/*--------------------------------------------------------------*/

function get_genid($mod,$key='',$type=''){
    global $con;
    $code = '';
    $ncode='';
    if($key!=''){$pre=strtoupper($key);}else{$pre='ABA';}
    if($mod=='CU'){$table='tbl_customer';}elseif($mod=='SU'){$table='tbl_supplier';}elseif($mod=='PU'){$table='tbl_item';}elseif($mod=='LO'){$table='tbl_loanid';}else{$table='tbl_seritem';}
    $sql="SELECT code FROM ".$table." ORDER BY id DESC LIMIT 1";
    $result=mysqli_query($con,$sql) or die(mysqli_error($con));
    if($result->num_rows > 0) {
	$row=mysqli_fetch_array($result);
    $code=$row['code'];
    if($mod=='CU' || $mod=='SU'){     
    $code=substr($code, 7, 10);
    }else{
    $code=substr($code, 3, -1);    
    }
    $code=$code+1;
    if($mod=='CU'){    
    $code=$pre.'/CU/'.sprintf('%03s', $code);
    }elseif($mod=='SU'){ 
    $code=$pre.'/SU/'.sprintf('%03s', $code);    
    }else{
    if($mod=='PU'){     
    $code=$pre.sprintf('%03s', $code).'P';
    }elseif($mod=='LO'){
    $code=$pre.sprintf('%03s', $code).$type;    
    }else{
    $code=$pre.sprintf('%03s', $code).'S';    
    }
    }
    $ncode=$code;    
    }else{
    if($mod=='CU'){    
    $code=$pre.'/CU/001';
    }elseif($mod=='SU'){ 
    $code=$pre.'/SU/001';
    }elseif($mod=='PU'){
    $code=$pre.'001P';    
    }else{
    if($type!=''){
    $code=$pre.'001'.$type;    
    }else{
    $code=$pre.'001S';    
    }    
    }
    $ncode=$code;    
    }
return $ncode;    
}

/*--------------------------------------------------------------*/
/* Function Generate Invoice No
/*--------------------------------------------------------------*/
// function gen_newinvno($table,$key,$fild=''){
//   global $con;
//   $today = date('dmy');    
//   $key = (string)$key;   
//   $tcode='';
//   $code = '';    
//   if($fild!=''){
// 	$sql="SELECT id,".$fild." AS invno FROM ".$table." ORDER BY id DESC LIMIT 1";  
//   }else{
// 	$sql="SELECT id,invno FROM ".$table." ORDER BY id DESC LIMIT 1";	
//   }  
//   $quiry=mysqli_query($con,$sql) or die(mysqli_error($con));
//   $rowq=mysqli_fetch_array($quiry);        
			
// 	$tinv = $rowq['invno'];				
// 	if(strlen($tinv)>0){
// 	if(substr($tinv,3,6)==$today){
// 	$tcode=intval(substr($tinv,9));
// 	$code=$key.$today.($tcode+1);	
// 	}else{
// 	$code = $key.$today.(1+100);	
// 	}		
// 	}else{
// 	$code = $key.$today.(1+100);		
// 	}	      
//     return $code;
// }


function gen_newinvno($table, $key, $fild = '') {
    global $con;
    $year = date('Y'); // Get the current year
    $today = date('dmy'); // Get the day, month, year in short format (e.g., 311224)
    $key = (string)$key; 
    $code = '';
    $id = 0;

    // Check for the last invoice number of the current year
    if ($fild != '') {
        $sql = "SELECT id, " . $fild . " AS invno FROM " . $table . 
               " WHERE LEFT(" . $fild . ", LENGTH('$key') + 6) = '$key$today' ORDER BY id DESC LIMIT 1";
    } else {
        $sql = "SELECT id, invno FROM " . $table . 
               " WHERE LEFT(invno, LENGTH('$key') + 6) = '$key$today' ORDER BY id DESC LIMIT 1";
    }

    $query = mysqli_query($con, $sql) or die(mysqli_error($con));
    $rowq = mysqli_fetch_array($query);

    if ($rowq) {
        // Extract the numeric part and increment it
        $last_invno = $rowq['invno'];
        $last_number = (int)substr($last_invno, -5); // Get the last 5 digits
        $id = $last_number + 1;
    } else {
        $id = 1; // Start from 1 if no invoice for the current date
    }

    $formatted_id = str_pad($id, 5, '0', STR_PAD_LEFT);
    $code = $key . $today . $formatted_id;

    return $code;
}




/*--------------------------------------------------------------*/
/* Display Address/Contact
/*--------------------------------------------------------------*/
function show_addres($name='',$mobile='',$email='',$web='',$code='',$detid=''){
    $out='';
    if($name!=''){
    $out='<b class="detailsrec" id="'.$detid.'" style="cursor: pointer;">'.$name.'</b>';    
    }
    if($mobile!=''){
    if($out!=''){
    $out.='<br><span style="color:orangered;"><i class="fa fa-phone"></i></span> '.$mobile;    
    }else{
    $out='<span style="color:orangered;"><i class="fa fa-phone"></i></span> '.$mobile;    
    }    
    }
    if($email!=''){
    if($out!=''){
    $out.='<br><span style="color:orangered;"><i class="fa fa-envelope"></i></span> '.$email;    
    }else{
    $out='<span style="color:orangered;"><i class="fa fa-envelope"></i></span> '.$email;    
    }    
    }
    if($web!=''){
    if($out!=''){
    $out.='<br><span style="color:orangered;"><i class="fa fa-link"></i></span> '.$web;    
    }else{
    $out='<span style="color:orangered;"><i class="fa fa-link"></i></span> '.$web;    
    }    
    }
    if($code!=''){
    if($out!=''){
    $out.='<br><span style="color:orangered;"><i class="fa fa-id-card-o"></i></span> '.$code;    
    }else{
    $out='<span style="color:orangered;"><i class="fa fa-id-card-o"></i></span> '.$code;    
    }    
    }
return $out;    
}

/*--------------------------------------------------------------*/
/* Get Page Permission
/*--------------------------------------------------------------*/
function get_section($section){
   global $con;
    if(isset($_SESSION['access'])){
    $seid=$_SESSION['access'];    
    }else{
    $seid=0;    
    }
    $sql="SELECT COUNT(*) AS rdata FROM tbl_userpermision WHERE seid='".$seid."' AND section='".$section."' LIMIT 1";
    $result=mysqli_query($con,$sql) or die(mysqli_error($con));
	$row=mysqli_fetch_array($result);
	return $row['rdata'];    
}

function get_pageval($seid,$pageid,$key){
	global $con;
	$sql = "SELECT ".$key." AS rdata FROM tbl_userpermision WHERE seid='".$seid."' AND pageid='".$pageid."' LIMIT 1";	
	$result=mysqli_query($con,$sql) or die(mysqli_error($con));
	$row=mysqli_fetch_array($result);
	return $row['rdata'];	
}


function get_pagesecurity($pageid,$key,$mod){
   global $con;
    if(isset($_SESSION['access'])){
    $seid=$_SESSION['access'];    
    }else{
    $seid=0;    
    }
    $sql = "SELECT ".$key." AS rdata FROM tbl_userpermision WHERE seid='".$seid."' AND pageid='".$pageid."' LIMIT 1";	
	$result=mysqli_query($con,$sql) or die(mysqli_error($con));
	$row=mysqli_fetch_array($result);
    if($mod=='R'){
    if($row['rdata']==0){    
    header("Location: axe_notfound.php");
    }else{
    return $row['rdata'];    
    }
    }elseif($mod=='P'){
    return $row['rdata'];   
    }
}

/*--------------------------------------------------------------*/
/* Get item name
/*--------------------------------------------------------------*/
function get_name($id){
global $con;
$name='';    
$sql="SELECT * FROM tbl_item WHERE id='$id'";
$query=mysqli_query($con,$sql) or die(mysqli_error($con));
$row=mysqli_fetch_array($query);
$name = $row['name'];
if($row['scatid']!=''){
$name = get_fild_data('tbl_subcat',$row['scatid'],'name').' '.$name;    
}
if($row['colid']!=''){
$name = $name.' '.get_fild_data('tbl_color',$row['colid'],'name');    
}
if($row['brid']!=''){
$name = $name.' '.get_fild_data('tbl_brand',$row['brid'],'name');    
}
return $name;    
}

/*--------------------------------------------------------------*/
/* Get Cash Amount
/*--------------------------------------------------------------*/
function get_cashflow($pino='',$invno=''){
global $con;
if($pino!='' && $invno!=''){
$sql="SELECT COALESCE ((SELECT SUM(debit) FROM tbl_cashflow WHERE pino='$pino' AND invno='$invno'),0) AS cash"; }elseif($pino!='' && $invno==''){
$sql="SELECT COALESCE ((SELECT SUM(debit) FROM tbl_cashflow WHERE pino='$pino'),0) AS cash";    
}elseif($pino=='' && $invno!=''){
$sql="SELECT COALESCE ((SELECT SUM(debit) FROM tbl_cashflow WHERE invno='$pino'),0) AS cash";     
}   
$query=mysqli_query($con,$sql) or die(mysqli_error($con));
$row=mysqli_fetch_array($query);
return $row['cash'];    
}

function get_invcash($invno,$key,$inv=''){
global $con;
if($key=='S'){
if($inv!=''){
//tbl_trarecord    
$sql="SELECT refinv,SUM(IF(xrate=0,amo,amo/xrate)) AS cash FROM tbl_traledger WHERE ((dty='LE' AND did='2') OR (dty IN ('BA','MO'))) AND invno='$invno' AND refinv='$invno'  GROUP BY refinv";    
}else{
$sql="SELECT refinv,SUM(IF(xrate=0,amo,amo/xrate)) AS cash FROM tbl_traledger WHERE ((dty='LE' AND did='2') OR (dty IN ('BA','MO'))) AND refinv='$invno'  GROUP BY refinv";    
}        
}elseif($key=='P'){
if($inv!=''){
$sql="SELECT refinv,SUM(IF(xrate=0,amo,amo/xrate)) AS cash FROM tbl_traledger WHERE ((cty='LE' AND cid='2') OR (cty IN ('BA','MO'))) AND invno='$invno' AND refinv='$invno'  GROUP BY refinv";    
}else{
$sql="SELECT refinv,SUM(IF(xrate=0,amo,amo/xrate)) AS cash FROM tbl_traledger WHERE ((cty='LE' AND cid='2') OR (cty IN ('BA','MO'))) AND refinv='$invno'  GROUP BY refinv";    
}        
}    
$query=mysqli_query($con,$sql) or die(mysqli_error($con));
$row=mysqli_fetch_array($query);
return getfloatval($row['cash']);    
}
/*--------------------------------------------------------------*/
/* Get ledger name
/*--------------------------------------------------------------*/

function get_ledgername($sgrid,$id){
global $con;
$sql='';    
if($sgrid==2){
$sql="SELECT tbl_bacount.id,CONCAT('BA',100+tbl_bacount.id,' - ',tbl_bank.sort,' / ',tbl_bacount.acno) AS name FROM tbl_bacount LEFT JOIN tbl_bank ON tbl_bank.id=tbl_bacount.bid WHERE tbl_bacount.id='$id'";    
}elseif($sgrid==3){
$sql="SELECT id,CONCAT(code,' - ',name) AS name FROM tbl_item WHERE id='$id'";
}elseif($sgrid==4){
$sql="SELECT id,CONCAT(code,' - ',name) AS name FROM tbl_customer WHERE id='$id'";     
}elseif($sgrid==13){
$sql="SELECT id,CONCAT(code,' - ',name) AS name FROM tbl_supplier WHERE id='$id'";    
}elseif($sgrid==33){    
$sql="SELECT id,CONCAT(code,' - ',name) AS name FROM tbl_employe WHERE id='$id'";
}elseif($sgrid==34){    
$sql="SELECT id,CONCAT('MO',100+id,' - ',name,' / ',mobile) AS name FROM tbl_acmobile WHERE id='$id'";
}elseif($sgrid==35){    
$sql="SELECT id,IF(type=0,CONCAT(name,' - ',acno),CONCAT(name,' - ',mobile)) AS cname,name FROM tbl_loanid WHERE id='$id'";    
}else{
$sql="SELECT id,CONCAT(code,' - ',name) AS name FROM tbl_acledger WHERE id='$id'";    
}
$query=mysqli_query($con,$sql) or die(mysqli_error($con));
$row=mysqli_fetch_array($query);
return $row['name'];    
}

function get_ledgertype($sgrid){
$type='';
if($sgrid==2){
$type='BA';
}elseif($sgrid==3){
$type='PD';    
}elseif($sgrid==4){
$type='CU';    
}elseif($sgrid==13){
$type='SU';
}elseif($sgrid==26){
$type='SE';    
}elseif($sgrid==33){
$type='EM';
}elseif($sgrid==34){
$type='MO';
}elseif($sgrid==35){
$type='LO';    
}elseif($sgrid==36){
$type='LO';    
}else{    
$type='LE';
}
return $type;    
}

function get_namebytype($type,$key,$id){
global $con;
$sql='';    
if($type=='BA'){
$sql="SELECT tbl_bacount.id,CONCAT('BA',100+tbl_bacount.id,' - ',tbl_bank.sort,' / ',tbl_bacount.acno) AS cname,CONCAT(tbl_bank.sort,' / ',tbl_bacount.acno) AS name FROM tbl_bacount LEFT JOIN tbl_bank ON tbl_bank.id=tbl_bacount.bid WHERE tbl_bacount.id='$id'";    
}elseif($type=='PD'){
$sql="SELECT id,CONCAT(code,' - ',name) AS cname,name FROM tbl_item WHERE id='$id'";
}elseif($type=='CU'){
$sql="SELECT id,CONCAT(code,' - ',name) AS cname,name FROM tbl_customer WHERE id='$id'";     
}elseif($type=='SU'){
$sql="SELECT id,CONCAT(code,' - ',name) AS cname,name FROM tbl_supplier WHERE id='$id'";    
}elseif($type=='EM'){    
$sql="SELECT id,CONCAT(code,' - ',name) AS cname,name FROM tbl_employe WHERE id='$id'";    
}elseif($type=='LE'){
$sql="SELECT id,CONCAT(code,' - ',name) AS cname,name FROM tbl_acledger WHERE id='$id'";
}elseif($type=='MO'){
$sql="SELECT id,CONCAT(name,' - ',mobile) AS cname,CONCAT(name,' - ',mobile) AS name FROM tbl_acmobile WHERE id='$id'";
}elseif($type=='SE'){
$sql="SELECT id,IF(LENGTH(code)>1,CONCAT(code,' - ',name),name) AS cname,name FROM tbl_seritem WHERE id='$id'";
}elseif($type=='LO'){
$sql="SELECT id,IF(type=0,CONCAT(name,' - ',acno),CONCAT(name,' - ',mobile)) AS cname,name FROM tbl_loanid WHERE id='$id'";    
}
$query=mysqli_query($con,$sql) or die(mysqli_error($con));
$row=mysqli_fetch_array($query);
if($key=='N'){    
return $row['name'];
}else{
return $row['cname'];    
}
}

function getfloatval($value, $places='') {
  $num=floatval($value);
  if($places!=''){
  $plc=intval($places);        
  $result = round($num,5);    
  }else{
  $result = round($num,5);    
  }            
  return $result;
}

/*--------------------------------------------------------------*/
/* Function for product uniq code
/*--------------------------------------------------------------*/
function gen_protrucking($table,$key){
global $con;
$today = date('my');    
$key = (string)$key;   
$tcode='';
$code = '';    
$sql="SELECT id,unqid FROM ".$table." ORDER BY id DESC LIMIT 1";	
$quiry=mysqli_query($con,$sql) or die(mysqli_error($con));
$rowq=mysqli_fetch_array($quiry);        
	
$id=	$rowq['id'];			
$code=$key.$today.($id+1);	 
return $code;   
}

/*--------------------------------------------------------------*/
/* Function for product cost and frice
/*--------------------------------------------------------------*/

function get_proacost($cost,$fdis,$gdis,$vat,$tax,$subtot,$otamo,$spamo,$freight,$less){
$fcost=0;
$dcost=($cost-((($cost-$fdis)*($gdis/100))+$fdis));
$vtcost=(($dcost*($vat/100))+($dcost*($tax/100)));
$otcost=(($otamo/$subtot)*($cost-$fdis));
$spcost=(($spamo/$subtot)*($cost-$fdis));
$frcost=(($freight/$subtot)*($cost-$fdis));
$ls=(($less/$subtot)*($cost-$fdis));
$fcost=getfloatval(($dcost+$vtcost+$otcost+$spcost+$frcost)-$ls);    
return getfloatval($fcost);   
}

function get_reamo($invno,$table){
global $con;
$sql="SELECT COALESCE ((SELECT SUM(IFNULL(adjust,0)+IFNULL(total,0)+IFNULL(less,0)) FROM ".$table." WHERE refinv='$invno' GROUP BY refinv),0) AS rcash";
$reamo=mysqli_query($con,$sql) or die(mysqli_error($con));    
$ramo=mysqli_fetch_array($reamo);

return $ramo['rcash'];    
}

/*--------------------------------------------------------------*/
/* Function for Bangla Date AND number
/*--------------------------------------------------------------*/

function is_leapyear($year) {
$flage=0;    
if ($year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0)){
$flage=1;
}else{
$flage=0;
}
return $flage;
}

function get_bnyear($hour,$day,$month,$year){
$bdyear=($year-593);
if(($month<4) || (($month==4) && (($day<14) || ($day == 14 && $hour < 6)))){
$bdyear-=1;    
}    
return $bdyear;     
}

function get_bndate($hour,$day,$month,$year,$mod='N',$sep='-') {
$bn_months = array(9,10,11,12,1,2,3,4,5,6,7,8);
$bn_month_dates = array(30,30,30,30,31,31,31,31,31,30,30,30);
$bn_month_middate = array(13,12,14,13,14,14,15,15,15,15,14,14);	
$lipyearindex = 3;    
    
$bndate = $day - $bn_month_middate[$month - 1];
if ($hour < 6){ 
$bndate -= 1;
}
if (($day <= $bn_month_middate[$month - 1]) || ($day == $bn_month_middate[$month - 1] + 1 && $hour < 6) ) {
$bndate += $bn_month_middate[$month - 1];
if (is_leapyear($year) && $lipyearindex == $month) 
$bndate += 1;
$bnmonth = $bn_months[$month - 1];
}else{
$bnmonth = $bn_months[$month%12];		
}
$bnyear=get_bnyear($hour,$day,$month,$year); 
if($mod=='N'){    
return bn_num($bndate).$sep.bn_num($bnmonth).$sep.bn_num($bnyear);
}else{
return bn_num($bndate).$sep.bnMoName($bnmonth).$sep.bn_num($bnyear);    
}
}

function bn_num( $int ) {
$enNum = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
$bnNum = array('১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯', '০');

$bnNo = str_replace($enNum,$bnNum,$int);
return $bnNo;
}

function bnMoName($mon){
$mon=intval($mon);    
$bnna = array('1'=>'বৈশাখ', '2'=>'জ্যৈষ্ঠ', '3'=>'আষাঢ়', '4'=>'শ্রাবণ', '5'=>'ভাদ্র','6'=>'আশ্বিন', '7'=>'কার্তিক', '8'=>'অগ্রহায়ণ', '9'=>'পৌষ', '10'=>'মাঘ', '11'=>'ফ্লাগুন', '12'=>'চৈত্র');    
$bnmname = strtr($mon,$bnna);
return $bnmname;
}

function bnDayName($day,$key='F'){
$day=intval($day);
if($key=='F'){    
$bnna = array('1'=>'সোমবার', '2'=>'মঙ্গলবার', '3'=>'বুধবার', '4'=>'বৃহস্পতিবার', '5'=>'শুক্রবার','6'=>'শনিবার', '0'=>'রবিবার');
}else{
$bnna = array('1'=>'সোম', '2'=>'মঙ্গল', '3'=>'বুধ', '4'=>'বৃহস্পতি', '5'=>'শুক্র','6'=>'শনি', '0'=>'রবি');    
}
$bndna = strtr($day,$bnna);
return $bndna;
}

function bnEngName($mon){
$mon=intval($mon);    
$engbna = array('1'=>'জানুয়ারী', '2'=>'ফেব্ররুয়ারি', '3'=>'মার্চ', '4'=>'এপ্রিল', '5'=>'মে','6'=>'জুন', '7'=>'জুলাই', '8'=>'অগাস্ট', '9'=>'সেপ্টেম্বর', '10'=>'অক্টোবর', '11'=>'নভেম্বর', '12'=>'ডিসেম্বর');    
$bnmname = strtr($mon,$engbna);
return $bnmname;
}

function bnEngDate($date){
$edate=explode('-',$date);
$bndate=engToBn($edate[2]).' '.bnEngName($edate[1]).' '.engToBn($edate[0]);
return $bndate;    
}

/*-----------------*/

function engToBn($number){
$eng_to_bn = array('1'=>'১', '2'=>'২', '3'=>'৩', '4'=>'৪', '5'=>'৫','6'=>'৬', '7'=>'৭', '8'=>'৮', '9'=>'৯', '0'=>'০', '.'=>'.', ','=>',');    
$bn_number = strtr($number,$eng_to_bn);
return $bn_number;
}

function numToBn($number){
$num_to_bd = array('1'=>'এক','2'=>'দুই','3'=>'তিন','4'=>'চার','5'=>'পাঁচ','6'=>'ছয়','7'=>'সাত','8'=>'আট', '9'=>'নয়','10'=>'দশ','11'=>'এগার','12'=>'বার','13'=>'তের','14'=>'চৌদ্দ','15'=>'পনের','16'=>'ষোল','17'=>'সতের','18'=>'আঠার','19'=>'ঊনিশ','20'=>'বিশ','21'=>'একুশ','22'=>'বাইশ','23'=>'তেইশ','24'=>'চব্বিশ','25'=>'পঁচিশ','26'=>'ছাব্বিশ','27'=>'সাতাশ','28'=>'আঠাশ','29'=>'ঊনত্রিশ','30'=>'ত্রিশ','31'=>'একত্রিশ','32'=>'বত্রিশ','33'=>'তেত্রিশ','34'=>'চৌত্রিশ','35'=>'পঁয়ত্রিশ','36'=>'ছত্রিশ','37'=>'সাঁইত্রিশ','38'=>'আটত্রিশ','39'=>'ঊনচল্লিশ','40'=>'চল্লিশ','41'=>'একচল্লিশ','42'=>'বিয়াল্লিশ','43'=>'তেতাল্লিশ','44'=>'চুয়াল্লিশ','45'=>'পঁয়তাল্লিশ','46'=>'ছেচল্লিশ','47'=>'সাতচল্লিশ','48'=>'আটচল্লিশ','49'=>'ঊনপঞ্চাশ','50'=>'পঞ্চাশ','51'=>'একান্ন','52'=>'বায়ান্ন','53'=>'তিপ্পান্ন','54'=>'চুয়ান্ন','55'=>'পঞ্চান্ন','56'=>'ছাপ্পান্ন','57'=>'সাতান্ন','58'=>'আটান্ন','59'=>'ঊনষাট','60'=>'ষাট','61'=>'একষট্টি','62'=>'বাষট্টি','63'=>'তেষট্টি','64'=>'চৌষট্টি','65'=>'পঁয়ষট্টি','66'=>'ছেষট্টি','67'=>'সাতষট্টি','68'=>'আটষট্টি','69'=>'ঊনসত্তর','70'=>'সত্তর','71'=>'একাত্তর','72'=>'বাহাত্তর','73'=>'তিয়াত্তর','74'=>'চুয়াত্তর','75'=>'পঁচাত্তর','76'=>'ছিয়াত্তর','77'=>'সাতাত্তর','78'=>'আটাত্তর','79'=>'ঊনআশি','80'=>'আশি','81'=>'একাশি','82'=>'বিরাশি','83'=>'তিরাশি','84'=>'চুরাশি','85'=>'পঁচাশি','86'=>'ছিয়াশি','87'=>'সাতাশি','88'=>'আটাশি','89'=>'ঊননব্বই','90'=>'নব্বই','91'=>'একানব্বই','92'=>'বিরানব্বই','93'=>'তিরানব্বই','94'=>'চুরানব্বই','95'=>'পঁচানব্বই','96'=>'ছিয়ানব্বই','97'=>'সাতানব্বই','98'=>'আটানব্বই','99'=>'নিরানব্বই');    
$word = strtr($number,$num_to_bd);
return $word;
}

function numToBnDecimal($number){
$num_to_bn_decimal = array('0'=>'শূন্য ','1'=>'এক ','2'=>'দুই ','3'=>'তিন ','4'=>'চার ','5'=>'পাঁচ ','6'=>'ছয় ','7'=>'সাত ','8'=>'আট ', '9'=>'নয় ');    
$word = strtr($number,$num_to_bn_decimal);
return $word;
}

function underHundred($number){
$number = ($number == 0)?'': numToBn($number);
return $number;
}

function hundred($number){
$hundreds = 'শত';    
$a = (int)($number/100);
$b = $number%100;
$hundred = ($a == 0)?'': numToBn($a).' '.$hundreds;
return $hundred.' '.underHundred($b);
}

function thousand($number){
$thousands = 'হাজার';    
$a = (int)($number/1000);
$b = $number%1000;
$thousand = ($a == 0)?'': numToBn($a).' '.$thousands;
return $thousand.' '.hundred($b);
}

function lakh($number){
$lakhs = 'লক্ষ';    
$a = (int)($number/100000);
$b = $number%100000;
$lakh = ($a == 0)?'': numToBn($a).' '.$lakhs;
return $lakh.' '.thousand($b);
}

function crore($number){
$crores = 'কোটি';     
$a = (int)($number/10000000);
$b = $number%10000000;
$more_than_core = ($a>99)?lakh($a):numToBn($a);
return $more_than_core.' '.$crores.' '.lakh($b);
}

function numberSelector($number){
if($number > 9999999){
return crore($number);
}elseif($number > 99999){
return lakh($number);
}elseif($number > 999){
return thousand($number);
}elseif($number > 99){
return hundred($number);
}else{
return underHundred($number);
}
}

function numTobnWord($number){
if (!is_numeric($number) ) return 'নম্বর নয়';

if(is_float($number)){
$dot = explode(".", $number);
return numberSelector($dot[0]).' দশমিক '.numToBnDecimal($dot[1]);
}else{
return numberSelector($number);
}
}
