<?php
error_reporting(0);
 extract($_REQUEST);
#pagination
function pagination($tbl_name,$fields,$where='',$orderby='',$page_url,$pagesize,$page_no)
{
	if($where)$where=" WHERE ".$where;
	if($orderby)$orderby=" ORDER BY ".$orderby;
	$sql1="SELECT ".$fields." FROM ".$tbl_name.$where.$orderby;
	$rowsperpage = $pagesize;
	$website = $page_url; 
	$pagination = new CSSPagination($sql1, $rowsperpage, $website); 
	$pagination->setPage($page_no); 
	$qsql1 = @mysql_query($sql1) or die("failed");
	$RecordCount = mysql_num_rows($qsql1);
	$sql2 = "select ".$fields." FROM ".$tbl_name.$where.$orderby." LIMIT ".$pagination->getLimit() . ", ". $rowsperpage; 
	$result_query = @mysql_query($sql2);
	$page = $pagination->showPage();
	$resultArr = array();
	if($RecordCount>1)
	{
		while($res = mysql_fetch_assoc($result_query))
		{
			$resultArr[] = $res;
		}
	}
	else if($RecordCount==1)
	{
		$res = mysql_fetch_assoc($result_query);
		$resultArr[] = $res;
	}
	$array_res	=	array('Query'=>$resultArr,'page'=>$page,'nr'=>$RecordCount);
	return $array_res;
}
function paginationQry($sql1,$page_url,$pagesize,$page_no)
{
	$rowsperpage = $pagesize;
	$website = $page_url; 
	$pagination = new CSSPagination($sql1, $rowsperpage, $website); 
	$pagination->setPage($page_no); 
	$qsql1 = @mysql_query($sql1) or die("failed");
	$RecordCount = mysql_num_rows($qsql1);
	$sql2 = $sql1." LIMIT ".$pagination->getLimit() . ", ". $rowsperpage; 
	$result_query = @mysql_query($sql2);
	$page = $pagination->showPage();
	$resultArr = array();
	if($RecordCount>1)
	{
		while($res = mysql_fetch_assoc($result_query))
		{
			$resultArr[] = $res;
		}
	}
	else if($RecordCount==1)
	{
		$res = mysql_fetch_assoc($result_query);
		$resultArr[] = $res;
	}
	$array_res	=	array('Query'=>$resultArr,'page'=>$page,'nr'=>$RecordCount);
	return $array_res;
}
#pagination for array
function pagination_array($array, $page = 1, $link_prefix = false, $link_suffix = false, $limit_page = 20, $limit_number = 10)
{
	if (empty($page) or !$limit_page) $page = 1;
	$num_rows = count($array);
	if (!$num_rows or $limit_page >= $num_rows) return false;
	$num_pages = ceil($num_rows / $limit_page);
	$page_offset = ($page - 1) * $limit_page;
	//Calculating the first number to show.
	if ($limit_number)
	{
		$limit_number_start = $page - ceil($limit_number / 2);
		$limit_number_end = ceil($page + $limit_number / 2) - 1;
		if ($limit_number_start < 1) $limit_number_start = 1;
		//In case if the current page is at the beginning.
		$dif = ($limit_number_end - $limit_number_start);
		if ($dif < $limit_number) $limit_number_end = $limit_number_end + ($limit_number - ($dif + 1));
		if ($limit_number_end > $num_pages) $limit_number_end = $num_pages;
		//In case if the current page is at the ending.
		$dif = ($limit_number_end - $limit_number_start);
		if ($limit_number_start < 1) $limit_number_start = 1;
	}
	else
	{
		$limit_number_start = 1;
		$limit_number_end = $num_pages;
	}
	//Generating page links.
	for ($i = $limit_number_start; $i <= $limit_number_end; $i++)
	{
		$page_cur = "<a href='$link_prefix$i$link_suffix'>$i</a>";
		if ($page == $i) $page_cur = "<b>$i</b>";
		else $page_cur = "<a href='$link_prefix$i$link_suffix'>$i</a>";
		$panel .= " <span>$page_cur</span>";
	}
	$panel = trim($panel);
	//Navigation arrows.
	if ($limit_number_start > 1) $panel = "<b><a href='$link_prefix".(1)."$link_suffix'>&lt;&lt;</a>  <a href='$link_prefix".($page - 1)."$link_suffix'>&lt;</a></b> $panel";
	if ($limit_number_end < $num_pages) $panel = "$panel <b><a href='$link_prefix".($page + 1)."$link_suffix'>&gt;</a> <a href='$link_prefix$num_pages$link_suffix'>&gt;&gt;</a></b>";
	$output['panel'] = $panel; //Panel HTML source.
	$output['offset'] = $page_offset; //Current page number.
	$output['limit'] = $limit_page; //Number of resuts per page.
	$output['array'] = array_slice($array, $page_offset, $limit_page, true); //Array of current page results.
	
	return $output;
}
#position add
function pos_add($table_name,$field_name,$catpos,$id,$where='')
{
	if($where)$where = "WHERE ".$where;
	$selectSql = mysql_query("SELECT * FROM ".$table_name." ".$where." ORDER BY ".$field_name." ASC");
	$rows = mysql_num_rows($selectSql);
	
	if($catpos!="Last")
	{
		$limit=$catpos-1;//0
		
		$squery = mysql_query("SELECT * FROM ".$table_name." ".$where." ORDER BY ".$field_name." ASC LIMIT $limit,$rows");
		while($resval=mysql_fetch_object($squery))
		{
			$inc = $resval->$field_name+1;
			$update=mysql_query("UPDATE ".$table_name." set ".$field_name."='$inc' WHERE ".$id."='".$resval->$id."'");
		}
		
		$fabric_pos = $catpos;
	}
	else
	{
		$fabric_pos=$rows+1;
	}
	return $fabric_pos;
}
#position update
function pos_update($table_name,$field_name,$catpos,$resultpos,$id,$where='')
{
	if($where)$where = " WHERE ".$where;
	if($resultpos<$catpos)
	{
		if($resultpos==1)
		{
			$limit=0;
			$max=($catpos-$resultpos)+1;
		}
		else
		{
			$limit=$resultpos;//4
			$max=($catpos-$resultpos);//5
		}
		
		$squery = mysql_query("SELECT * FROM ".$table_name.$where." ORDER BY ".$field_name." LIMIT $limit,$max");
		while($res=mysql_fetch_assoc($squery))
		{
			$inc=$res[$field_name]-1;
			$update = mysql_query("UPDATE ".$table_name." SET ".$field_name."='$inc' WHERE ".$id."='".$res[$id]."'");
		}
		
	}
	else
	{
		$limit=$catpos-1;//7
		$max=($resultpos-$catpos);//1
		$squery = mysql_query("SELECT * FROM ".$table_name.$where." ORDER BY ".$field_name." LIMIT $limit,$max");
		//echo "SELECT * FROM ".$table_name.$where." ORDER BY ".$field_name." LIMIT $limit,$max"."<br>";
		while($res=mysql_fetch_assoc($squery))
		{
			$inc=$res[$field_name]+1;
			//echo "UPDATE ".$table_name." SET ".$field_name."='$inc' WHERE ".$id."='".$res[$id]."'"."<br>";
			$update =  mysql_query("UPDATE ".$table_name." SET ".$field_name."='$inc' WHERE ".$id."='".$res[$id]."'");
		}
	}
	return $catpos;
}
#function show position box in insert form
function show_pos($table_name,$field_name,$where='')
{
	if($where)$where=" WHERE ".$where;
	$squery = mysql_query("SELECT ".$field_name." FROM ".$table_name." ".$where." ORDER BY ".$field_name." ASC");
	if(mysql_num_rows($squery)==0)
	{
		echo '<option value="1">1</option>';
	}
	else
	{
		while($res=mysql_fetch_object($squery))
		{
			echo '<option value="'.$res->$field_name.'">'.$res->$field_name.'</option>';	
		}
		echo '<option value="Last">Last</option>';
	}
}
#function show position box in edit form
function show_posupd($table_name,$field_name,$result_pos,$where='')
{
	if($where)$where=" WHERE ".$where;
	$selPos = mysql_query("SELECT ".$field_name." FROM ".$table_name.$where." ORDER BY ".$field_name." ASC");
	if(mysql_num_rows($selPos)>0)
	{
		while($resPos=mysql_fetch_object($selPos))
		{
			echo '<option value="'.$resPos->$field_name.'" '.isselected($resPos->$field_name,$result_pos).'>'.$resPos->$field_name.'</option>';
		}
	}
}
function insert($table,$exist='',$new_field='',$up_folder='')
{
        if($up_folder=="")
        {
            $folder = "upload/";
        }
        else
        {
            $folder = "$up_folder/";
        }
   
   
        $selfield = mysql_query("show columns from $table");
        while($rowfield=@mysql_fetch_assoc($selfield))
        {
            $field[]=$rowfield[Field];
        }
        //print_r($field);
       
        if($exist)
        {
       
            $expexist=explode(",",$exist);
            foreach($expexist as $existvar)
            {
                $existcond.= "$existvar = '".variable($_POST[$existvar])."' and  ";
            }
           
        }
        else
        {
       
            foreach($_POST as $key => $value)
            {
                if(@in_array($key,$field))
                {
                    $existcond.= "$key = '".variable($_POST[$key])."' and ";
                }
           
            }
       
        }
       
	   //	echo $existcond."<br>";
		
        $existcond = substr($existcond,0,strlen($existcond)-5);
		
        //echo $existcond."<br>";
   
        $selexist=mysql_query("select * from $table where $existcond");
		
		//echo "select * from $table where $existcond";
		
        $checkexist = mysql_affected_rows();
       
        if($checkexist <= 0)
        {
       
            foreach($_POST as $key => $value)
            {
                if(@in_array($key,$field))
                {
                    $insertfield.= "$key, ";
                    $insertvalue.= "'".variable($_POST[$key])."', ";
                }
           
            }
           
            if($new_field)
            {
                foreach($new_field as $key => $value)
                {
                    if(@in_array($key,$field))
                    {
                        $insertfield.= "$key, ";
                        $insertvalue.= "'".variable($new_field[$key])."', ";
                    }
               
                }
            }
           
            if($_FILES)
            {
           
                foreach($_FILES as $key => $value)
                {
                    if(@in_array($key,$field) && $_FILES[$key][name])
                    {
                        $insertfield.= "$key, ";
                        $file_name = rand(1,99999).$_FILES[$key][name];
                        $strFileType = strtolower($_FILES[$key]["type"]);
                        $insertvalue.= "'".$file_name."', ";
                        move_uploaded_file($_FILES[$key][tmp_name],$folder.$file_name);
                       
                    }
               
                }
           
            }
            if(@in_array("date",$field))
            {
                $insert_field = $insertfield."date";
                $insert_value = $insertvalue."curdate()";
            }
            else
            {
                $insert_field = substr($insertfield,0,strlen($insertfield)-2);
                $insert_value = substr($insertvalue,0,strlen($insertvalue)-2);
            }
           
            //echo $insert_field,"<br>";
            //echo $insert_value;
            $ins_query = "insert into $table($insert_field) values($insert_value)";
            //echo $ins_query;
            $result = mysql_query($ins_query);
           
            if(mysql_error())
            {
                echo mysql_error(),"<br>",$ins_query;
            }
           
            $ar = mysql_affected_rows();
            $insert_id = mysql_insert_id();
           
            return array(ar=>$ar,id=>$insert_id);
       
        }
        else
        {
            //echo "Already Exist";
            return array(exist=>'1');
        }
   
}
function update($table,$upcond,$new_field='',$up_folder='',$checkbox='')
{
   
        if($up_folder=="")
        {
            $folder = "upload/";
        }
        else
        {
            $folder = "$up_folder/";
        }
   
   
        $selfield = mysql_query("show columns from $table");
		
        while($rowfield=@mysql_fetch_assoc($selfield))
        {
            $field[]=$rowfield[Field];
        }
        //print_r($field);
      
            foreach($_POST as $key => $value)
            {
                if(@in_array($key,$field))
                {
                    $updatefield.= "$key = "."'".variable($_POST[$key])."', ";
                }
           
            }
           
            if($new_field)
            {
                foreach($new_field as $key => $value)
                {
                    if(@in_array($key,$field))
                    {
                        $updatefield.= "$key = "."'".variable($new_field[$key])."', ";
                    }
               
                }
            }
           
            if($_FILES)
            {
           
                foreach($_FILES as $key => $value)
                {
                    if(@in_array($key,$field) && $_FILES[$key][name])
                    {
                        $file_name = rand(1,99999).$_FILES[$key][name];
                        $updatefield.= "$key = "."'".$file_name."', ";
                        move_uploaded_file($_FILES[$key][tmp_name],$folder.$file_name);
                    }
               
                }
           
            }
           
            if($checkbox)
            {
           
                $expcheckbox=explode(",",$checkbox);
                foreach($expcheckbox as $checkboxvar)
                {
                    if(@in_array($checkboxvar,$field) && $_POST[$checkboxvar]=="")
                    {
                        $updatefield.= "$checkboxvar = "."'".$_POST[$checkboxvar]."', ";
                    }
                }
               
            }
           
            $insert_field = substr($updatefield,0,strlen($updatefield)-2);
           
            //echo $insert_field,"<br>";
            $up_query = "update $table set $insert_field where $upcond";
            $result = mysql_query($up_query);
            //echo $up_query."<br>";
           
            if(mysql_error())
            {
                echo mysql_error(),"<br>",$ins_query;
            }
           
            $ar = mysql_affected_rows();
           
            return array(ar=>$ar);
   
}
function select_query($table_name, $field_name, $condition, $limitations='',$print='')
{
	if($field_name == "")
	{
		$field_name = "*";
	}
	
	$selectQ = "select $field_name from $table_name";
	
	if($condition!="")
	{
		$selectQ .= " where $condition";
	}
	if($limitations!="")
	{
		$selectQ .= " limit $limitations";
	}
	if($print){echo $selectQ."<br>";}
   
	$resQuery    =    mysql_query($selectQ);
	
	if(($_SERVER['HTTP_HOST']=="localhost:81" || $_SERVER['HTTP_HOST']=="localhost") && mysql_error())
	{
		echo $sql,"<br>",mysql_error();
	}
   
	$NumRows    =    mysql_num_rows($resQuery);
   
	if($limitations == 1)
	{
		$fetchArray    =    mysql_fetch_assoc($resQuery);
	   
		$fetchArray['nr']    =    $NumRows;
	   
		return $fetchArray;
	}
	else
	{
		while($res = mysql_fetch_assoc($resQuery))
		{
			$resultArr[] = $res;
		}
	
		return array(Query => $resQuery,nr => $NumRows,result=>$resultArr);
	}
	
}
function delete_query($table_name, $condition)
    {
        $deleteQ = "delete from $table_name where $condition";
       
        //echo $deleteQ."<br>";
       
        return mysql_query($deleteQ);
    }
