<?php

function getValidFileName($fname) {
	$pattern="[?()\/&#\,\;\.$+%]";
	$valid_file=mb_ereg_replace($pattern,"-",$fname);
	$valid_file=strtolower($valid_file);
	$valid_file=str_replace("  ","-",$valid_file);
	$valid_file=str_replace(" ","-",$valid_file);
	$valid_file=str_replace("_","-",$valid_file);
	$valid_file=str_replace("%","",$valid_file);
	$valid_file=str_replace("__","-",$valid_file);
	$valid_file=str_replace("--","-",$valid_file);
	return $valid_file;
}

function smtp_mailer($to,$email,$name,$subject,$msg){
   
	$mail = new PHPMailer(); 
	$mail->SMTPDebug  = 0;
	$mail->IsSMTP(); 
	$mail->SMTPAuth = true; 
	$mail->SMTPSecure = 'tls'; 
	$mail->Host = "162.215.169.152";
	$mail->Port = 587; 
	$mail->IsHTML(true);
	$mail->CharSet = 'UTF-8';
	$mail->Username = "enquiry@webpulsesolution.net";
    $mail->Password = "aWj)lgpI5s5+";
    $mail->SetFrom("enquiry@webpulsesolution.net",'webpulsesolution.net');
	$mail->AddReplyTo($email,$name);
	$mail->Subject = $subject;
	$mail->Body =$msg;
	$mail->AddAddress($to);
    
    
	$mail->SMTPOptions=array('ssl'=>array(
		'verify_peer'=>false,
		'verify_peer_name'=>false,
		'allow_self_signed'=>false
	));
	if(!$mail->Send()){
      
		echo $mail->ErrorInfo;
	}else{
       
		return 'Sent';
	}
}


// ip address 
function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}


function createSeoUrl($string) {
    $string = strtolower($string);
   $string = preg_replace('/[^a-z0-9\-]+/', '-', $string);
    $string = preg_replace('/-+/', '-', $string);
    return trim($string, '-');
}


function is_mobile() {
    return preg_match("/(android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini)/i", $_SERVER["HTTP_USER_AGENT"]);
}
function htmlentitiesDecode($string_with_quotes)
{
	$string_with_quotes = htmlspecialchars($string_with_quotes, ENT_QUOTES, 'UTF-8');
	$string_with_quotes = mysqli_real_escape_string($GLOBALS['dbconn'],$string_with_quotes);
	return $string_with_quotes;

}

function clean($string) {
	$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
	$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
 
	$string = preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
	$string = strtolower($string);
	return $string;
 }

function mail_header() {
	$ContactPerson=getAdminname();
	$eMail=getAdminemail();
	$headers = "From: $ContactPerson<$eMail> \n";
	$headers .= "Reply-To: $eMail \r\n";
	$headers .= "X-Mailer: PHP/". phpversion();
	$headers .= "X-Priority: 3 \n";
	$headers .= "MIME-version: 1.0\n";
	$headers .= "Content-Type: text/html; charset=UTF-8\n";
	return $headers;
}

function getAdminemail() {
	$res=getResult("admin_details"," where slno=1");
	return $res['email'];
}

function getUserDetails($mob='') {
	$name = $_SESSION['name'];
	$email = $_SESSION['email'];
	$res=getResult("customer_tbl"," where cmobile='$mob'");
	if($res){
		return $res;
	} else{
		return $res = null;
	}
}

//added on 15-06-2024
function saveResizedPhoto($file_name, $width, $height, $source_folder, $destination_folder) {
	
	if (!file_exists($destination_folder)) {
		mkdir($destination_folder, 0777);
		chmod($destination_folder, 0777);
	}
	
	$source_path=$source_folder."/".$file_name;
	$destination_path=$destination_folder."/".$file_name;
	$ext=explode(".",$file_name);






	if($ext[1]=="gif" or $ext[1]=="GIF") {
		$mainimage=imagecreatefromgif($source_path);
	}
	elseif($ext[1]=="png" or $ext[1]=="PNG") {
		$mainimage=imagecreatefrompng($source_path);
	}
	elseif($ext[1]=="jpg" or $ext[1]=="JPG" or $ext[1]=="jpeg" or $ext[1]=="JPEG") {
		$mainimage=imagecreatefromjpeg($source_path);
	}

	elseif($ext[1]=="webp" or $ext[1]=="WEBP") {
		$mainimage=imagecreatefromwebp($source_path);
	}
	
	$mainwidth=imagesx($mainimage);
	$mainheight=imagesy($mainimage);

	


	
	if($mainwidth<=$width and $mainheight<=$height) {
		$thumbleheight=$mainheight;
		$thumblewidth=$mainwidth;	
	}
	else {
		if($mainwidth>$width) {
			$thumblewidth=$width;
			$thumbleheight=(($width/$mainwidth)*$mainheight);	
			if ($thumbleheight > $height) {
				$thumbleheight=$height;
				$thumblewidth=(($height/$mainheight)*$mainwidth);	
			}
		}
		else if($mainheight>$height) {
			$thumbleheight=$height;
			$thumblewidth=(($height/$mainheight)*$mainwidth);	
			if ($thumblewidth > $width) {
				$thumblewidth=$width;
				$thumbleheight=(($width/$mainwidth)*$mainheight);	
			}
		}
	}
	
	if($ext[1]=="webp" or $ext[1]=="WEBP")
	{
		
		$newImg = imagecreatetruecolor($width, $height);
		imagealphablending($newImg, false);
		imagesavealpha($newImg, true);
		$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
		imagefilledrectangle($newImg, 0, 0, $width, $height, $transparent);
		imagecopyresampled($newImg, $mainimage, 0, 0, 0, 0, $width, $height, $mainwidth, $mainheight);
		imagewebp($newImg,$destination_path);
		imagedestroy($newImg);
		imagedestroy($mainimage);
	}
	else if($ext[1]=="png" or $ext[1]=="PNG")
	{
		$newImg = imagecreatetruecolor($width, $height);
		imagealphablending($newImg, false);
		imagesavealpha($newImg, true);
		$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
		imagefilledrectangle($newImg, 0, 0, $width, $height, $transparent);
		imagecopyresampled($newImg, $mainimage, 0, 0, 0, 0, $width, $height, $mainwidth, $mainheight);
		imagepng($newImg,$destination_path);
		imagedestroy($newImg);
		imagedestroy($mainimage);
	}
	else{

	$thumbleimage=imagecreate($thumblewidth,$thumbleheight);
	$thumbleimage=@imagecreatetruecolor($thumblewidth,$thumbleheight);
	$my_temp_file= ImageCopyResampled($thumbleimage,$mainimage,0,0,0,0,$thumblewidth,$thumbleheight,$mainwidth,$mainheight);
	imagejpeg($thumbleimage,$destination_path,70);
	imagedestroy($thumbleimage);
	imagedestroy($mainimage);

	}



}

