<?php
include("xls.class.php");
//error_reporting(0);
include ("include/returnConfig.php");
function con(){
global $globalConfig;
$db=new DB($globalConfig['dbase'], $globalConfig['dbhost'],$globalConfig['dbuser'], $globalConfig['dbpass']);
return $db;
}
					
// debug message: 1 = info 2 = congratulation 3 = error
function debug_message($message, $kind, $width = false){
	if(!$width){
		$width = '80';
	}
	switch($kind){
		case 1:
			$message_box = '<div class="highlight_box" style="margin: 20px auto ; padding: 0 .7em; width:'.$width.'%;"> 
<p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>
<p>'.$message.'</p>
</p></div>';
		break;
		
		case 2:
			$message_box = '<div class="congratulation_box" style="margin: 20px auto ; padding: 0 .7em; width:'.$width.'%;"> 
<p><span class="ui-icon ui-icon-congratulation" style="float: left; margin-right: .3em;"></span>
<p>'.$message.'</p>
</p></div>';
		break;

		case 3:
			$message_box = '<div class="error_box" style="margin: 20px auto ; padding: 0 .7em; width:'.$width.'%;"> 
<p>
<p><span style="float: left;" class="ui-icon ui-icon-alert"></span>'.$message.'</p>
</p></div>';
		break;
	}
return $message_box;
}
function show_error($error){
global $globalConfig;

switch((int)$error){
	
		case 1:
			$message =$globalConfig['errorNoCookies'];
		break;
		
		case 2:
			$message =$globalConfig['errorDelay'];
		break;
		
		case 3:
			$message =$globalConfig['errorNoAdmin'];
		break;
		
		case 4:
			$message =$globalConfig['errorNoGroup'];
		break;
		
		case 5:
			$message =$globalConfig['errorNoLogin'];
		break;		
		
		case 6:
			$message =$globalConfig['errorInvalid'];
		break;
	}
return '<div dir="rtl" style="color:red; background-color:#FFC4C4; width:100%; border-bottom: 1px solid #F30; border-top: 1px solid #F30; font-size:11px ; font-weight:normal; text-align:right;"><img src="images/notice-alert.png"  align="absmiddle"> '.$message.'</div>';
}
//download
function ipCheck() {
	/*
	This function checks if user is coming behind proxy server. Why is this important?
	If you have high traffic web site, it might happen that you receive lot of traffic
	from the same proxy server (like AOL). In that case, the script would count them all as 1 user.
	This function tryes to get real IP address.
	Note that getenv() function doesn't work when PHP is running as ISAPI module
	*/
		if (getenv('HTTP_CLIENT_IP')) {
			$ip = getenv('HTTP_CLIENT_IP');
		}
		elseif (getenv('HTTP_X_FORWARDED_FOR')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_X_FORWARDED')) {
			$ip = getenv('HTTP_X_FORWARDED');
		}
		elseif (getenv('HTTP_FORWARDED_FOR')) {
			$ip = getenv('HTTP_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_FORWARDED')) {
			$ip = getenv('HTTP_FORWARDED');
		}
		else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}
function download_file($id,$tableid,$nametable,$file,$sorce){
      $query="select * from $nametable where $tableid=$id";
      $result=mysql_query($query) or die ("Bad Query<br>".$query);  
      $row=mysql_fetch_array($result);
	  $filename=$row[$file];
          //  $filename = realpath($filename);
       
            $file_extension = strtolower(substr(strrchr($filename,"."),1));
			
			switch ($file_extension) {
                case "pdf": $ctype="application/pdf"; break;
                case "exe": $ctype="application/octet-stream"; break;
                case "zip": $ctype="application/zip"; break;
                case "doc": $ctype="application/msword"; break;
                case "doc": case "docx":
                case "doc": $ctype="application/msword"; break;
			    case "xls": $ctype="application/vnd.ms-excel"; break;
                case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
                case "gif": $ctype="image/gif"; break;
                case "png": $ctype="image/png"; break;
                case "jpe": case "jpeg":
                case "jpg": $ctype="image/jpg"; break;
                default: $ctype="application/force-download";
            }
			

			header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: private",false);
            header("Content-Type: $ctype");
            header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".@filesize('mirzaeiKeyvan/upfiles/'.$filename));
            set_time_limit(0);
            @readfile("$sorce/$filename") or die("File not found.");
//download			
	  }