function Execute($sql)
{
	$resQ = mysql_query($sql);
	
	return($resQ);
}
function getRow($sqlRow)
{
	$resArr = mysql_fetch_array(mysql_query($sqlRow));
	
	return $resArr;
}
function variable($vari)
{
//	$varVal = ereg_replace("'","''",stripslashes($vari));
	
	$varVal = mysql_real_escape_string(trim($vari));
	
	return $varVal;
}
function divert($fileName)
{
	echo "<meta http-equiv='refresh' content='0;url=$fileName'>";
	exit();
}
function encrypt($inp,$mod='')
{
	if($mod == 0)
	{
		return base64_encode($inp);
	}
	else
	{
		return base64_decode($inp);
	}
}
function check_session($sess_val,$path='')
{
	if(!$sess_val)
	{	
		divert($file_login);
	}
	
}
function ischecked($val1, $val2)
{
	
	if($val1==$val2)
	{
		return 'checked="checked"';
	}
	else
	{
		return '';
	}
}
/*~~~~~~~~~~CHECKING A CHECKBOX SET OR NOT END~~~~~~~~~~*/
/*~~~~~~~~~~CHECKING A SELECT BOX SELECTED OR NOT START~~~~~~~~~~*/
function isselected($val1, $val2)
{
	
	if($val1==$val2)
	{
		return 'selected="selected"';
	}
	else
	{
		return '';
	}
}	
function parsing_criteria($pairs)
{
	 $criteria = array();
	 if($pairs!='all')
	 {
		$pairs = explode(",",$pairs);
		foreach($pairs as $row)
		{
			$array_row = explode("___",$row);
			//print_r($array_row);
			if($array_row[0])
			{
				$criteria[$array_row[0]] = $array_row[1];
			}
		}
	}
	return $criteria;
}
function show_dashvalues()
{
	#number of products
	$selProduct = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS total_products FROM tbl_product WHERE prod_status='Y'"));
	$ret['total_products'] = $selProduct['total_products'];
	#Total sales
	$selRevenue = mysql_fetch_array(mysql_query("SELECT SUM(sub_total) AS total_revenues FROM tbl_order WHERE (payment='Collected' OR payment='Dispatched') AND status='Y'"));
	$ret['total_revenues'] = $selRevenue['total_revenues'];
	#Total orders WHERE payment='Collected' AND status='Y'
	$selOrders = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS total_orders FROM tbl_order"));
	$ret['total_orders'] = $selOrders['total_orders'];
	#Total customers
	$selUsers = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS total_customers FROM tbl_users WHERE user_status='Y'"));
	$ret['total_customers'] = $selUsers['total_customers'];
	#Today Orders
	$selTodayOrders = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS today_orders FROM tbl_order WHERE dt='".date('Y-m-d')."'"));
	$ret['today_orders'] = $selTodayOrders['today_orders'];
	#current month orders
	$selCmonthOrders = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS cmonth_orders FROM tbl_order WHERE MONTH(dt)=MONTH(CURDATE())"));
	$ret['cmonth_orders'] = $selCmonthOrders['cmonth_orders'];
	#current year orders
	$selCyearOrders = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS cyear_orders FROM tbl_order WHERE YEAR(dt)=YEAR(CURDATE())"));
	$ret['cyear_orders'] = $selCyearOrders['cyear_orders'];
	#Total Tax
	$selTax = mysql_fetch_array(mysql_query("SELECT SUM(tax) AS total_tax FROM tbl_order WHERE (payment='Collected' OR payment='Dispatched') AND status='Y'"));
	$ret['total_tax'] = $selTax['total_tax'];
	#Total Tax
	$selShipping = mysql_fetch_array(mysql_query("SELECT SUM(shipping_cost) AS total_shipping FROM tbl_order WHERE (payment='Collected' OR payment='Dispatched') AND status='Y'"));
	$ret['total_shipping'] = $selShipping['total_shipping'];
	#Total Quantity
	$selQty =mysql_query("SELECT quan FROM tbl_order WHERE (payment='Collected' OR payment='Dispatched') AND status='Y'");
	while($resQty =  mysql_fetch_array($selQty))
	{
		$quan = explode(",",$resQty['quan']);
		
		$val += array_sum($quan);
	}
	$ret['total_qty'] = $val;
	#Processing Orders
	$selProcessing = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS total_processing FROM tbl_order WHERE (payment='Processing') AND status='Y'"));
	$ret['total_processing'] = $selProcessing['total_processing'];
	#Completed Orders
	$selCompleted = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS total_completed FROM tbl_order WHERE (payment='Collected') AND status='Y'"));
	$ret['total_completed'] = $selCompleted['total_completed'];
	#Dispatched Orders
	$selDispatched = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS total_dispatched FROM tbl_order WHERE (payment='Dispatched') AND status='Y'"));
	$ret['total_dispatched'] = $selDispatched['total_dispatched'];
	
	return $ret;
}
#product sale count in order table
function product_salecount($product_id,$arg='')
{
	
	$selProducts = mysql_query("SELECT prod_id,quan,prod_total,pro_usd_uamt FROM tbl_order WHERE FIND_IN_SET(".$product_id.",prod_id)");
	
	if(mysql_num_rows($selProducts))
	{
		while($resProducts = mysql_fetch_assoc($selProducts))
		{
			$selProduct = mysql_fetch_array(mysql_query("SELECT prod_name FROM tbl_product WHERE prod_id='".$product_id."'"));
			$explode_prod = explode(",",$resProducts['prod_id']);
			$prod_index = array_search($product_id,$explode_prod);
			$explode_qty = explode(",",$resProducts['quan']);
			$explode_amt = explode(",",$resProducts['prod_total']);
			$total_qty = $total_qty+$explode_qty[$prod_index];
			$total_amount = $total_amount+$explode_amt[$prod_index];
		}
		if($arg)
		{
			$arr = array('product'=>$selProduct['prod_name'],'qty'=>$total_qty,'amt'=>$total_amount);
		}
		else
		{
			$arr = $total_qty;
		}
	}
	else
	{
		//$arr = array('qty'=>0,'amt'=>0);
	}
	return $arr;
}
function product_salecountall($limit="")
{
	
	$selProducts = mysql_query("SELECT * FROM tbl_product WHERE prod_status='Y'");
	
	$prodArr = array();
	
	if(mysql_num_rows($selProducts)>0)
	{
		$i=0;
		while($res = mysql_fetch_array($selProducts))
		{
			$prod = product_salecount($res['prod_id']);
			
			if($prod)
			{
				$i++;
				if($limit)
				{
					if($i<=$limit)
					{
						
						$pkey = $res['prod_id'];
						$prodArr[$pkey] = $prod;
					}
				}
				else
				{
					$pkey = $res['prod_id'];
					$prodArr[$pkey] = $prod;	
				}
			}
		}
		arsort($prodArr);
		return $prodArr;
	}
}
#newsletter
function send_newsletter($htitle,$sendn_val)
{
	#select settings
		 $selSettings=mysql_query("select * from tbl_settings") or die(mysql_error());
		 $resSettings=mysql_fetch_array($selSettings);
		 $settings_earg = @unserialize($resSettings['extra_fields']);
		 $fname=$resSettings['fromname'];
		 $femail=$resSettings['set_email'];
		 $temail=$resSettings['testemail'];
		 $verification=$resSettings['verification'];
	#select Newsletter Info
		 $fletter=mysql_query("select * from tbl_newsletter where nl_id='".$sendn_val."' and nl_status='Y'")or die(mysql_error());
		 $res=mysql_fetch_array($fletter);
		 $subject=$res['nl_title'];
		 $nlid=$res['nl_id'];
		 $message=$res['nl_content'];
		 $date=date("Y-m-d",strtotime($resSettings['set_days']." day ".$resSettings['set_hrs']." hours ".$resSettings['set_mins']." minutes"));
		 #define email address array
		$addr_users = array();
		$addr_abookusers = array();
		
		if($htitle=="user" || $htitle=="all" || $htitle=="noneffective" || $htitle=="effective" || $htitle=="privileged" || $htitle=="mprivileged")
		{
			#user List
			if($htitle=="noneffective")
			{
				$cond = "having ctorder<'".$settings_earg['noneffective']."'";
			}
			else if($htitle=="effective")
			{
				$cond = "having ctorder BETWEEN '".$settings_earg['effective_from']."' AND '".$settings_earg['effective_to']."'";
			}
			else if($htitle=="privileged")
			{
				$cond = "having ctorder BETWEEN '".$settings_earg['previleged_from']."' AND '".$settings_earg['previleged_to']."'";
			}
			else if($htitle=="mprivileged")
			{
				$cond = "having ctorder>".$settings_earg['mprevileged'];
			}
		
			if($cond)
			{
				$UserList = mysql_query("SELECT U.user_id, U.user_name, U.user_email, U.user_dt, U.user_mobile, count( O.id ) AS ctorder FROM tbl_users U LEFT JOIN tbl_order O ON U.user_id = O.user_id GROUP BY U.user_id $cond");	
			}
			else #all user
			{
				$UserList=mysql_query("select * from tbl_users where user_status='Y'")or die(mysql_error());
				
			}
			$UserRows=mysql_num_rows($UserList);
			if($UserRows)
			{
				while($resUsers=mysql_fetch_array($UserList))
				{
					 $title = "Users";
					 $addr_users[]=$resUsers['user_email'];
					 $id=$resUsers['user_id'];
					 $insert=mysql_query("insert into tbl_history(id,ab_id,hnewsletter,htitle,dt) values('$id','".$title."','$nlid','$title','$date')")or die(mysql_error());	
				}
			}	
		}
		
		#address book
		$subscriber_id = (is_integer($htitle)) ? $htitle : "";
		if($htitle=="0" || $htitle=="all")
		{
			//echo $htitle;
			$sub_id = ($subscriber_id) ? $subscriber_id : 0;
			$sqlAddrBook=mysql_query("select * from tbl_addr_book where ab_id='".$sub_id."' and status='Y'")or die(mysql_error());
			$AddressBookRows=mysql_num_rows($sqlAddrBook);
			if($AddressBookRows>0)
			{
				 while($resAbook=mysql_fetch_array($sqlAddrBook))
				 {
				 	 $title = "Subscribers";
					 $addr_abookusers[]=$resAbook['email'];
					 $id=$resAbook['aid'];
					 $abid=$resAbook['ab_id'];
					 $insert=mysql_query("insert into tbl_history(id,ab_id,hnewsletter,htitle,dt) values('$id','$abid','$nlid','$title','$date')")or die(mysql_error());	
				 }
			}
		}
		
		$MergeEmailAddress = array_merge($addr_users,$addr_abookusers);
		//print_r($MergeEmailAddress);
		if($MergeEmailAddress)
		{
			$list=implode(',',$MergeEmailAddress);
	 
	   	    $from = stripslashes($fname)."<".stripslashes($femail).">";
	   	    
			$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
	  		
			$headers = "From: $from\r\nBcc: {$list}" . "\r\n" .
			   "MIME-Version: 1.0\r\n" .
				  "Content-Type: multipart/mixed;\r\n" .
				  " boundary=\"{$mime_boundary}\"";
				$message = $res['nl_content'] . "\r\n";   
			   $message = "This is a multi-part message in MIME format.\n\n" .
				  "--{$mime_boundary}\n" .
				  "Content-Type: text/html; charset=\"iso-8859-1\"\n" .
				  "Content-Transfer-Encoding: 7bit\n\n" .
			   $message . "\n\n";
				
				$i=1;
			  
			   while($i<=5)
			   {
					   if($res['nl_attach'.$i]!="")
					   {
						  $attach = "../mail_attach/".$sendn_val."/".$res['nl_attach'.$i];
						  $name = $res['nl_attach'.$i];
						  $type = filetype($attach);
						  $size = filesize($attach);
						  $file = fopen($attach,'rb');
						   $data = fread($file,filesize($attach));
						   fclose($file);
						  $data = chunk_split(base64_encode($data));
							 $message .= "--{$mime_boundary}\n" .
								"Content-Type: {$type};\n" .
								" name=\"{$name}\"\n" .
								"Content-Disposition: attachment;\n" .
								" filename=\"{$name}\"\n" .
								"Content-Transfer-Encoding: base64\n\n" .
							 $data . "\n\n";
					   }
					   $i++;
			   }
		 	
				$message.="--{$mime_boundary}--\n";
				$sendmail = @mail($tomail, $subject, $message, $headers);
				if($sendmail)
				{
 					$ret = 'success';
				}
				else
				{
					$ret = 'failure';
				}
	 	}
		else
		{
			$ret = "failure1";
		}
		return $ret;
}
function reIndexArray( $arr, $val )
{
   $new_array = array();
   
   $new_array[0] = $val;
   
   foreach($arr as $arrval)
   {
   		if($arrval!=$val)
   		$new_array[] = $arrval;
   }
   return $new_array;
}
#show parent attributes depends on category
function show_filterattributes($cat_id)
{
	$sel = select_query("tbl_product","attribute_parent","FIND_IN_SET(".$cat_id.",cat_id)");
	if($sel['nr'])
	{
		foreach($sel['result'] as $res)
		{
			$ex_val = explode(",",$res['attribute_parent']);
			foreach($ex_val as $val)
			{
				$arr[] = $val;
			}
		}
		return @array_unique($arr);
	}
}
#show_price
function show_price($product_id,$price_status)
{
	if($price_status=="fixed")
	{
		$sel = select_query("tbl_product","prod_ret_amt,prod_sp_amt","prod_id='".$product_id."'","1");
		$arr['list_price'] = $sel['prod_ret_amt'];
		$arr['our_price'] = $sel['prod_sp_amt'];
	}
	else
	{
		$sel = select_query("tbl_price","list_price,price","product_id='".$product_id."' AND price_default='Y'","1");
		$arr['list_price'] = $sel['list_price'];
		$arr['our_price'] = $sel['price'];
	}
	return $arr;
}