function getImage($file_name, $width, $height, $product_name, $source_folder1) {
    $product_name = str_replace(' ', '-', $product_name);
    $file_parts = explode('.', $file_name);
    $file_name_to_store = $product_name . '-thumbs-' . $width . 'X' . $height . '.' . $file_parts[1];
    $source_folder = SITE_DIR_PATH . $source_folder1;
    $destination_folder = $source_folder . "thumbs";

    saveResizedImage($file_name, $width, $height, $source_folder, $destination_folder, $file_name_to_store,$quality);
    return site_url . $source_folder1 . "thumbs/" . $file_name_to_store;
}



function saveResizedImage($file_name, $width, $height, $source_folder, $destination_folder,$file_name_to_store = '') {
	   if ($file_name_to_store == '') {
        $file_name_to_store = $file_name;
    }
	if (!file_exists($destination_folder)) {
		mkdir($destination_folder, 0777);
		chmod($destination_folder, 0777);
	}
	
	$source_path=$source_folder."/".$file_name;
  $destination_path = $destination_folder . "/" . $file_name_to_store;
	$ext=explode(".",$file_name);






	if($ext[1]=="gif" or $ext[1]=="GIF") {
		$mainimage=imagecreatefromgif($source_path);
	}
	elseif($ext[1]=="png" or $ext[1]=="PNG") {
		$mainimage=imagecreatefrompng($source_path);
	}
	elseif($ext[1]=="jpg" or $ext[1]=="JPG" or $ext[1]=="jpeg" or $ext[1]=="JPEG") {
		$mainimage=imagecreatefromjpeg($source_path);
	}

	elseif($ext[1]=="webp" or $ext[1]=="WEBP") {
		$mainimage=imagecreatefromwebp($source_path);
	}
	
	$mainwidth=imagesx($mainimage);
	$mainheight=imagesy($mainimage);

	


	
	if($mainwidth<=$width and $mainheight<=$height) {
		$thumbleheight=$mainheight;
		$thumblewidth=$mainwidth;	
	}
	else {
		if($mainwidth>$width) {
			$thumblewidth=$width;
			$thumbleheight=(($width/$mainwidth)*$mainheight);	
			if ($thumbleheight > $height) {
				$thumbleheight=$height;
				$thumblewidth=(($height/$mainheight)*$mainwidth);	
			}
		}
		else if($mainheight>$height) {
			$thumbleheight=$height;
			$thumblewidth=(($height/$mainheight)*$mainwidth);	
			if ($thumblewidth > $width) {
				$thumblewidth=$width;
				$thumbleheight=(($width/$mainwidth)*$mainheight);	
			}
		}
	}
	
	if($ext[1]=="webp" or $ext[1]=="WEBP")
	{
		
		$newImg = imagecreatetruecolor($width, $height);
		imagealphablending($newImg, false);
		imagesavealpha($newImg, true);
		$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
		imagefilledrectangle($newImg, 0, 0, $width, $height, $transparent);
		imagecopyresampled($newImg, $mainimage, 0, 0, 0, 0, $width, $height, $mainwidth, $mainheight);
		imagewebp($newImg,$destination_path);
		imagedestroy($newImg);
		imagedestroy($mainimage);
	}
	else if($ext[1]=="png" or $ext[1]=="PNG")
	{
		$newImg = imagecreatetruecolor($width, $height);
		imagealphablending($newImg, false);
		imagesavealpha($newImg, true);
		$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
		imagefilledrectangle($newImg, 0, 0, $width, $height, $transparent);
		imagecopyresampled($newImg, $mainimage, 0, 0, 0, 0, $width, $height, $mainwidth, $mainheight);
		imagepng($newImg,$destination_path);
		imagedestroy($newImg);
		imagedestroy($mainimage);
	}
	else{

	$thumbleimage=imagecreate($thumblewidth,$thumbleheight);
	$thumbleimage=@imagecreatetruecolor($thumblewidth,$thumbleheight);
	$my_temp_file= ImageCopyResampled($thumbleimage,$mainimage,0,0,0,0,$thumblewidth,$thumbleheight,$mainwidth,$mainheight);
	imagejpeg($thumbleimage,$destination_path,70);
	imagedestroy($thumbleimage);
	imagedestroy($mainimage);

	}



}



	function getCount($tableName, $cond="", $fields="*") {
		$sql=db_query("select $fields from $tableName $cond");
		return mysqli_num_rows($sql);
	}
	

	function updateTable($tableName,$cond="") {

		

	
		$updateResult = db_query("update $tableName set $cond");
		return $updateResult;
	}
	
	
	function getResult($tableName, $cond="", $fields="*") {
		$sql=db_query("select $fields from $tableName $cond");
		$res=mysqli_fetch_array($sql);
		return $res;
	}

	function getAdminname() {
		$res=getResult("admin_details"," where slno=1");
		return $res['name'];
	}


	function getbrandname($ID) {
		$res=getResult("brand_tbl"," where slno=$ID order by slno");
		return $res['brandTitle'];
	}

	function get_category_name($id) {
		$sql = mysqli_query($GLOBALS['dbconn'], "SELECT * FROM category_tbl where catID= $id");
		$team_group = mysqli_fetch_array($sql);
		if (is_array($team_group)) {
		  return $team_group['catName'];
		} else {
		  return "";
		}
	  }

	  function getCatname($id) {
		
		$sql = mysqli_query($GLOBALS['dbconn'], "SELECT * FROM category_tbl where catID= $id");
		$team_group = mysqli_fetch_array($sql);
		$dspname = $team_group['displayName'] ? $team_group['displayName'] : $team_group['catName'];
		return $dspname;

	  }

	  function getImgAlt($id) {
		
		$sql = mysqli_query($GLOBALS['dbconn'], "SELECT * FROM category_tbl where catID= $id");
		$team_group = mysqli_fetch_array($sql);
		$alt= $team_group['alt'] ? $team_group['alt'] : $team_group['displayName'];
		return $alt;

	  }
	  function getImgTitle($id) {
		
		$sql = mysqli_query($GLOBALS['dbconn'], "SELECT * FROM category_tbl where catID= $id");
		$team_group = mysqli_fetch_array($sql);
		$title= $team_group['title'] ? $team_group['title'] : $team_group['displayName'];
		return $title;

	  }


	  
	  function get_catprice($id,$br) {
		$sql = mysqli_query($GLOBALS['dbconn'], "SELECT * FROM attribute_tbl where cat_id= '$id' and brand_id='$br'");
		$team_group = mysqli_fetch_array($sql);
		if (is_array($team_group)) {
			return $team_group['price']; 
		} else {
		  return "";
		}
	  }
	

	function send_email($fromPerson, $fromEmail, $to, $subject, $message) {
		$eMail=getAdminemail();
		$headers = "From:$fromPerson<$fromEmail> \n";
		$headers .= "Reply-To: $eMail \r\n";
		$headers .= "X-Mailer:PHP v".phpversion()."\r\n";
		$headers .= "X-Priority:3\n";
		$headers .= "MIME-version:1.0\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
		$msg=$message;
		mail($to, $subject, $msg, $headers);
	}


	function print_message() {
		echo "<center><font style=\"color:#ee0000;\"><b>".$_SESSION['session_message']."</b></font></center><br />";
		$_SESSION['session_message']="";
	}

	function upload_file($newname,$image,$folder) {
		$folder=SITE_DIR_PATH."/".$folder;
		if (!file_exists($folder)) {
			mkdir($folder, 0777);
			chmod($folder, 0777);
		}
		if($_FILES[$image]['name']!="") {
			$extension=getExtension($_FILES[$image]['name']);
			$image_name=$newname.".".$extension;		
			$uploadedfile=$_FILES[$image]['tmp_name'];
			$tmp_imagename=$_FILES[$image]['name'];
			if($tmp_imagename<>"" && $uploadedfile<>"" && $image_name<>"") {		
				move_uploaded_file($uploadedfile, $folder."/".$image_name);
			}
		}
		return $image_name;
	}

	function getExtension($str) {
		$i = strrpos($str,".");
		if (!$i) { return ""; }
		$l = strlen($str) - $i;
		$ext = substr($str,$i+1,$l);
		return $ext;
	}
	

	function getClass() {
		$msg=explode("~",$_SESSION['opmsg']);
		if(count($msg)<2) {
			$class="msgadmin";	
		}else {
			$class=$msg[1];
		}
		return $class;	
	}

	function page_nav($catid) {
		$res=getResult("category_tbl"," where catID='$catid'");
		$flag=0;
		$catparent=$catid;
		while($flag!=1) {
			$res1=db_query("select * from category_tbl where catID='$catparent'");
			$record=db_fetch_array($res1);
			if($record['parentID']!=0) {
				$catparent=$record['parentID'];
				$array=$record['catID']."~";
			}
			else {
				if($record['catID']!="") {
					$array=$record['catID']."~";
				}
				$flag=1;
			}
		}
		$arr=explode("~",$array);
		$result = array_reverse($arr);
		echo "<b><a href='manage-category.php' class='menu2'>Manage Categories</a> ";
		for($i=1;$i<count($result);$i++) {
			$res=getResult("category_tbl"," where catID='$result[$i]'");
			$re=db_query("select * from category_tbl where catID='".$res['catID']."'");
			if(NumRows($re)==0) {
				if($res['catID']==$catid) {
					echo " <b>::</b> ".$res['catName'];
				}else {
					echo " <b>::</b> <a href='manage-category.php?parentID=".$res['catID']."' class='menu2'>".$res['catName']."</a>";
				}
			}else {
				if($res['catID']==$catid) {
					echo " <b>::</b> ".$res['catName'];
				}else {
					echo " <b>::</b> <a href='manage-category.php?parentID=".$res['catID']."' class='menu2'>".$res['catName']."</a>";
				}
			}
		}
		echo "</b>";
	}
	
	function getListingCategoriesDropDownAjax3($fldName, $value, $width="") {
		if ($width=="") {
			$width="220";
		}
		$link="'".$_SERVER['PHP_SELF']."'";
		$var='<select name="'.$fldName.'" style="width: '.$width.'px; " onChange="javascript:dynshowHint(this.value,'.$link.',\'?id=show_sub_categories\',\'showSubCategories\');">
		<option value="" selected="selected" >----------- Select Listing Categories -----------</option>';
		$catQry=db_query("select catID, catName from  category_tbl where parentID='0' and catgType='2' order by catOrder asc");
		while($catRes=mysql_fetch_array($catQry)) {
			
			if(trim($catRes[catID])==trim($value)) {
				$var.= "<option value='".$catRes[catID]."' selected='selected'>".$catRes[catName]."</option>";
			}
			else {
				$var.="<option value='".$catRes[catID]."'>".$catRes[catName]."</option>";
			}
		}
		$var.='</select>';
		return $var; 
	}