// send mail
function send_mail($user_id, $subject, $message){
	$db = con();
	$from = returnConfigPortal('title');
	$email = 'info@pishsakhteh.com';
	$sql = $db->query("select email from u_users where ID = '".(int)$user_id."'");
	$res = $db->fetchNextArray($sql);
	$to = $res['email'];
	$header  = "MIME-Version: 1.0\r\n";
	$header .= "Content-type: text/html; charset=utf-8\r\n";
	$header .= "To: ".$to."\r\n";
	$header .= "From: ".$from." <".$email.">\r\n";
	$header .= "Cc: \r\n";
	$message .='<br><span style="font-family:Tahoma, Arial; font-size:12px;">'.returnConfigPortal('title').'<br />'.date("l d F Y").'</span>';
	@mail($to, $subject, $message, $header);
	
}
//name user
function name_user($ID){
	global $db;
      $query="select * from u_users where ID='".(int)$ID."'";
      $result=$db->query($query) ;  
      $row=$db->fetchNextArray($result);
	  return $row['name'] .' ' .$row['lastName'];
}
//mobile user
function mobile_user($ID){
	global $db;
      $query="select * from u_users where ID='".(int)$ID."'";
      $result=$db->query($query) ;  
      $row=$db->fetchNextArray($result);
	  return $row['mobile'];
}
//====================================================
	function get_years ($selected, $name = 'year') {
		$from = 1399;
		$to = 1300;
       // if ($name == '') $name = 'year';
        
		$text = '<select name="'.$name.'">';
        
		for ($i=$from;$i>=$to; $i--) {
		
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			if (($i == 1300) && ($selected == '')) $selected = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_monthes ($selected, $name = 'month') {
		$from = 1;
		$to = 12;
		$text = '<select name="'.$name.'">';
		for ($i=$from;$i<=$to; $i++) {
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_days ($selected, $name = 'day') {
		$from = 1;
		$to = 31;
		$text = '<select name="'.$name.'">';
		for ($i=$from;$i<=$to; $i++) {
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_hours ($selected, $name = 'hour') {
		$from = 0;
		$to = 23;
		$text = '<select name="'.$name.'">';
		for ($i=$from;$i<=$to; $i++) {
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_minutes ($selected, $name = 'minute') {
		$from = 0;
		$to = 59;
		$text = '<select name="'.$name.'">';
		for ($i=$from;$i<=$to; $i++) {
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_credit_amount($user_id){
		$db = con();
		global $credit_amount;
		$sql = $db->query("select $credit_amount from credit where user_id='".(int)$user_id."'");
		$res = $db->fetchNextArray($sql);
		return $res[$credit_amount];
	}
//====================================================
	function decrease_from_credit_amount($user_id, $amount) {
		$db = con();
		global $credit_amount;
		$sql = $db->execute("update credit SET amount = amount - ".(int)$amount." where user_id='".(int)$user_id."'");
	return true;
	}
//====================================================
	function increase_credit_amount($user_id, $amount) {
		$db = con();
		global $credit_amount;
		$sql = $db->execute("update credit SET $credit_amount = $credit_amount + ".(int)$amount." where user_id='".(int)$user_id."'");
	return true;
	}
//====================================================
	function get_parent_id ($parent_name) {
		$db = con();
		$sql = $db->query("SELECT ID FROM u_users WHERE userName = '".$db->safe_string($parent_name)."'");
		$res = $db->fetchNextArray($sql);
	return $res['ID'];
	}
	
//====================================================
function get_user_name ($userID) {
		$db = con();
        $query="select userName from u_users where ID='".(int)$userID."'";
        $result=$db->query($query);  
        $row=$db->fetchNextArray($result);
	return $row['userName'];
}
//====================================================
function get_ID ($userName) {
		$db = con();
        $query="select ID from u_users where userName='".$userName."'";
        $result=$db->query($query);  
        $row=$db->fetchNextArray($result);
	return $row['ID'];
}
//====================================================
	function get_member_days ($userID) {
		$db = con();
		$today = g_days_of_year(date("m"),date("d"),date("Y"));
		$query="select date from u_users where ID='".(int)$userID."'";
        $result=$db->query($query) ;  
        $row=$db->fetchNextArray($result);
		$member_date = explode("-",$row['date']);
		$first_day = g_days_of_year($member_date[1], $member_date[2], $member_date[0]);
		if($member_date[0] == date("Y")){
			$days = $today - $first_day;
		}elseif((date("Y") - $member_date[0]) == 1){
			$days = ($today + (365 - $first_day));
		}
		return $days;
	}
//====================================================
	function get_member_name ($userID) {
		$db = con();
        $query="select name_lastname from u_users where ID='".(int)$userID."'";
        $result=$db->query($query);  
        $row=$db->fetchNextArray($result);
	return $row['name_lastname'];
	}
//====================================================
	function get_user_level ($userID) {
		$db = con();
        $query="select status from u_users where ID='".(int)$userID."'";
        $result=$db->query($query);  
        $row=$db->fetchNextArray($result);
	return (int)$row['status'];
	}
//===========================================
	function title_news($ID){
	
      $query="select * from subcat_news where scid='".$ID."'";
      $result=mysql_query($query) ;  
      $row=mysql_fetch_array($result);
	  return $row['title'];
}
//===========================================
function get_user_name_lastname($userID) {
    $query="select * from u_users where ID='".(int)$userID."'";
    $result=mysql_query($query);  
    $row=mysql_fetch_array($result);
	return $row['name'] . $row['lastName'];
}
//====================================================
function get_bank_amount($user_id){
		$db = con();
		global $credit_amount;
		$sql = $db->query("select amount from bank where user_id='".(int)$user_id."'");
		$res = $db->fetchNextArray($sql);
	return $res['amount'];
}
//====================================================
function get_bank_x_amount($user_id){
		$db = con();
		global $credit_amount;
		$sql = $db->query("select amount_x from bank where user_id='".(int)$user_id."'");
		$res = $db->fetchNextArray($sql);
	return $res['amount_x'];
}	
//====================================================

	function decrease_from_bank_amount($user_id, $amount) {
		$db = con();
		global $credit_amount;
		$sql = $db->execute("update bank SET amount = amount - ".(int)$amount." where user_id='".(int)$user_id."'");
	return true;
	}
//====================================================
	function increase_bank_amount($user_id, $amount) {
		$db = con();
		global $credit_amount;
		$sql = $db->execute("update bank SET amount = amount + ".(int)$amount." ,amount_x =amount_x +".(int)$amount." where user_id='".(int)$user_id."'");
	return true;
	}
//=======================================================
	function get_last_seven_days (){
		for($i = 1; $i <= 6; $i++){
				$date['year'][$i] = (int)date("Y", mktime(0, 0, 0, date("m")  , date("d")-$i, date("Y")));
				$date['month'][$i] = (int)date("m", mktime(0, 0, 0, date("m")  , date("d")-$i, date("Y")));
				$date['day'][$i] = (int)date("d", mktime(0, 0, 0, date("m")  , date("d")-$i, date("Y")));
		}
	return $date;
	}
//=======================================================
	function get_unvisited_settles(){
		$db = con();
		$sql = $db->query("SELECT * FROM settle WHERE visited = '0' AND payer_id != 0");
		$num = $db->numRows($sql);
	return $num;
	}
//=======================================================
	function get_unvisited_settles2(){
		$db = con();
		$sql = $db->query("SELECT * FROM settle WHERE visited = '0' AND payer_id = 0");
		$num = $db->numRows($sql);
	return $num;
	}
//=======================================================
	function get_unvisited_settles3(){
		$db = con();
		$sql = $db->query("SELECT * FROM epay WHERE visited = '0' AND pay_from != ''");
		$num = $db->numRows($sql);
	return $num;
	}
//=======================================================
	function get_unvisited_settles4(){
		$db = con();
		$sql = $db->query("SELECT * FROM pEpay WHERE visited = '0' AND paymentType = 2");
		$num = $db->numRows($sql);
	return $num;
	}
//=======================================================
	function get_unvisited_settles5(){
		$db = con();
		$sql = $db->query("SELECT * FROM epay_mellat WHERE visited = '0' AND manualName <> ''");
		$num = $db->numRows($sql);
	return $num;
	}	
//=======================================================
	function get_unvisited_requests(){
		$db = con();
		$sql = $db->query("SELECT * FROM requests WHERE request_status = '0'");
		$num = $db->numRows($sql);
	return $num;
	}

//=======================================================
	function get_unvisited_users(){
		$db = con();
		$sql = $db->query("SELECT * FROM u_users WHERE visited = '0'");
		$num = $db->numRows($sql);
	return $num;
	}
//=======================================================
	function get_unvisited_users_city(){
		$db = con();
		$sql = $db->query("SELECT * FROM sms_city_request WHERE status = '0'");
		$num = $db->numRows($sql);
	return $num;
	}
//==============================================
	function sql2XLS($fileName, $tableName, $fields, $names, $whereClaus = '', $orderBy = '', $limit = ''){
		$db =con();
		$xl = new xls();
		$selects = "";
		$selectNum = count($fields);
		$i = 1;
		foreach($fields as $field){
			$selects .= "$field AS ".$names[$i];
			if($i < $selectNum){
				$selects .= ", ";
			}
			$i++;
		}
		$sql = $db->query("SELECT $selects FROM $tableName $whereClaus $limit");
		foreach($names as $name => $value){
			$xl->add_cell("$name:1", $value);
		}
		$j = 2;
		while($res = $db->fetchNextArray($sql)){
			foreach($names as $name => $value){
				$xl->add_cell("$name:$j",$res [$value]);
			}
			$j++;
		}
		$xl->execute("$fileName.xls");
	}
//==================================================

	function getDiff ($a, $b) {
		if($a >= $b) {
			if(($a - $b) < 10) {
				return true;
			}else{
				return false;
			}
		}elseif($a < $b) {
			if(($b - $a) < 10) {
				return true;
			}else{
				return false;
			}
		}
	}
//====================================================
	function get_credit_all_users(){
		$db = con();
		$amount=0;
		global $credit_amount;
		$sql = $db->query("select * from credit ");
		while($res = $db->fetchNextArray($sql)){
			$amount = $amount+$res[$credit_amount];
		}
		
			return $amount;
	}

//========================================
function return_epay_insert(){
		$db = con();
		global $credit_amount;
		$sql =$db->query("select * from settle WHERE state = 2 ");
		$amount=0;
		while($res =  $db->fetchNextArray($sql)){
			$amount=$amount+$res[$credit_amount];
		}
		return $amount;
}

//========================================
function return_epay_insert_mellat(){
		$db = con();
		$sql =$db->query("SELECT * FROM epay_mellat WHERE manualName <> '' AND statusSettle = 1");
		$pay_value=0;
		while($res =  $db->fetchNextArray($sql)){
			$pay_value=$pay_value+$res['pay_value'];
		}
		return $pay_value;
}
//========================================
function return_epay_insert_pasargad(){
		$db = con();
		global $credit_amount;
		$sql =$db->query("SELECT * FROM pEpay WHERE paymentType = 2 AND status = 1");
		$amount=0;
		while($res =  $db->fetchNextArray($sql)){
			$amount=$amount+$res[$credit_amount];
		}
		return $amount;
}
//=================
function get_unread_contacts(){
		$db = con();
		$sql = $db->query("SELECT * FROM contact WHERE status =  '0'");
		$num = $db->numRows($sql);
		
		$sql2 = $db->query("SELECT * FROM messages_user WHERE dell_r =0 and r_m_user = 0");
		$num2 = $db->numRows($sql2);		
		
	return $num + $num2;
}
//================================
function num_languages(){
     $db = con();
		$sql = $db -> query("select * from languages order by languagesID desc");
		$num = $db->numRows($sql);
		return $num;
}
//=================================
function getProvinceName($ProvinceID){
	$db = con();
	$query=$db->query("select ProvinceName from province where ProvinceID ='".$ProvinceID."'");	
	$row=$db->fetchNextArray($query);
	return $row['ProvinceName'];
}
//=================================
function getCityName($CityID){
	$db = con();
	$query=$db->query("select CityName from city where CityID ='".$CityID."'");	
	$row=$db->fetchNextArray($query);
	return $row['CityName'];
}
//=================================
function getTypeusecatName($catID){
	$db = con();
	$query=$db->query("select nameCat from typeusecat where catID='".$catID."'");	
	$row=$db->fetchNextArray($query);
	return $row['nameCat'];
}
//=================================
function categoryNameLa($cat,$la){
	$db = con();
	$query=$db->query("select categoriesName from categoriesdescription where categoriesID='".$cat."' and languagesID = '".$la."'");	
	$row=$db->fetchNextArray($query);
	return $row['categoriesName'];
}
//=================================
function categoryDatailLa($cat,$la){
	$db = con();
	$query=$db->query("select categoriesDatail from categoriesdescription where categoriesID='".$cat."' and languagesID = '".$la."'");	
	$row=$db->fetchNextArray($query);
	return $row['categoriesDatail'];
}
//=================================
function products_nameNameLa($cat,$la){
	$db = con();
	$query=$db->query("select products_name from products_description where products_id='".$cat."' and language_id = '".$la."'");	
	$row=$db->fetchNextArray($query);
	return $row['products_name'];
}
//=================================
function products_descriptionLa($cat,$la){
	$db = con();
	$query=$db->query("select products_description from products_description where products_id='".$cat."' and language_id = '".$la."'");	
	$row=$db->fetchNextArray($query);
	return $row['products_description'];
}
//=================================
function getParenCategory($cat){
	$db = con();
	$query=$db->query("select * from categories where categoriesID='".$cat."' ");
		$row=$db->fetchNextArray($query);
	     return $row['parentID'];
}
//=================================
function parenCategory($cat){
	$db = con();
	$query=$db->query("select * from categories where categoriesStatus=1 and parentID=0");
	$select='<select name="categoriesID">';
		$select .='<option value="0">گروه اصلی</option>';
		while($row=$db->fetchNextArray($query)){
			if($cat==$row['categoriesID']){$selected='selected="selected"';}else{$selected='';}
			
		    $select .='<option '.$selected.'  value="'.$row['categoriesID'].'">'.categoryName($row['categoriesID']).'</option>';
		
		}
	$select .='</select>';

	
	return $select;
}
//=================================
function productName($products_id){
	$db = con();
	$query=$db->query("select products_name from products_description where products_id='".$products_id."' ");	
	$row=$db->fetchNextArray($query);
	return $row['products_name'];
}
//=================================
function categoryName($cat){
	$db = con();
	$query=$db->query("select * from categoriesdescription where categoriesID='".$cat."' and languagesID = 1");	
	$row=$db->fetchNextArray($query);
	return $row['categoriesName'];
}
//==================================
function sendSms($urltopost,$user,$pass,$msgBody,$recNums,$smsid=0){
	$db = con();
		$query=$db->query("select * from configuration where id =1");
			$res=$db->fetchNextArray($query);
			$urltopost = $urltopost;
			$fullmsg = $msgBody;
			$datatopost = array (
			"login" => 'motormarket',
			"pass" =>'chitasoft',
			"msgBody" => $fullmsg,
			"recNums" => $recNums,
			"senderNum" => '9830004526210516',
			"getsmsid" => $smsid,
			"send" => 'submit'
			);
		$ch = curl_init ();
		curl_setopt($ch, CURLOPT_URL, "http://www.chitasms.com/sendByPost.php");
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
		$returndata = curl_exec ($ch);
}
//=================================
function returnConfig($fild){
	$db = con();
	$query=$db->query("select * from configuration where id=1");
	$res=$db->fetchNextArray($query);
	return $res[$fild];
}
//==================================
function stateNaja($userID){
	$db = con();
	$query=$db->query("select * from u_users where ID='".$userID."'");	
	$res=$db->fetchNextArray($query);
	if($res['statusNaja']==0){
		return 'تایید نشده';
	}elseif($res['statusNaja']==1){
		return 'تایید شده';	
	}
}

//==================================
function stateCompany($userID){
	$db = con();
	$query=$db->query("select * from u_users where ID='".$userID."'");	
	$res=$db->fetchNextArray($query);
	if($res['statusCompany']==0){
		return 'تایید نشده';
	}elseif($res['statusCompany']==1){
		return 'تایید شده';	
	}
}
//=================================
function smsInsert($userID,$from_num,$to_num,$text_message ,$date=''){
	$db = con();
	$db->execute("INSERT INTO sms_records SET user_id = '".(int)$userID."',
											  from_num = '".$from_num."',
											  to_num = '".$to_num."',
											  text_message='".$text_message."' ,
											  date = now()");
}
//==================================
function return_available($userID,$fild){
	$db = con();
	$sql=$db->query("select * from adminavilable where userID='".$userID."' ");
	$res=$db->fetchNextArray($sql);
	return $res[$fild];
}
//==================================
function getCountParentUser($userID , $fild , $status){
	$db = con();
	$sql=$db->query("select * from u_users where parent_id ='".$userID."' AND $fild = $status" );
	$res=$db->fetchNextArray($sql);
	$num=$db->numRows($sql);
	return $num;
}
//==================================getSoudCat
function getSoudCat($productCat){
	$db = con();
	$sql=$db->query("select * from categories where categoriesID  ='".$productCat."'");
	$res=$db->fetchNextArray($sql);
	$soudCat = $res['soudCat'];
	if($res['parentID']==0){
		return $soudCat;
	}else{
		getSoudCat($res['parentID']);
	}
}
//==================================returnSoudCat
function returnSoudCat($productID){
	$db = con();
	$sql=$db->query("select productCat from products where productID ='".$productID."'");
	$res=$db->fetchNextArray($sql);
	$productCat = $res['productCat'];
	$soudCat=getSoudCat($productCat);
	return $soudCat;
}
//==================================returnSoudNemayandeh
function returnSoudNemayandeh($userID,$productID){
	$db = con();
	$soudCat = returnSoudCat($productID);
	$soudPortal = returnConfigPortal('soudPortal');
	
	$sql3=$db->query("select * from u_users  where ID  ='".$userID."'");
	$res3=$db->fetchNextArray($sql3);
	$soudUser = $res3['soud'];
	
	$allSoud=$soudUser + $soudPortal + $soudCat;
	return $allSoud;
}
//==================================getReturnNemayandehID
function getReturnNemayandehID($userID){
	$db = con();
	$query=$db->query("select * from u_users where ID='".$userID."'");	
	$res=$db->fetchNextArray($query);
	if($res['parent_id']){
		return $res['parent_id'];
	}else{
		return 0;	
	}
}
//==================================
function getReturnNemayandeh($userID){
	$db = con();
	$query=$db->query("select * from u_users where ID='".$userID."'");	
	$res=$db->fetchNextArray($query);
	if($res['parent_id']){
		return 'کد : ' .$res['parent_id'] .' | نام : '.name_user($res['parent_id']) ;
	}else{
		return 'شرکت';	
	}
}
//=================================
function detailOid($orderId){
	$db=con();
	$query=$db->query("select * from orders_products where orders_id='".$orderId."' ");
		while($row=$db->fetchNextArray($query)){
		     $product .= $row['products_name'].'<br />';	
		}
	return $product;	
			
}
//================================================
function get_status_orders($status){
			if($status == 1){$Pstatus = '<font color="#FF0000">لغو </font>';}
			if($status == 2){$Pstatus = '<font color="#FF9900">در انتظار</font>';}
			if($status == 3){$Pstatus = '<font color="#663300">در حال پردازش </font>';}
			if($status == 5){$Pstatus = '<font color="#006600">ارسال شده </font>';}
			if($status == 6){$Pstatus = '<font color="#006600">تحویل شده </b></font>';}
return $Pstatus;
}
//================================================
function planName($plan){
			if($plan == 1){$Pplan = '<font color="#999999"><b> برنزه </b></font>';}
			if($plan == 2){$Pplan = '<font color="#C0C0C0"><b> نقره ای </b></font>';}
			if($plan == 3){$Pplan = '<font color="#FF9900"><b> طلایی </b></font>';}
			if($plan == 0){$Pplan = '<font color="#006600">رایگان  </font>';}
return $Pplan;
}
//==============================
function stateEpaye($orderID){
		$db=con();
		$sql =$db->query("select * from settle where order_id='".$orderID."' ");
        $row = $db->fetchNextArray($sql);
		$num = mysql_num_rows($sql);
		if($num){
			 if($row['state']=='2') {$type_taead= 'پرداخت شده';}
			 else{$type_taead ='پرداخت تایید نشده ';}
		}else{
			$type_taead ='<a style="color:#000" href="epay.php?orderID='.$orderID.'">پرداخت نشده ' . ' <img src="images/dolar.gif" alt="پرداخت هزینه سفارش" title="پرداخت هزینه سفارش" ></a>';
		}
	return $type_taead;
}
//==============================
function stateEpayFactorّّّّ($orderID){
		$db=con();
		$sql =$db->query("select * from orders where order_id ='".$orderID."' ");
        $row = $db->fetchNextArray($sql);
		$num = $db->fetchNextArray($sql);
         if($row['payment']=='1'){
			 $type_taead= 'پرداخت شده';
		}else{
			$type_taead ='پرداخت نشده ';
		}
	return $type_taead;
}
//====================================
function returnPriceMojavez($productID,$countProduct){
$db=con();
	$query=$db->query("select * from products where productID='".$productID."'");	
	$res=$db->fetchNextArray($query);
	$License=$res['License'];
	$countLicense=$res['countLicense'];
	$priceLicense=$res['priceLicense'];								
	if($License==1){
		if($countProduct <= $countLicense){
			$FpriceLicense=$priceLicense;
		}else{
			$countMojavez = $countProduct / $countLicense;
			$Rcount = $countProduct % $countLicense;
			if($Rcount >0){
				$FcountMojavez=1+ (int)$countMojavez;
			}else{
				$FcountMojavez= (int)$countMojavez;
			}
			$FpriceLicense=(int)$FcountMojavez * $priceLicense;
		}
	}else{
		$FpriceLicense=0;	
	}
	return $FpriceLicense;
}
//=================================
function returnConfigPortal($fild){
	$db = con();
	$query=$db->query("select * from chitaportal where portalID=1");
	$res=$db->fetchNextArray($query);
	return $res[$fild];
}
//=====================================
function orderName($oID){
	$db=con();
	$sql=$db->query("select * from orders where order_id = '".$oID."'");
	$res=$db->fetchNextArray($sql);
	return name_user($res['userID']);
}
//================================================
function get_status_payment($status){
			if($status == 1){$Pstatus = '<font color="#FF9900"> پرداخت آنلاین</font>';}
			elseif($status == 2){$Pstatus = '<font color="#009900"> واریز به حساب</font>';}
			elseif($status == 3){$Pstatus = '<font color="#FF0000"> پرداخت در محل </font>';}
			elseif($status == 4){$Pstatus = '<font color="#006600">پرداخت در محل </font>';}
			else{$Pstatus = '<font color="#000">پرداخت نشده</font>';}
return $Pstatus;
}
//---------------------------------------------------------------------------------------
function getExpireDate ($aFromDate,$aAddDays){
	// aFromDate on the format YYmd, like 20040212
	$from_year=substr($aFromDate,0,4);
	$from_month=substr($aFromDate,4,2);
	$from_day=substr($aFromDate,6,2);
	$expire_date_conv = formatDate(date ("Ymd", mktime (date("H"),date("i"),date("s"),$from_month,$from_day+$aAddDays,$from_year)));  
	return $expire_date_conv;
}
//----------------------------------------------------------------------------------------
function formatDate($aDate){
	// aDate should have Ymd format
	 $date_format="y-m-d";
	$year=substr($aDate,0,4);
	$month=substr($aDate,4,2);
	$day=substr($aDate,6,2);
	// Date_format grabbed from settings...
	$date_added_1 = $date_format;
	$date_added_1 = ereg_replace("d", "$day", $date_added_1);
	$date_added_1 = ereg_replace("m", "$month", $date_added_1);
	$date_added_1 = ereg_replace("y", "$year", $date_added_1);
	$sitedate1 = $date_added_1;
	return $sitedate1;
}
//=====================================
function statusOrders($status){
	$db=con();
	$sql=$db->query("select * from orders where status = '".$status."'");
	$num=$db->numRows($sql);
	return $num;
}
//=====================================
function statusNewEpay(){
	$db=con();
	$sql=$db->query("select * from settle where visited  = 0");
	$num=$db->numRows($sql);
	return $num;
}
//=====================================
function statusNewEmploy(){
	$db=con();
	$sql=$db->query("select * from employ where visited  = 0");
	$num=$db->numRows($sql);
	return $num;
}
//=====================================
function statusNewPorsant(){
	$db=con();
	$sql=$db->query("select * from requestcommission where visited  = 0");
	$num=$db->numRows($sql);
	return $num;
}
//=====================================
function statusNewContact(){
	$db=con();
	$sql=$db->query("select * from contact where state  = 0");
	$num=$db->numRows($sql);
	return $num;
}
//=====================================
function returnCountUser($userGroup,$fild,$status){
	$db=con();
	$sql=$db->query("select * from u_users where userGroup  = '".$userGroup."' AND $fild=$status  ");
	$num=$db->numRows($sql);
	return $num;
}
//-----------------------------------------
function return_install_product($productID){
		global $db;
		$sql = $db->query("SELECT products_price2 from products WHERE productID='".$productID."'");
		$res = $db->fetchNextArray($sql);
		$products_price2=$res['products_price2'];
		return $products_price2;
}
//========================================================
function count_product($valid){
	$sql=mysql_query("select * from products where valid ='".$valid."' ");
	$num=mysql_num_rows($sql);
	return $num;
}
//========================================================
function count_ad($valid){
	$sql=mysql_query("select * from ad where valid ='".$valid."' ");
	$num=mysql_num_rows($sql);
	return $num;
}
//========================================================
function count_ad_tamdid($valid){
	$sql=mysql_query("select * from ad where tamdid ='1' ");
	$num=mysql_num_rows($sql);
	return $num;
}
//========================CalcTotalCost
function CalcTotalCost($star,$expire_days){
	if($expier_days=='30'){
		$pric=$star * returnConfigAd('ad2_amount_1') * 30;
	}elseif($expire_days=='90'){
		$pric=$star * returnConfigAd('ad2_amount_2') * 90;
	}elseif($expire_days=='180'){
		$pric=$star * returnConfigAd('ad2_amount_3') * 180;
	}elseif($expire_days=='365'){
		$pric=$star * returnConfigAd('ad2_amount_12') * 365;
	}
	return $pric;
}
//=================================
function returnConfigAd($fild){
	$db = con();
	$query=$db->query("select * from config where config_id =1");
	$res=$db->fetchNextArray($query);
	return $res[$fild];
}
//=================================
function typeEpay($fild){
	$db = con();
	$query=$db->query("select * from config where config_id =1");
	$res=$db->fetchNextArray($query);
	return $res[$fild];
}
//==================================
function seourl($kind,$id){
	$db = con();
	// we have two different kind of argomans in this function. 
	if($kind=='post'){
		
	 $sql = "SELECT * FROM parts WHERE id = '".$id."'";
			  $query = $db->query($sql) ;
			  $array=$db->fetchNextArray($query);
			  if($array['category']==8){
			 	  return 'blog/'.urlencode($array['slug']); 
			  }
			  elseif($array['category']==9){
			      return 'خدمات/'.urlencode($array['slug']);
				  }
			  else{
				  return urlencode($array['slug']); 
				  }
			  }
				
			
	if($kind=='category'){
	 $sql = "SELECT * FROM categories WHERE id = '".$id."'";
			  $query = $db->query($sql) ;
			  $array=$db->fetchNextArray($query);
			  return 'category/'.urlencode($array['slug']);}


}
function adsprice($kind,$userid){
	// kind 0 = agahi mamooli
	// kind 1 = agahi vizhe
	$db = con();
	global $globalConfig;
    $eads = $db->query("SELECT * FROM configuration WHERE id = '1'");
	$ads = $db->fetchNextArray($eads);
    $euser = $db->query("SELECT * FROM u_users WHERE ID = '".$userid."'");
	$user = $db->fetchNextArray($euser);
		if($kind=='0'){
			if($user['agent']=='1'){
				return $ads['price_normal_agent'];
				}else{
					return $ads['price_normal'];
					}
			}else{
			if($user['agent']=='1'){
				return $ads['price_special_agent'];
				}else{
					return $ads['price_special'];
					}
				}
    
	};
include ("include/function/chitasoft_function.php");
include ("include/function/sms_function.php");
?>