#function attribute parent name
function attr_parent($attr_id)
{
	if($attr_id)
	{
		$selAttrparent = select_query("tbl_productattributes C,tbl_productattributes P","P.attr_title AS pname,C.attr_title AS attr_name","C.attr_pid=P.attr_id AND C.attr_id='".$attr_id."'","1");
		$arr['attr_title'] = $selAttrparent['attr_name'];
		$arr['attr_parent'] = $selAttrparent['pname'];
		return $arr;
	}
}
//print_r(show_price(415,"fixed"));
//print_r(show_filterattributes(6));
#settings
$settings = select_query("tbl_settings","*","set_id=1","1");
$settings_earg = @unserialize($settings['extra_fields']);
$attribute_setting = ($settings_earg['attributes']) ? $settings_earg['attributes'] : "";

function show_list($table_name,$field_name,$where='',$order,$key='',$name='',$select='')
{
	if($where)$where=" WHERE ".$where;
	$squery = mysql_query("SELECT ".$field_name." FROM ".$table_name." ".$where." ORDER BY ".$order." ASC");
	if(mysql_num_rows($squery)!=0)
	{
		while($res=mysql_fetch_object($squery))
		{
			$sel=($select)?isselected($res->$key,$select):'';
			echo '<option value="'.$res->$key.'" '.$sel.'>'.$res->$name.'</option>';	
		}
	}
}
function get_cat($table_name, $field_name, $condition, $name='',$print='')
{
	if($field_name == "")
	{
		$field_name = "*";
	}
	
	$selectQ = "select $field_name from $table_name";
	
	if($condition!="")
	{
		$selectQ .= " where $condition limit 1";
	}

	if($print){echo $selectQ."<br>";}
   
	$resQuery    =    mysql_query($selectQ);
	
	if(($_SERVER['HTTP_HOST']=="localhost:81" || $_SERVER['HTTP_HOST']=="localhost") && mysql_error())
	{
		echo $sql,"<br>",mysql_error();
	}
   
	$NumRows    =    mysql_num_rows($resQuery);
	if($NumRows==0)
	{
	echo 'NOT IN';
	}
	else
	{
	$res = mysql_fetch_assoc($resQuery);
	echo ($res[$name])?$res[$name]:'Nill';
	}
}
?>