function watermark_image($target, $wtrmrk_file, $newcopy) {
  $watermark = imagecreatefrompng($wtrmrk_file);
  imagealphablending($watermark, false);
  imagesavealpha($watermark, true);
  $img = imagecreatefromjpeg($target);
  $img_w = imagesx($img);
  $img_h = imagesy($img);
  $wtrmrk_w = imagesx($watermark);
  $wtrmrk_h = imagesy($watermark);
  imagecopy($img, $watermark, -5, -5, 0, 0, $wtrmrk_w, $wtrmrk_h);
  imagejpeg($img, $newcopy, 100);
  imagedestroy($img);
  imagedestroy($watermark);
}
	
	
	function getListingSubCategoriesDropDown($fldName, $catID, $sel, $width="") {
		if ($width=="") {
			$width="220";
		}
		
		$var="<div style='width:".$width."px; height:115px; overflow-x:hidden; overflow-y:scroll; border:1px solid gray'>";
		
		$low_level = "";
		if($catID!='') {
			$qry=db_query("select catID from category_tbl where parentID='$catID' and status='Y' order by catName");
			$num=NumRows($qry);
			if($num>0) {
				$i=0;
				while($row=mysql_fetch_array($qry)) {
					$low_level.=	$row[0].",".getAllChilds($row[0]);
					$i++;
				}
			}
		}
		
		$catarr=explode(",",$low_level);
		if (count($catarr) > 1) {
			for($i=0;$i<count($catarr);$i++) {
				$catid2=$catarr[$i];
				$res2=getResult("category_tbl"," where catID='$catid2'");
				$space=parentCount($catid2);
				if(haveSubCategory($catid2)=='Y' && $i < count($catarr)-1) {
					if ($space!=0) {
						for ($p=1;$p<$space;$p++) {
							$var.='&nbsp;&nbsp;';
						}
					}
					$var.="<strong>".ucwords($res2[catName])."</strong><br/>";
				}
				
				if(haveSubCategory($catid2)=='N') {
					if ($space!=0) {
						for ($p=2;$p<=$space;$p++) {
							$var.='&nbsp;&nbsp;';					
						}
					}
					if (is_array($sel)) {
						if (in_array($catid2,$sel)) {
							$var.= "<input type='checkbox' name='".$fldName."[]' id='".$fldName."' value='".$catid2."' checked>".getCategoryName($catid2)."<br/>";
						}
						else {
							$var.= "<input type='checkbox' name='".$fldName."[]' id='".$fldName."' value='".$catid2."'>".getCategoryName($catid2)."<br/>";
						}
					}
					else {
						$catg="^".$catid2."^";
						if(strstr($sel,$catg)) {
							$var.= "<input type='checkbox' name='".$fldName."[]' id='".$fldName."' value='".$catid2."' checked>".getCategoryName($catid2)."<br/>";
						}
						else {
							$var.= "<input type='checkbox' name='".$fldName."[]' id='".$fldName."' value='".$catid2."'>".getCategoryName($catid2)."<br/>";
						}
					}								
				}
			}			
		}
		else {
			$res3=getResult("category_tbl"," where catID='$catID'");
			$var.= "<input type='checkbox' name='".$fldName."' id='".$fldName."' value='".$catid."' checked>".ucwords($res3[catName])."<br/>";
		}
		
		$var.='</div>';
		return $var; 
	}


	function pageNavigation($reccnt,$pagesize,$start,$link="") {
		if($reccnt>$pagesize) {
			$num_pages=$reccnt/$pagesize;
			$PHP_SELF=$_SERVER['PHP_SELF'];
			$qry_str=$_SERVER['argv'][0];
			$m=$_GET;
			unset($m['start']);
			$qry_str=qry_str($m);
			$j=$start/$pagesize-5;
			if($j<=0) {
				$j=0;
			}
			$k=$j+10;
			if($k>$num_pages)	{
				$k=$num_pages;
			}
			$j=intval($j);
			?>
			
			<div class="main_index" align="center" style="margin:auto; ">
			 <?php
			 if($start!=0) {
				 $s=$start-$pagesize;
				 $newUrl=$PHP_SELF."".$qry_str."&start=".$s."&pagesize=".$pagesize.$link;
				 $newUrl=str_replace("?&","?",$newUrl);
				 ?>
				 <a href="<?=$newUrl?>" ><img src="<?=SITE_ADMIN_URL?>/images/previous.gif" alt="Previous Page" width="69" height="17" border="0" class="left"/></a>
				 <?php
			 }
			 else {
				 ?>
				 <img src="<?=SITE_ADMIN_URL?>/images/previous.gif" alt="Previous Page" width="69" height="17" border="0" class="left" />
				 <?php
			 }
			 if($start+$pagesize < $reccnt) {
				 $s=$start+$pagesize;
				 $newUrl=$PHP_SELF."".$qry_str."&start=".$s."&pagesize=".$pagesize.$link;
				 $newUrl=str_replace("?&","?",$newUrl);
				 ?>
				 <a href="<?=$newUrl?>"><img src="<?=SITE_ADMIN_URL?>/images/next.gif" alt="Next Page" width="44" height="17" border="0"  class="right" /></a>
				 <?php
			 }
			 else {
				 ?>
				 <img src="<?=SITE_ADMIN_URL?>/images/next.gif" alt="Next Page" width="44" height="17" border="0"  class="right" />
				 <?php
			 }
			 $startfrom=$start+1;
			 $end=$start+$pagesize;
			 if($reccnt<$end) {
				 $end=$reccnt;
			 }
			 #echo "Showing	$startfrom - $end of Total $reccnt Records";
			 ?>
			 <div class="index">
			  <?php 
			  for($i=$j;$i<$k;$i++) {
				  if(($pagesize*$i)!=$start) {
					  $s=$pagesize*$i;
					  $newUrl=$PHP_SELF."".$qry_str."&start=".$s."&pagesize=".$pagesize.$link;
					  $newUrl=str_replace("?&","?",$newUrl);
					  ?>
					  <a href="<?=$newUrl?>"  class="navBarTxt"><?=$i+1?></a>
					  <?php
				  }
				  else {
					  ?>
					  <span class="navBarTxt"><?=$i+1?></span>
					  <?php
				  }
			  }
			  ?>
			 </div>
			</div>
			<?php
		}
	}
	function getAdminDetails() {
		$res=getResult("admin_details"," where slno=1");
		return $res;
	}

    function getAdminaddress() {
	$res=getResult("admin_details"," where slno=1");
	return $res['address'];
    }

    function companyName(){
        $res=getResult("admin_details"," where slno=1");
	   return $res['companyName'];
    }

	function static_pages($page_id)
	{
		$res=getResult("static_pages"," where pageID='$page_id'");
		return $res;
	}


	function brand_id($name){
		$res=getResult("brand_tbl"," where brandTitle='$name'");
		return $res['slno'];
	}

    function coupan_per($code){
		$res=getResult("coupan_codes_tbl"," where code='$code'");
		return $res['discount'];
	}


   function getBanner()
   {   $bannerRes = [];
	   $banQuery = mysqli_query($GLOBALS['dbconn'],"select * from banner_tbl");
	   while($res_ban = mysqli_fetch_array($banQuery))
	   {
		$bannerRes[] = $res_ban;
	   }

	   return $bannerRes;
   }

   function getMediaLogo()
   {   $logoRes = [];
	   $logoQuery = mysqli_query($GLOBALS['dbconn'],"select * from media_tbl where status='Y' order by client_order");
	   while($res_logo = mysqli_fetch_assoc($logoQuery))
	   {
		$logoRes[] = $res_logo;
	   }

	   return $logoRes;
   }


function facebook() {
  $res = getResult("admin_details", "where slno=1");
  return $res['facebook_link'];
}

function youtube() {
  $res = getResult("admin_details", "where slno=1");
  return $res['youtube_link'];
}

function twitter() {
  $res = getResult("admin_details", "where slno=1");
  return $res['twitter_link'];
}

function linkedin() {
  $res = getResult("admin_details", "where slno=1");
  return $res['linked_link'];
}

function instagram() {
  $res = getResult("admin_details", "where slno=1");
  return $res['instagram_link'];
}

function theme_url() {
  echo theme_url;
}

function site_url() {
  echo site_url;
}

	function metainfo($arr,$arr1) {
			$data['page_metatitle'] = str_replace('hotkeyword1',$arr['keyword1'],str_replace('hotkeyword2', $arr['keyword2'], str_replace('state', $arr1['country'], str_replace('state', $arr1['country'], str_replace('city', $arr1['city'],$arr['pageTitle'])))));
			$data['page_metakey'] = str_replace('hotkeyword1',$arr['keyword1'],str_replace('hotkeyword2', $arr['keyword2'], str_replace('state', $arr1['country'], str_replace('hotkeyword3', $arr['keyword3'], str_replace('city', $arr1['city'],$arr['pageKeywords'])))));
            $data['page_metadesc']= str_replace('hotkeyword1',$arr['keyword1'],str_replace('hotkeyword2', $arr['keyword2'],str_replace('companyname', $arr1['companyName'], str_replace('phone', $arr1['phone'], str_replace('state', $arr1['country'], str_replace('hotkeyword3', $arr['keyword3'], str_replace('city', $arr1['city'],$arr['pageDescription'])))))));
		return $data;
	}

	function metainfo_sub($arr,$arr1) {
		$data['page_metatitle'] = str_replace('hotkeyword1',$arr['keyword1'],str_replace('hotkeyword2', $arr['keyword2'], str_replace('state', $arr1['state'], str_replace('state', $arr1['state'], str_replace('city', $arr1['city'],$arr['meta_title'])))));
		$data['page_metakey'] = str_replace('hotkeyword1',$arr['keyword1'],str_replace('hotkeyword2', $arr['keyword2'], str_replace('state', $arr1['state'], str_replace('hotkeyword3', $arr['keyword3'], str_replace('city', $arr1['city'],$arr['meta_keyword'])))));
        $data['page_metadesc']= str_replace('hotkeyword1',$arr['keyword1'],str_replace('hotkeyword2', $arr['keyword2'],str_replace('companyname', $arr1['companyName'], str_replace('phone', $arr1['phone'], str_replace('state', $arr1['state'], str_replace('hotkeyword3', $arr['keyword3'], str_replace('city', $arr1['city'],$arr['meta_description'])))))));
		return $data;
	}


	function generateOTP() {
		// Generate a random 4-digit number
		$otp = rand(1000, 9999);
		return $otp;
	}

	function sendSms($mobile,$message,$ip) {
		$sms_text = urlencode($message);
		$payload = file_get_contents("http://www.hindit.co.in/API/pushsms.aspx?loginID=T1ShamimDSC&password=sham123&mobile=$mobile&text=$sms_text&senderid=SHMTRD&route_id=2&Unicode=0&IP=$ip&Template_id=1007165675433921668"); 	
		return TRUE;
	}


	function get_emailcontent($table,$id){
		$res = getResult($table,"where id='$id'");
		return $res['email_content'];
	}



	function getIndianCurrency(float $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;
    }
    $Rupees = implode('', array_reverse($str));
    $paise = ($decimal > 0) ? "." . ($words[$decimal / 10] . " " . $words[$decimal % 10]) . ' Paise' : '';
    return ucwords(($Rupees ? $Rupees . 'Rupees ' : '') . $paise);
}


function get_OrderDetails($orderID){
	$order_res = getResult("orders_tbl", "where order_id='$orderID'");
	return $order_res;
}


	function invoice_html($invoice, $dbconn){
		ob_start();

		$orderDetails = mysqli_fetch_array($dbconn->query("SELECT * FROM orders_tbl1 WHERE invoice_id='".$invoice['invoice_id']."'"));
		$bg = file_get_contents(site_url.'/designer/images/invoice-watermark.jpg');
		$bg_img = 'data:image/jpg;base64,' . base64_encode($bg);
		$barcode = file_get_contents(site_url.'/designer/images/barcodedsc.png');
		$barcode_img = 'data:image/jpg;base64,' . base64_encode($barcode);
		$logo = file_get_contents(site_url.'/designer/images/logo.png');
		$logo_img = 'data:image/png;base64,' . base64_encode($logo);
		$sign = file_get_contents(site_url.'/sign.png');
		$sign_img = 'data:image/png;base64,' . base64_encode($sign);
		$t = round($orderDetails['total_amount']);
		$d = round($orderDetails['discount']);
		$g = round($orderDetails['gst_amount']);
		$d_percent = $orderDetails['discount']/$orderDetails['total_amount'];

		?>
	<!DOCTYPE html>
	<html lang="en">
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Invoice</title>
		<style>
			@page { 
				margin: 5px auto; 
			}
		</style>
		  

    </head>
    <body style="background-image:url(<?= $bg_img ?>); background-position:center; background-repeat: no-repeat; text-decoration: none; font-size:12px; font-family: Open Sans;  color: #000;">
        <div style="margin: 10px auto; box-shadow: 0 1px 4px 0 rgb(0 0 0 / 9%); padding: 25px; height: auto;">
			<div style="border-bottom: 1px solid #ccc; padding-bottom: 0px; margin-bottom: 0px; margin-top: 5px">
				<div style="width:80%; display: inline-block; text-align: left;">
					<div style="margin-bottom: 2px; vertical-align: top;"><img src="<?= $logo_img; ?>" alt=""></div>
					<p style=" margin:0px margin-bottom: 0px; color: #3e3f95; font-size: 15px; line-height: 12px;">dscsignature.in (a unit of)</p>
					<span style="display: block; margin-bottom: 0px; color: #3e3f95; font-weight: bold; font-size: 20px;  line-height: 15px;">SHAMIM`S TRADING CORPORATION</span>
					<span style="display: block; vertical-align: baseline; line-height: 13px;">B11/84B DDA Flats Inderlok Delhi, New Delhi, Delhi, India - 110035</span>
					<span style="display: block; line-height: 13px;">GSTIN/UIN: 07BEKPH5453P1ZX</span>
					<span style="display: block; line-height: 13px;">Mobile Number: 7838767686</span>
					<span style="display: block; margin-bottom:0px; line-height: 13px;">Email: support@dscsignature.in </span>
				</div>
				<div style="width:19%; display: inline-block; float:right; text-align: right; height:110px; ">
					<img src="<?= $barcode_img; ?>" style="height:100px;">
				</div>				
			</div>
			<div style="text-align: center; font-size: 14px; padding: 5px; background: #3e3f95; color: #fff;">TAX INVOICE</div>

			
            <table  style="border-collapse: collapse; width:100%" cellpadding="5">
				<tr>
					<td style="border:1px solid #ccc; padding: 5px; width:50%; vertical-align: top; font-size: 12px; text-decoration: none;">
						<span style="display: block; margin-bottom: 1px; vertical-align: baseline; font-size: 16px; font-weight:900; line-height: 15px;">Billing To</span>
						<span style="display: block; vertical-align: baseline; line-height: 13px;"><b style="font-weight:900;"><?=$orderDetails['bill_ogname']?></b></span>
						<span style="display: block; vertical-align: baseline; line-height: 13px">Contact Name : <b style="font-weight:900;"><?=$orderDetails['applicants_name']?></b></span>
						
						<span style="display: block; vertical-align: baseline; line-height: 13px"><?=$orderDetails['bill_address']?>, <?=$orderDetails['bill_city']?>, <?=$orderDetails['bill_state']?>, <?=$orderDetails['bill_country']?> - <?=$orderDetails['bill_zip']?></b></span>
						<span style="display: block; vertical-align: baseline; line-height: 13px"><?=$orderDetails['applicants_mobile']?>, <?=$orderDetails['applicants_email']?></span>
						<?php if($orderDetails['delivery_status'] != 'NA'){?>
							<span style="display: block; font-size: 16px; margin-top: 2px; border-top:1px solid #ccc; padding-top: 2px;line-height: 15px"><b>Delivery Address</b></span>
							<span style="display: block; line-height: 13px vertical-align: baseline; font-weight:400;"><?=$orderDetails['delivery_address']?>, <?=$orderDetails['delivery_city']?>, <?=$orderDetails['delivery_state']?>, <?=$orderDetails['delivery_country']?> - <?=$orderDetails['delivery_zip']?></span>
						<?php } ?>
					</td>
					<td style="border:1px solid #ccc; width:50%; vertical-align: top; padding:0;  border-left: 3px solid #3e3f95;">
						<table style="width:100%; border-collapse: collapse; font-size:12px; font-style: normal; font-weight: normal;" cellpadding="5">
							<tr>
								<td style="width:50%; border:1px solid #ccc; padding: 3px;">Invoice No: <span style="font-weight:900;"><?=$orderDetails['success_order_id']?></span></td>
								<td style="width:50%; border:1px solid #ccc; padding: 3px;">Invoice Date: <span style="font-weight:900;"><?=date('d-m-Y',strtotime($invoice['created_at']))?></span></td>
							</tr>
							<tr>
								<td colspan="2" style="width:50%; border:1px solid #ccc; padding: 3px;	">Order Id: <span style="font-weight:900;"><?= $invoice['payment_invoice_id']; ?></span></td>
							</tr>
							<tr>
								<td  colspan="2" style="width:50%; border:1px solid #ccc; padding: 3px;">Payment Id: <span style="font-weight:900;"><?= $invoice['tracking_id']; ?></span></td>
							</tr>
							<tr>
								<td colspan="2" style="width:50%; border:1px solid #ccc; padding: 3px;">Customer GST No.: <span style="font-weight:900;"><?=$orderDetails['bill_gst']?></span></td>
							</tr>
							<tr>
								<td colspan="2" style="width:50%; border:1px solid #ccc; padding: 3px; border-bottom:none;">Customer State: <span style="font-weight:900;"><?=$orderDetails['bill_state']?></span></td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
			<div style="clear: both; display: block;"></div>

            <table width="100%" style="border-collapse: collapse; font-size: 12px; font-family: Arial; color: #000; clear: inline-end;" cellpadding="5">
            	<tbody>
					<tr style="background: #c5c5c5a8; text-align:right; font-weight: 600;">
						<td rowspan="2" style="width:30%; border:1px solid #ccc; padding: 2px; text-align: left;">Description of Goods/Services</td>
						<td rowspan="2" style="width:5%; border:1px solid #ccc; padding: 2px; text-align:left;">SAC/HSN</td>
						<td rowspan="2" style="width:5%; border:1px solid #ccc; padding: 2px;">QTY</td>
						<td rowspan="2" style="width:5%; border:1px solid #ccc; padding: 2px; text-align:center;">UOM</td>
						<td rowspan="2" style="width:5%; border:1px solid #ccc; padding: 2px;">Rate</td>
						<td rowspan="2" style="width:10%; border:1px solid #ccc; padding: 2px; text-align:center;">Gross Amount</td>
						<td rowspan="2" style="width:5%; border:1px solid #ccc; padding: 2px;">Discount</td>
						<td rowspan="2" style="width:5%; border:1px solid #ccc; padding: 2px;">Net Value</td>
						<td colspan="2" style="width:30%; border:1px solid #ccc; padding: 2px; text-align:center;"><?= $gst_type = (strtoupper($orderDetails['bill_state']) == 'DELHI')?'CGST/SGST':'IGST'; ?></td>
					</tr>
					<tr style="background: #c5c5c5a8; text-align:center; font-weight: 600;">
						<td style="width:15%; border:1px solid #ccc; padding: 2px;">Rate</td>
						<td style="width:15%; border:1px solid #ccc; padding: 2px;">Amount</td>
					</tr>
				<?php $itms = $dbconn->query("SELECT o.*, c.displayName FROM order_items AS o LEFT JOIN category_tbl AS c ON o.category_id=c.catID WHERE invoice_id='".$orderDetails['invoice_id']."'");
            		while($itm = mysqli_fetch_array($itms)){ ?>
					<tr style="text-align: right;">
						<td style="text-align: left; border:1px solid #ccc; padding: 2px; width:30%">
							<?= $itm['displayName']; ?>
							<?php if(!empty($itm['brand'])){ ?><div><small>Brand: <?= $itm['brand']?></small></div><?php } ?>
							<?php if(!empty($itm['validity'])){ ?><div><small>Validity: <?= $itm['validity']?> Year</small></div><?php } ?>
							<?php if(!empty($itm['user_type'])){ ?><div><small>User Type: <?= $itm['user_type']?></small></div><?php } ?>
							<?php if(!empty($itm['organizationType'])){ ?><div><small>Org. Type: <?= $itm['organizationType']?></small></div><?php } ?>
							<?php if(!empty($itm['token_type'])){ ?><div><small>Token Type: <?= $itm['token_type']?></small></div><?php } ?>
						</td>
						<td style="border:1px solid #ccc; padding: 2px;"><?= (empty($itm['brand']))?'847330':'998319'; ?></td>
						<td style="border:1px solid #ccc; padding: 2px;"><?= $itm['quantity']?></td>
						<td style="border:1px solid #ccc; padding: 2px;">Nos</td>
						<td style="border:1px solid #ccc; padding: 2px;;"><?= round($itm['price_each']); ?></td>
						<td style="border:1px solid #ccc; padding: 2px;"><?= $itm['price_each']*$itm['quantity']; ?></td>
						<td style="border:1px solid #ccc; padding: 2px;"><?= $d_each = round(($itm['price_each']*$itm['quantity'])*$d_percent); ?></td>
						<td style="border:1px solid #ccc; padding: 2px;"><?= ($itm['price_each']*$itm['quantity'])-$d_each; ?></td>
						<td style="border:1px solid #ccc; padding: 0px; text-align:center;">
							<?= ($gst_type !='IGST')?'CGST: 9%<hr style="margin: 0px; height: 0.5px; border: 0; background: #ccc;">SGST: 9%':'18%'?>
						</td>
						<td style="border:1px solid #ccc; padding: 0px; padding: 2px;">
							<?php $gst_each = round((($itm['price_each']*$itm['quantity'])-$d_each)*0.18)?>
							<?= ($gst_type !='IGST')?($gst_each/2).'<hr style="margin: 0px; height: 0.5px; border: 0; background: #ccc;">'.($gst_each/2):$gst_each; ?>
						</td>
					</tr>
				<?php } ?>
					<tr>
						<td style="text-align: left; border:1px solid #ccc; padding: 2px;">Total: </td>
						<td style="border:1px solid #ccc; padding: 2px;"></td>
						<td style="border:1px solid #ccc; padding: 2px;"></td>
						<td style="border:1px solid #ccc; padding: 2px;"></td>
						<td style="border:1px solid #ccc; padding: 2px;"></td>
						<td style="border:1px solid #ccc; padding: 2px; text-align: right;"><?= $t; ?></td>
						<td style="border:1px solid #ccc; padding: 2px; text-align: right;"><?= $d; ?></td>
						<td style="border:1px solid #ccc; padding: 2px; text-align: right;"><?= $t-$d; ?></td>
						<td style="border:1px solid #ccc; padding: 2px;"></td>
						<td style="text-align: right; border:1px solid #ccc; padding: 2px; font-family: Arial;"><?= $g = round($orderDetails['gst_amount']); ?></td>
					</tr>
				</tbody>
			</table>

			<?php $gt = ($t-$orderDetails['discount'])+$g; ?>
			
			<table style="width:100%; border-collapse: collapse; font-size: 12px; font-family: Arial;">
				<tbody>
					<tr style="">
						<?php
							$rowspan = ($orderDetails['discount'] > 0)?4:3; 
							
							$last_payment = mysqli_fetch_assoc(mysqli_query($dbconn, "SELECT SUM(requested_amount) as amount FROM order_payment_history WHERE invoice_id='".$invoice['invoice_id']."' AND payment_id<".$invoice['payment_id']));
							$last_recieved = ($last_payment['amount'])?$last_payment['amount']:0;
							if($last_recieved > 0){$rowspan++;}
							$paid_amount = $invoice['requested_amount'];
						?>
						<td rowspan="<?= (($paid_amount+$last_recieved) <= $gt)?$rowspan+3:$rowspan ?>" style="width:60%; border:1px solid #ccc; padding: 5px; border-bottom:1px solid #ccc; vertical-align: top;">Total Invoice Value in Words:<br> <b><?= getIndianCurrency($gt)?> Only</b></td>
						<td style="text-align: right; border-right:1px solid #ccc; padding-right: 2px; line-height:10px;">Gross Value</td>
						<td style="width:10%; border-right:1px solid #ccc; padding: 2px; text-align:right; line-height:10px;"><?= $t ?> </td>
					</tr>
					<?php if($orderDetails['discount']  > 0){?>
					<tr>
						<td style="text-align: right; border-right:1px solid #ccc; padding-right: 2px;  line-height:10px;">Discount (<?=strtoupper($orderDetails['coupon_code'])?>)</td>
						<td style="width:10%; border-right:1px solid #ccc; padding: 2px; text-align:right; line-height:10px;"><?= round($orderDetails['discount'])?></td>
					</tr>
					
					<?php } ?>
					<tr>
						<td style="text-align: right; border-right:1px solid #ccc; padding-right: 2px;  line-height:10px;">Net Value</td>
						<td style="width:10%; border-right:1px solid #ccc; padding: 2px; text-align:right; line-height:10px;"><?= $t-$d; ?></td>
					</tr>
					<tr>
						<td style="text-align: right; border-right:1px solid #ccc; padding-right: 2px; line-height:10px;">Total Tax</td>
						<td style="width:10%; border-right:1px solid #ccc; padding: 2px; text-align:right;  line-height:10px;"><?= $g ?></td>
					</tr>
					<tr>
						<td style="text-align: right; border-right:1px solid #ccc; border-bottom:1px solid #ccc; padding-right: 2px; line-height:10px;">Total Invoice Value</td>
						<td style="width:10%; line-height:10px; border-right:1px solid #ccc; padding: 2px; border-bottom:1px solid #ccc; text-align:right;"><?= round($gt)?></td>
					</tr>
					
					<?php
						if($paid_amount < $gt){
							if($last_recieved > 0){
					?>
					<tr>
						<td style="text-align: right; border-right:1px solid #ccc; padding: 2px; padding-right: 2px; line-height:10px;">Previous Payment Received</td>
						<td style="width:10%; border-right:1px solid #ccc; padding: 2px; text-align:right; line-height:10px;"><?= round($last_recieved)?></td>
					</tr>
					<?php } ?>
					<tr>
						<td style="text-align: right; border-right:1px solid #ccc; padding: 2px; padding-right: 2px; line-height:10px;">Current Payment Received</td>
						<td style="width:10%; border-right:1px solid #ccc; padding: 2px; text-align:right; line-height:10px;"><?= round($paid_amount)?></td>
					</tr>
					<tr>
						<td style="text-align: right; border-right:1px solid #ccc;  padding: 2px; padding-right: 3px; border-bottom:1px solid #ccc; line-height:10px;">Balance Due</td>
						<td style="width:10%; border-right:1px solid #ccc; padding: 2px; text-align:right; border-bottom:1px solid #ccc; line-height:10px;"><?= $gt - round($paid_amount+$last_recieved)?></td>
					</tr>
					<?php } ?>
					
				</tbody>

			</table>
			<p style="width:100%; margin-top: 2px; display: block; text-align: left; border-bottom: 1px solid #ccc; padding-bottom: 10px; margin-bottom: 3px; ">
				<!-- <span style="display: block; vertical-align: baseline;  line-height: 18px; ">Amount Chargeable (in words): <strong><?= getIndianCurrency($paid_amount)?></strong></span>
				<span style="display: block; vertical-align: baseline;  line-height: 18px; ">Tax Amount (in words): <strong><?=getIndianCurrency($orderDetails['gst_amount'])?></strong></span> -->
				<span style="display: block; margin-top: 2px;  font-weight: 600; text-decoration: none; vertical-align: baseline;  line-height: 18px;  font-weight: 600;">Company`s Bank Details:</span>
				<span style="display: block; vertical-align: baseline; line-height:10px;">Bank Name:Axis Bank </span>
				<span style="display: block; vertical-align: baseline; line-height:10px;">A/c No:920020067249188 </span>
				<span style="display: block; vertical-align: baseline; line-height:10px;">Branch & IFS Code:Tri Nagar, New Delhi & UTIB0001150</span>
			</p>

			<p style="margin-top: 5px; text-align: left; padding-bottom: 5px; margin-bottom: 3px;">
				<span style="display: block; border-left: 3px solid #3e3f95; padding-left: 10px;vertical-align: baseline;">Declaration:<br> We declare that this invoice shows the actual price of the goods described and that all particulars are
					true and correct.</span>
			</p>
			<div style="text-align: right; display:block; margin-bottom: 5px; width: 100%;">
				<span style="margin:0px; border:0; width: 150.00px; height: 58.59px; float:right;">
					<img src="<?= $sign_img;?>" style="width: 150.00px; height: 58.59px;" >
					<br>
					<br>
					<span style=" width: 100%; text-align: right; vertical-align: baseline;  line-height: 18px; ">Authorised Signatory</span>
				</span>

			</div>
			<br>
			<br>
		
        </div>
    </body>
</html>
		<?php
		return ob_get_clean();
	} 

?>