<?php include_once('database_connection.php');
if(isset($_GET['action']))
{

$ProductBaseType=isset($_GET['ProductBaseType'])?$_GET['ProductBaseType']:'';

if($_GET['action']=="getRoomBooking")
{

	$mt=$_GET['mt'];//get month 
	$yt=$_GET['yt'];
	$RoomID=$_GET['RoomTypeID'];
	$condition=$_GET['condition'];

	$GodownID=(isset($_GET['CompanyID']) && $_GET['CompanyID']>0)?$_GET['CompanyID']:0;
	if($GodownID>0)
	{
		$GodownID=" and CompanyID=".$GodownID." ";
	}
	else
	{
		$GodownID="";
	}
	
	$dtarray=array();
	$maxdate=array(31,28,31,30,31,30,31,31,30,31,30,31);
		$md=$maxdate[$mt-1];
		$EndDate=$yt."-".$mt."-".$md;
		$StartDate=$yt."-".$mt."-"."01";
//$StartDate = date('Y-m-d H:i:s', strtotime('-7 day', $StartDate));


$RoomTypeSum=getSum("inventory","count(ID) as sum","Under",$RoomID,$connection);

$Rm=getnamewhere("inventory","count(ID) as sum","Under=".$RoomID."  ".$condition."",$connection);
$Rm=json_decode($Rm);
$RoomTypeSum=$Rm->sum;

	for($c=1;$c<=$md;$c++)
	{
		$dtarray[$c-1]=$RoomTypeSum;
	}
	//select ID from inventory where under=
	    $sql="select ide.* from invoicemaster as im inner join InvoiceDetail as ide on im.InvoiceID=ide.InvoiceID where  (ide.itemid in (select ID from Inventory where (Under=$RoomID or ID=$RoomID) $GodownID)) and ide.Invoicedate>'$StartDate' and ide.duedate<'$EndDate'  order by invoicedate";
	$result=odbc_exec($connection,$sql);
	while($row=odbc_fetch_array($result))
	{
		$InvoiceDate=$row['InvoiceDate'];
		$startdate=date_create($InvoiceDate);
		 $sd=date_format($startdate,"d");
		$DueDate=$row['DueDate'];
		$qty=$row['QTY'];
		$DueDate=date_create($DueDate);
		 $dd=date_format($DueDate,"d");
		for($a=$sd;$a<$dd;$a++)
		{
				$dtarray[$a-1]=($dtarray[$a-1]-$qty);
		}
	}
	//print_r($dtarray);
	echo json_encode($dtarray);
	//return;

}
if($_GET['action']=="TotalCheckOut")
{

	$mt=$_GET['mt'];//get month 
	$yt=$_GET['yt'];
	$dt=$_GET['dt'];
	$RoomID=$_GET['RoomTypeID'];

$EndDate=$yt."-".$mt."-".($dt+1);
		$StartDate=$yt."-".$mt."-".($dt+1);

      $data= array();
      if(isset($_GET['RoomTypeID']) && $_GET['RoomTypeID']!="" && $_GET['RoomTypeID']!="undefined" && $_GET['RoomTypeID']>0)
	{
		$RoomTypeID=" Under=".$_GET['RoomTypeID']." and ";
	}
	else
	{
		$RoomTypeID="";
	}
      if(isset($_GET['Under']) && $_GET['Under']!="")
    {
        $Category=$_GET['Under'];
        $Under=" Under=".$_GET['Under']." and ";
    }
    else
    {
      $Under="";
    }
      if(isset($_GET['CompanyID']) && $_GET['CompanyID']!="" && $_GET['CompanyID']!="undefined" && $_GET['CompanyID']>0)
    {
        $CompanyID=" CompanyID=".$_GET['CompanyID']." and ";
    }
    else
    {
      $CompanyID="";
    }
    //itemid=$Category or
//    $StartDate=isset($_GET['StartDate'])?$_GET['StartDate']:'';
  //  $EndDate=isset($_GET['EndDate'])?$_GET['EndDate']:'';
    $searchbox="".$Under.$CompanyID.$RoomTypeID;

  $sql="select (select count(*) from inventory where $searchbox [group]=0 and active=1 and ProductBaseType='Property') as Total1,count(*) as Total from InvoiceDetail where invoiceid in (select InvoiceID from InvoiceMaster where  InvoiceType=5 and Duedate=convert(date,'$StartDate') ) and (itemid in (select ID from inventory where $searchbox    ProductBaseType='Property')) ";
	
	//$sql="select count(*) as Total from invoicemaster as im inner join InvoiceDetail as ide on im.InvoiceID=ide.InvoiceID where  ide.itemid=$RoomID and Invoicedate>='$StartDate' and duedate<='$EndDate' and InvoiceStatus not in (3)";
	$result=odbc_exec($connection,$sql);
	while($row=odbc_fetch_array($result))
	{

  	    $data []=$row;
  	}
  	  		echo json_encode($data); 




}
if($_GET['action']=="TotalCheckIN")
{

	$mt=$_GET['mt'];//get month 
	$yt=$_GET['yt'];
	$dt=$_GET['dt'];
	$RoomID=$_GET['RoomTypeID'];

$EndDate=$yt."-".$mt."-".($dt+1);
		$StartDate=$yt."-".$mt."-".($dt+1);

      $data= array();
if(isset($_GET['RoomTypeID']) && $_GET['RoomTypeID']!="" && $_GET['RoomTypeID']!="undefined" && $_GET['RoomTypeID']>0)
	{
		$RoomTypeID=" Under=".$_GET['RoomTypeID']." and ";
	}
	else
	{
		$RoomTypeID="";
	}      
      if(isset($_GET['Under']) && $_GET['Under']!="")
    {
        $Category=$_GET['Under'];
        $Under=" Under=".$_GET['Under']." and ";
    }
    else
    {
      $Under="";
    }
      if(isset($_GET['CompanyID']) && $_GET['CompanyID']!="" && $_GET['CompanyID']>0)
    {
        $CompanyID=" CompanyID=".$_GET['CompanyID']." and ";
    }
    else
    {
      $CompanyID="";
    }
    //itemid=$Category or
//    $StartDate=isset($_GET['StartDate'])?$_GET['StartDate']:'';
  //  $EndDate=isset($_GET['EndDate'])?$_GET['EndDate']:'';
    $searchbox="".$Under.$CompanyID.$RoomTypeID;

  $sql="select (select count(*) from inventory where $searchbox [group]=0 and active=1 and ProductBaseType='Property') as Total1,count(*) as Total from InvoiceDetail where invoiceid in (select InvoiceID from InvoiceMaster where  InvoiceType=5 and InvoiceDate=convert(date,'$StartDate') ) and (itemid in (select ID from inventory where $searchbox    ProductBaseType='Property')) ";
	
	//$sql="select count(*) as Total from invoicemaster as im inner join InvoiceDetail as ide on im.InvoiceID=ide.InvoiceID where  ide.itemid=$RoomID and Invoicedate>='$StartDate' and duedate<='$EndDate' and InvoiceStatus not in (3)";
	$result=odbc_exec($connection,$sql);
	while($row=odbc_fetch_array($result))
	{

  	    $data []=$row;
  	}
  	  		echo json_encode($data); 


}

if($_GET['action']=="getRoomReservationTotal")
{
	$mt=$_GET['mt'];//get month 
	$yt=$_GET['yt'];
	$dt=$_GET['dt'];
	$RoomID=$_GET['RoomTypeID'];

$EndDate=$yt."-".$mt."-".($dt);
		$StartDate=$yt."-".$mt."-".($dt);

      $data= array();
      if(isset($_GET['Under']) && $_GET['Under']!="")
    {
        $Category=$_GET['Under'];
        $Under=" Under=".$_GET['Under']." and ";
    }
    else
    {
      $Under="";
    }
    if(isset($_GET['RoomTypeID']) && $_GET['RoomTypeID']!="" && $_GET['RoomTypeID']!="undefined" && $_GET['RoomTypeID']>0)
	{
		$RoomTypeID=" (Under=".$_GET['RoomTypeID']." or ID=".$_GET['RoomTypeID'].")   and ";
	}
	else
	{
		$RoomTypeID="";
	}

	//$searchbox=$RoomTypeID;
      if(isset($_GET['CompanyID']) && $_GET['CompanyID']!="" && $_GET['CompanyID']!="undefined" && $_GET['CompanyID']>0)
    {
        $CompanyID=" BranchID=".$_GET['CompanyID']." and ";
    }
    else
    {
      $CompanyID="";
    }
    //itemid=$Category or
//    $StartDate=isset($_GET['StartDate'])?$_GET['StartDate']:'';
  //  $EndDate=isset($_GET['EndDate'])?$_GET['EndDate']:'';
    $searchbox="".$Under.$RoomTypeID;
    $searchbox2=$CompanyID;
   $sql="select (select count(*) from inventory where $searchbox [group]=0 and active=1 and ProductBaseType='Property') as Total1,count(*) as Total from InvoiceDetail where $CompanyID invoiceid in (select InvoiceID from InvoiceMaster where  InvoiceType=5 and active=1) and ((InvoiceDate>convert(date,'$StartDate') and  Duedate<convert(date,'$EndDate')) or (DueDate>convert(date,'$StartDate') and InvoiceDate<=convert(date,'$EndDate'))) and (itemid in (select ID from inventory where $searchbox    ProductBaseType='Property')) ";
	
	//$sql="select count(*) as Total from invoicemaster as im inner join InvoiceDetail as ide on im.InvoiceID=ide.InvoiceID where  ide.itemid=$RoomID and Invoicedate>='$StartDate' and duedate<='$EndDate' and InvoiceStatus not in (3)";
	$result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
	while($row=odbc_fetch_array($result))
	{

  	    $data []=$row;
  	}
  	  		echo json_encode($data); 

}
if($_GET['action']=="getRoomTotal")
{
	$data=array();
	if(isset($_GET['RoomTypeID']) && $_GET['RoomTypeID']!="" && $_GET['RoomTypeID']!="undefined" && $_GET['RoomTypeID']>0)
	{
		$RoomTypeID=" Under=".$_GET['RoomTypeID']." and ";
	}
	else
	{
		$RoomTypeID="";
	}
	 if(isset($_GET['CompanyID']) && $_GET['CompanyID']!="" && $_GET['CompanyID']!="undefined" && $_GET['CompanyID']>0)
    {
        $CompanyID=" CompanyID=".$_GET['CompanyID']." and ";
    }
    else
    {
      $CompanyID="";
    }
	$searchbox=$RoomTypeID.$CompanyID;
	$sql="select count(*) as Total from inventory where $searchbox active=1 and ProductBaseType='Property' and [group]=0";
	$result=odbc_exec($connection,$sql);
	while ($row = odbc_fetch_array($result)) 
  	{
  		/*foreach ($row as $key => $value) {
  			$row[$key]=utf8_encode($value);
  		}*/
  	    $data []=$row;
  	}
  	  		echo json_encode($data); 
}

if($_GET['action']=="getBooking")
{
	$mt=$_GET['mt'];//get month 
	$yt=$_GET['yt'];
	$RoomID=$_GET['RoomID'];
	$dtarray=array();
	$maxdate=array(31,28,31,30,31,30,31,31,30,31,30,31);
		$md=$maxdate[$mt-1];
		$EndDate=$yt."-".$mt."-".$md;
		$StartDate=$yt."-".$mt."-"."01";


	for($c=1;$c<=$md;$c++)
	{
		$dtarray[$c-1]="A";
	}
	 $sql="select ide.InvoiceDate as InvoiceDate,ide.DueDate as DueDate from invoicemaster as im inner join InvoiceDetail as ide on im.InvoiceID=ide.InvoiceID where  ide.itemid=$RoomID and ide.Invoicedate>='$StartDate' and ide.duedate<='$EndDate' and InvoiceStatus not in (3) order by ide.invoicedate";
	$result=odbc_exec($connection,$sql);
	while($row=odbc_fetch_array($result))
	{
		$InvoiceDate=$row['InvoiceDate'];
		$startdate=date_create($InvoiceDate);
		 $sd=date_format($startdate,"d");
		$DueDate=$row['DueDate'];
		$DueDate=date_create($DueDate);
		 $dd=date_format($DueDate,"d");
		for($a=$sd;$a<$dd;$a++)
		{
				$dtarray[$a-1]='D';
		}
	}
	//print_r($dtarray);
	echo json_encode($dtarray);
	//return;
}
if($_GET['action']=="RoomsAvailable")
{



//i.ProductBaseType='".$ProductBaseType."'
	   $data=array();
	   $ProductID="";
	   $BillDate=    isset($_GET['StartDate'])?$_GET['StartDate']:'';
       $DeliveryDate=    isset($_GET['EndDate'])?$_GET['EndDate']:'';
          /*  if($BillDate!="" && $BillDate!="undefined")
            {
            	if($DeliveryDate=="")
            	{
            		$BillDate=" ide.InvoiceDate='".$BillDate."' and ";
            	}
             	else
             	{

             	$BillDate=" ide.InvoiceDate>='".$BillDate."' and ";
             	}	
            $tokendate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            if($DeliveryDate!="" && $DeliveryDate!="undefined")
            {
            	if($BillDate=="")
            	{
           $DeliveryDate=" ide.Duedate='".$DeliveryDate."' and ";
            	}
            	else
            	{

             $DeliveryDate=" ide.Duedate<='".$DeliveryDate."' and ";
            	}
             
            }
            else
            {
            $DeliveryDate=""; 
            }*/
            if($DeliveryDate!="" && $BillDate!="")
            {
            	$Date="(ide.InvoiceDate>='$BillDate' and   ide.Duedate<='$DeliveryDate') or (ide.InvoiceDate<='$DeliveryDate' and   ide.Duedate>='$BillDate') and ";
            }
	   if(isset($_GET['ProductBaseType']) && $_GET['ProductBaseType']!="" && $_GET['ProductBaseType']!="undefined")
	   {
	   	$ProductBaseType="i.ProductBaseType='".$_GET['ProductBaseType']."' and ";
	   }
	   else
	   {
	   	$ProductBaseType="i.ProductBaseType='Property' and ";
	   }
	   if(isset($_GET['Under']) && $_GET['Under']!="" && $_GET['Under']!="undefined")
	   {
	   	$ProductID="i.under=".$_GET['Under']." and ";
	   }
	   else
	   {
	   	$ProductID="";
	   }
	   	   if(isset($_GET['GodownID']) && $_GET['GodownID']!="" && $_GET['GodownID']!="undefined" && $_GET['GodownID']>0)
	   {
	   	$GodownID="i.CompanyID=".$_GET['GodownID']." and ";
	   }
	   else
	   {
	   	$GodownID="";
	   }

	   if(isset($_GET['Floor']) && $_GET['Floor']!="" && $_GET['Floor']!="undefined")
	   {
	   	$Floor="i.AdditionalInfo1=".$_GET['Floor']." and ";
	   }
	   else
	   {
	   	$Floor="";
	   }
	 if(isset($_GET['Status']) && $_GET['Status']!="" && $_GET['Status']!="undefined")
	   {
	   	$Status="i.Model='".$_GET['Status']."' and ";
	   }
	   else
	   {
	   	$Status="";
	   }
//	   $searchbox=$ProductBaseType."".$ProductID."".$Status.$BillDate.$DeliveryDate.$Floor.$GodownID;
	   $searchbox=$ProductBaseType."".$Date;//.$BillDate.$DeliveryDate;
	   $searchbox2="".$ProductID."".$Status.$Floor.$GodownID;
	     $sql="select   i.under as under,ROW_NUMBER() OVER (
      PARTITION BY i.[ID]
      ORDER BY i.[ID]
   ) row_num, i.Name as ItemName,inv.Name as ProductCategoryName,i.degree as level,i.AdditionalInfo2 as Code,i.Make as Brand,i.Rating as Color,i.Model as Size,g.Name as Project,i.KeyField as KeyField,
   g.AdditionalInfo1 as CompanyShortForm,i.CompanyID as CompanyId ,i.ProductBaseType as ProductBaseType,i.ID as ItemID,i.StandardPrice2 as MonthlyRent,i.StandardPrice3 as Deposit, 
   '' as StartDate,'' as EndDate,0 as Rent,0 as InvoiceID  ,'' as CustomerName,0
    as MobileNumber,0 as Passport,i.AdditionalInfo1 as Floor from inventory as i
   left outer join Inventory as inv on i.Under=Inv.ID
   left outer join Godowns as g  on i.CompanyID=g.godownid
      where $searchbox2 i.ProductBaseType='Property'  and i.[group]=0 and  i.ID not in (select itemid from invoicedetail as ide where $searchbox 1=1)
      order by i.[group],i.under
";
/*
((im.Invoicedate>=getdate() and im.duedate<=getdate()+3) or (im.Invoicedate>=getdate()+2 and im.duedate<=getdate()+10))
*/
      //and (Im.Invoicestatus is null or (InvoiceStatus not in (3,4)))
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  	while ($row = odbc_fetch_array($result)) 
  	{
  		foreach ($row as $key => $value) {
  			$row[$key]=utf8_encode($value);
  		}
  	    $data []=$row;
  	}
  	  		echo json_encode($data); 



}
if($_GET['action']=="ListofRooms")
{


	//i.ProductBaseType='".$ProductBaseType."'
	   $data=array();
	   $ProductID="";
	   $BillDate=    isset($_GET['StartDate'])?$_GET['StartDate']:'';
       $DeliveryDate=    isset($_GET['EndDate'])?$_GET['EndDate']:'';
            if($BillDate!="" && $BillDate!="undefined")
            {
            	if($DeliveryDate=="")
            	{
            		$BillDate=" ide.InvoiceDate='".$BillDate."' and ";
            	}
             	else
             	{

             	$BillDate=" ide.InvoiceDate>='".$BillDate."' and ";
             	}	
            $tokendate=""; 
            }
            else
            {
            $BillDate=""; 
            }
            if($DeliveryDate!="" && $DeliveryDate!="undefined")
            {
            	if($BillDate=="")
            	{
           $DeliveryDate=" ide.Duedate='".$DeliveryDate."' and ";
            	}
            	else
            	{

             $DeliveryDate=" ide.Duedate<='".$DeliveryDate."' and ";
            	}
             
            }
            else
            {
            $DeliveryDate=""; 
            }
	   if(isset($_GET['ProductBaseType']) && $_GET['ProductBaseType']!="" && $_GET['ProductBaseType']!="undefined")
	   {
	   	$ProductBaseType="i.ProductBaseType='".$_GET['ProductBaseType']."' and ";
	   }
	   else
	   {
	   	$ProductBaseType="i.ProductBaseType='Property' and ";
	   }
	   if(isset($_GET['Under']) && $_GET['Under']!="" && $_GET['Under']!="undefined")
	   {
	   	$ProductID="i.under=".$_GET['Under']." and ";
	   }
	   else
	   {
	   	$ProductID="";
	   }
	   	   if(isset($_GET['GodownID']) && $_GET['GodownID']!="" && $_GET['GodownID']!="undefined" && $_GET['GodownID']>0)
	   {
	   	$GodownID="i.CompanyID=".$_GET['GodownID']." and ";
	   }
	   else
	   {
	   	$GodownID="";
	   }

	   if(isset($_GET['Floor']) && $_GET['Floor']!="" && $_GET['Floor']!="undefined")
	   {
	   	$Floor="i.AdditionalInfo1=".$_GET['Floor']." and ";
	   }
	   else
	   {
	   	$Floor="";
	   }
	 if(isset($_GET['Status']) && $_GET['Status']!="" && $_GET['Status']!="undefined")
	   {
	   	$Status="i.Model='".$_GET['Status']."' and ";
	   }
	   else
	   {
	   	$Status="";
	   }
	   if($DeliveryDate!="" && $BillDate!="")
            {
            	$Date="((ide.InvoiceDate>='$BillDate' and   ide.Duedate<='$DeliveryDate') or (ide.InvoiceDate<='$DeliveryDate' and   ide.Duedate>='$BillDate')) and ";
            }
            else
            	$Date="";
           //$BillDate.$DeliveryDate 
            
/*            if($Date!="")
	   $searchbox=$ProductBaseType."".$ProductID."".$Status.$Date.$Floor.$GodownID;
		else*/
$searchbox=$ProductBaseType."".$ProductID."".$Status.$BillDate.$DeliveryDate.$Floor.$GodownID;

	    $sql=" select   i.under as under,ROW_NUMBER() OVER (
      PARTITION BY i.[ID]
      ORDER BY i.[ID]
   ) row_num, i.Name as ItemName,inv.Name as ProductCategoryName,i.degree as level,i.AdditionalInfo2 as Code,i.Make as Brand,i.Rating as Color,i.Model as Size,g.Name as Project,im.KeyField as KeyField,
   g.AdditionalInfo1 as CompanyShortForm,i.CompanyID as CompanyId ,i.ProductBaseType as ProductBaseType,i.ID as ItemID,i.StandardPrice2 as MonthlyRent,i.StandardPrice3 as Deposit, 
   convert(date,ide.InvoiceDate) as StartDate,CONVERT(DATE,ide.DueDate) as EndDate,ide.NetAmount as Rent,im.Paid as Paid,im.InvoiceID as InvoiceID  ,im.CustomerName as CustomerName,im.MobileNumber as MobileNumber,im.chassisNumber as Passport,i.AdditionalInfo1 as Floor from inventory as i
   left outer join Inventory as inv on i.Under=Inv.ID
   left outer join InvoiceDetail as ide on ide.ItemID=I.ID
   left outer join InvoiceMaster as im on im.InvoiceID=Ide.InvoiceID   
   left outer join Godowns as g  on i.CompanyID=g.godownid
      where $searchbox  i.ProductBaseType='Property' and i.[group]=0 and (Im.Invoicestatus is null or InvoiceStatus not in (3))
      order by i.[group],i.under
";
/*
((im.Invoicedate>=getdate() and im.duedate<=getdate()+3) or (im.Invoicedate>=getdate()+2 and im.duedate<=getdate()+10))
*/
      //and (Im.Invoicestatus is null or (InvoiceStatus not in (3,4)))
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  	while ($row = odbc_fetch_array($result)) 
  	{
  		foreach ($row as $key => $value) {
  			$row[$key]=utf8_encode($value);
  		}
  	    $data []=$row;
  	}
  	  		echo json_encode($data); 


}
if($_GET['action']=="ListofProperties")
{

	//i.ProductBaseType='".$ProductBaseType."'
	   $data=array();
	   $ProductID="";
	   if(isset($_GET['ProductBaseType']) && $_GET['ProductBaseType']!="")
	   {
	   	$ProductBaseType="i.ProductBaseType='".$_GET['ProductBaseType']."' and ";
	   }
	   else
	   {
	   	$ProductBaseType="";
	   }
	   if(isset($_GET['ProductID']) && $_GET['ProductID']!="")
	   {
	   	$ProductID="";//i.under=".$_GET['ProductID']." and ";
	   }
	   else
	   {
	   	$ProductID="";
	   }
	 if(isset($_GET['Status']) && $_GET['Status']!="" && $_GET['Status']!="undefined")
	   {
	   	$Status="i.Model='".$_GET['Status']."' and ";
	   }
	   else
	   {
	   	$Status="";
	   }
	   $searchbox=$ProductBaseType."".$ProductID."".$Status;
	   $sql="select   i.under as under,ROW_NUMBER() OVER (
      PARTITION BY i.[under]
      ORDER BY i.[under]
   ) row_num,i.Name as ItemName,inv.Name as ProductCategoryName,
   i.degree as level1,i.AdditionalInfo2 as Code,
   0 as BuildingBlock,g.Name as Project,
   g.AdditionalInfo1 as CompanyShortForm,i.CompanyID as CompanyId ,i.ProductBaseType as ProductBaseType,i.ID as ItemID,i.StandardPrice2 as MonthlyRent,i.StandardPrice3 as Deposit, 
   0 as PropertyType,0 as PropertyNature,0 as LuxuryType,
   convert(date,InvoiceDate) as StartDate,CONVERT(DATE,DueDate) as EndDate,im.NetAmount as Rent,im.InvoiceID from inventory as i
   left outer join Inventory as inv on i.Under=Inv.ID
   left outer join InvoiceDetail as ide on ide.ItemID=I.ID
   left outer join InvoiceMaster as im on im.InvoiceID=Ide.InvoiceID
   left outer join Godowns as g  on i.CompanyID=g.godownid 
   left outer join Master_Values  as mv  on convert(numeric,i.Attr20)=mv.MasterValueID
   left outer join Master_Values  as mv1  on convert(numeric,i.additionalinfo2)=mv1.MasterValueID
   left outer join Master_Values  as mv2  on convert(numeric,i.additionalinfo5)=mv2.MasterValueID
   left outer join Master_Values  as mv3  on convert(numeric,i.AdditionalInfo3)=mv3.MasterValue
       
   where $searchbox convert(date,InvoiceDate)='".Date("Y-m-d")."'
      order by i.[group],i.under
";
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  	while ($row = odbc_fetch_array($result)) 
  	{
  		foreach ($row as $key => $value) {
  			$row[$key]=utf8_encode($value);
  		}
  	    $data []=$row;
  	}
  	  		echo json_encode($data); 

}
if($_GET['action']=="ListProducts")
{
	//i.ProductBaseType='".$ProductBaseType."'
	   $data=array();
	   $ProductID="";
	   if(isset($_GET['ProductBaseType']) && $_GET['ProductBaseType']!="")
	   {
	   	$ProductBaseType="i.ProductBaseType='".$_GET['ProductBaseType']."' and ";
	   }
	   else
	   {
	   	$ProductBaseType="";
	   }
	   if(isset($_GET['ProductID']) && $_GET['ProductID']!="")
	   {
	   	$ProductID="i.under=".$_GET['ProductID']." and ";
	   }
	   else
	   {
	   	$ProductID="";
	   }

	   $searchbox=$ProductBaseType."".$ProductID;
	$sql="  select   i.under as under,ROW_NUMBER() OVER (
      PARTITION BY i.[under]
      ORDER BY i.[under]
   ) row_num,i.Name as ItemName,inv.Name as ProductCategoryName,i.degree as level,i.AdditionalInfo2 as Code,i.Make as Brand,i.Rating as Color,i.Model as Size,
   g.AdditionalInfo1 as CompanyShortForm,i.CompanyID as CompanyId ,i.ProductBaseType as ProductBaseType,i.ID from inventory as i
   left outer join Inventory as inv on i.Under=Inv.ID
   inner join Godowns as g  on i.CompanyID=g.godownid where $searchbox 1=1
      order by i.[group],i.under
";
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  	while ($row = odbc_fetch_array($result)) 
  	{
  		foreach ($row as $key => $value) {
  			$row[$key]=utf8_encode($value);
  		}
  	    $data []=$row;
  	}
  	  		echo json_encode($data); 
}
if($_GET['action']=="GetProductsRoom")
{


		if(isset($_GET['ID']))
		{
			$ID=$_GET['ID'];
$sql="select Name as ItemName,Under as ProductCategoryID,AdditionalInfo2 as Code,Make as Brand,Rating as Color,Model as Size,CompanyID as CompanyID,'' as col_Action,ID,UnitID,Attr1,AdditionalInfo3,AdditionalInfo5,Barcode,cast(StandardPrice3 as numeric) as CostPrice,cast(StandardPrice2 as numeric) as WholeSalePrice,cast(StandardPrice1 as numeric) as RetailPrice,cast(MinPriceLevel as numeric) as MinPriceLevel,cast(CommisionPercent as numeric) as CommisionPercent,cast(CommisionAmount as numeric) as CommisionAmount,cast(MinQtyLevel as numeric) as MinQtyLevel,cast(MaxQtyLevel as numeric) as MaxQtyLevel,KeyField,ShowInSales as ShowInSales,ShowInStock as ShowInStock,ShowInPurchases as ShowInPurchases,IsFixedAsset as IsFixedAsset,Details,LastModificationTimeStamp,cast(VATPercent as numeric) as VATPercent,AdditionalInfo2,AdditionalInfo1,KeyField from inventory where ID=$ID";// offset $start rows fetch next $limit rows only";
		}
		else
		{
		$start=0;
		$limit=20;
				if(isset($_GET['ItemName']) && $_GET['ItemName']!="")
		$ItemName="i.Name like '%".$_GET['ItemName']."%' and ";
		else
		$ItemName="";

		if(isset($_GET['CompanyID']) && $_GET['CompanyID']!="" && $_GET['CompanyID']!="undefined" && $_GET['CompanyID']>0)
		$CompanyID=" i.CompanyID=".$_GET['CompanyID']." and ";
		else
		$CompanyID="";

		if(isset($_GET['Under']) && $_GET['Under']!="")
		$Under="i.Under=".$_GET['Under']."   and ";
		else
		$Under="";
		//	
		if(isset($_GET['Code']) && $_GET['Code']!="")
		$Code="i.AdditionalInfo2 like '%".$_GET['Code']."%' and ";
		else
		$Code="";

		if(isset($_GET['Size']) && $_GET['Size']!="" && $_GET['Size']>0)
		$Size="i.Size like '%".$_GET['Size']."%' and ";
		else
		$Size="";

		if(isset($_GET['AdditionalInfo5']) && $_GET['AdditionalInfo5']!="" && $_GET['AdditionalInfo5']>0)
		$AdditionalInfo5="i.AdditionalInfo5 like '%".$_GET['AdditionalInfo5']."%' and ";
		else
		$AdditionalInfo5="";
		//i.AdditionalInfo5	
		$searchbox=$ItemName."".$Under."".$Code."".$Size."".$AdditionalInfo5."".$CompanyID;
		 $sql="  select   ROW_NUMBER() OVER (
      ORDER BY i.[ID]
   ) row_num,i.Name as ItemName,inv.Name as ProductCategoryName,i.under,i.AdditionalInfo2 as Code,i.Make as Brand,i.Rating as Color,i.AdditionalInfo1 as Part,i.Model as Size,
   g.AdditionalInfo1 as CompanyShortForm,i.CompanyID as CompanyId ,'' as col_Action,i.ID,i.ShowInSales as ShowInSales,i.ShowInStock as ShowInStock,i.ShowInPurchases as ShowInPurchases,i.IsFixedAsset as IsFixedAsset,'' as col_Action,i.* from  inventory as i
   inner join Inventory as inv on i.Under=Inv.ID
   inner join Godowns as g  on i.CompanyID=g.godownid
    where $searchbox i.[group]=0 and i.active=1 and   i.ProductBaseType='".$ProductBaseType."' order by i.CompanyID
";// offset $start rows fetch next $limit rows only";
		}

   $data=array();
//echo $sql;
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  while ($row = odbc_fetch_array($result)) {
        $row['col_Action']='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this,'.$row["ID"].');"></i>&nbsp;&nbsp;&nbsp;  <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this,'.$row["ID"].');"></i>';
        foreach ($row as $key => $value) {
        	# code...
        	$row[$key]=utf8_encode($value);
        }
      //  $row['ItemName']=htmlspecialchars($row['ItemName']);
      //  $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
      //  $row['Code']=htmlentities($row['Code']);

    $data []=$row;
  		}//end while
  		//print_r($data);
  		echo json_encode($data); 

	

}
if($_GET['action']=="GetProducts")
{

		if(isset($_GET['ID']))
		{
			$ID=$_GET['ID'];
$sql="select Name as ItemName,Under as ProductCategoryID,AdditionalInfo2 as Code,Make as Brand,Rating as Color,Model as Size,CompanyID as CompanyID,'' as col_Action,ID,UnitID,Attr1,AdditionalInfo3,AdditionalInfo5,Barcode,cast(StandardPrice3 as numeric) as CostPrice,cast(StandardPrice2 as numeric) as WholeSalePrice,cast(StandardPrice1 as numeric) as RetailPrice,cast(MinPriceLevel as numeric) as MinPriceLevel,cast(CommisionPercent as numeric) as CommisionPercent,cast(CommisionAmount as numeric) as CommisionAmount,cast(MinQtyLevel as numeric) as MinQtyLevel,cast(MaxQtyLevel as numeric) as MaxQtyLevel,KeyField,ShowInSales as ShowInSales,ShowInStock as ShowInStock,ShowInPurchases as ShowInPurchases,IsFixedAsset as IsFixedAsset,Details,LastModificationTimeStamp,cast(VATPercent as numeric) as VATPercent,AdditionalInfo2,AdditionalInfo1,KeyField from inventory where ID=$ID";// offset $start rows fetch next $limit rows only";
		}
		else
		{
		$start=0;
		$limit=20;
				if(isset($_GET['ItemName']) && $_GET['ItemName']!="")
		$ItemName="i.Name like '%".$_GET['ItemName']."%' and ";
		else
		$ItemName="";

		if(isset($_GET['CompanyID']) && $_GET['CompanyID']!="")
		$CompanyID=" i.CompanyID=".$_GET['CompanyID']." and ";
		else
		$CompanyID="";

		if(isset($_GET['Under']) && $_GET['Under']!="")
		$Under="i.Under=".$_GET['Under']." and ";
		else
		$Under="";
		//	
		if(isset($_GET['Code']) && $_GET['Code']!="")
		$Code="i.AdditionalInfo2 like '%".$_GET['Code']."%' and ";
		else
		$Code="";

		if(isset($_GET['Size']) && $_GET['Size']!="" && $_GET['Size']>0)
		$Size="i.Size like '%".$_GET['Size']."%' and ";
		else
		$Size="";

		if(isset($_GET['AdditionalInfo5']) && $_GET['AdditionalInfo5']!="" && $_GET['AdditionalInfo5']>0)
		$AdditionalInfo5="i.AdditionalInfo5 like '%".$_GET['AdditionalInfo5']."%' and ";
		else
		$AdditionalInfo5="";
		//i.AdditionalInfo5	
		$searchbox=$ItemName."".$Under."".$Code."".$Size."".$AdditionalInfo5."".$CompanyID;
		$sql="  select   ROW_NUMBER() OVER (
      ORDER BY i.[ID]
   ) row_num,i.Name as ItemName,inv.Name as ProductCategoryName,i.under,i.AdditionalInfo2 as Code,i.Make as Brand,i.Rating as Color,i.AdditionalInfo1 as Part,i.Model as Size,
   g.AdditionalInfo1 as CompanyShortForm,i.CompanyID as CompanyId ,'' as col_Action,i.ID,i.ShowInSales as ShowInSales,i.ShowInStock as ShowInStock,i.ShowInPurchases as ShowInPurchases,i.IsFixedAsset as IsFixedAsset,'' as col_Action from  inventory as i
   inner join Inventory as inv on i.Under=Inv.ID
   inner join Godowns as g  on i.CompanyID=g.godownid
    where $searchbox i.[group]=0 and i.active=1 and   i.ProductBaseType='".$ProductBaseType."' order by i.CompanyID
";// offset $start rows fetch next $limit rows only";
		}

   $data=array();
//echo $sql;
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  while ($row = odbc_fetch_array($result)) {
        $row['col_Action']='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this,'.$row["ID"].');"></i>&nbsp;&nbsp;&nbsp;  <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this,'.$row["ID"].');"></i>';
        foreach ($row as $key => $value) {
        	# code...
        	$row[$key]=utf8_encode($value);
        }
      //  $row['ItemName']=htmlspecialchars($row['ItemName']);
      //  $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
      //  $row['Code']=htmlentities($row['Code']);

    $data []=$row;
  		}//end while
  		//print_r($data);
  		echo json_encode($data); 

	
}
	if($_GET['action']=="GetProducts2")
	{
		if(isset($_GET['ID']))
		{
			$ID=$_GET['ID'];
$sql="select Name as ItemName,(select Name from Inventory as inv where inv.id=inventory.Under) as ProductCategoryID,AdditionalInfo2 as Code,Make as Brand,Rating as Color,Model as Size,CompanyID as CompanyID,'' as col_Action,ID,UnitID,Attr1,AdditionalInfo3,AdditionalInfo5,Barcode,cast(StandardPrice3 as numeric) as CostPrice,cast(StandardPrice2 as numeric) as WholeSalePrice,cast(StandardPrice1 as numeric) as RetailPrice,cast(MinPriceLevel as numeric) as MinPriceLevel,cast(CommisionPercent as numeric) as CommisionPercent,cast(CommisionAmount as numeric) as CommisionAmount,cast(MinQtyLevel as numeric) as MinQtyLevel,cast(MaxQtyLevel as numeric) as MaxQtyLevel,KeyField,ShowInSales as ShowInSales,ShowInStock as ShowInStock,ShowInPurchases as ShowInPurchases,IsFixedAsset as IsFixedAsset,Details,LastModificationTimeStamp,cast(VATPercent as numeric) as VATPercent,AdditionalInfo2,AdditionalInfo1,KeyField,PictureLocation from inventory where barcode='$ID'";// offset $start rows fetch next $limit rows only";
		}
		else
		{
		$start=0;
		$limit=20;
				if(isset($_GET['ItemName']) && $_GET['ItemName']!="")
		$ItemName="i.Name like '%".$_GET['ItemName']."%' and ";
		else
		$ItemName="";

		if(isset($_GET['CompanyID']) && $_GET['CompanyID']!="")
		$CompanyID=" i.CompanyID=".$_GET['CompanyID']." and ";
		else
		$CompanyID="";

		if(isset($_GET['Under']) && $_GET['Under']!="")
		$Under="i.Under=".$_GET['Under']." and ";
		else
		$Under="";
		//	
		if(isset($_GET['Code']) && $_GET['Code']!="")
		$Code="i.AdditionalInfo2 like '%".$_GET['Code']."%' and ";
		else
		$Code="";

		if(isset($_GET['Size']) && $_GET['Size']!="" && $_GET['Size']>0)
		$Size="i.Size like '%".$_GET['Size']."%' and ";
		else
		$Size="";

		if(isset($_GET['AdditionalInfo5']) && $_GET['AdditionalInfo5']!="" && $_GET['AdditionalInfo5']>0)
		$AdditionalInfo5="i.AdditionalInfo5 like '%".$_GET['AdditionalInfo5']."%' and ";
		else
		$AdditionalInfo5="";
		//i.AdditionalInfo5	
		$searchbox=$ItemName."".$Under."".$Code."".$Size."".$AdditionalInfo5."".$CompanyID;
		$sql="  select   ROW_NUMBER() OVER (
      ORDER BY i.[ID]
   ) row_num,i.Name as ItemName,inv.Name as ProductCategoryName,i.under,i.AdditionalInfo2 as Code,i.Make as Brand,i.Rating as Color,i.AdditionalInfo1 as Part,i.Model as Size,
   g.AdditionalInfo1 as CompanyShortForm,i.CompanyID as CompanyId ,'' as col_Action,i.ID,i.ShowInSales as ShowInSales,i.ShowInStock as ShowInStock,i.ShowInPurchases as ShowInPurchases,i.IsFixedAsset as IsFixedAsset,'' as col_Action from  inventory as i
   inner join Inventory as inv on i.Under=Inv.ID
   inner join Godowns as g  on i.CompanyID=g.godownid
    where $searchbox i.[group]=0 and i.active=1 and   i.ProductBaseType='".$ProductBaseType."' order by i.CompanyID
";// offset $start rows fetch next $limit rows only";
		}

   $data=array();
//echo $sql;
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  while ($row = odbc_fetch_array($result)) {
        $row['col_Action']='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this,'.$row["ID"].');"></i>&nbsp;&nbsp;&nbsp;  <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this,'.$row["ID"].');"></i>';
        foreach ($row as $key => $value) {
        	# code...
        	$row[$key]=utf8_encode($value);
        }
      //  $row['ItemName']=htmlspecialchars($row['ItemName']);
      //  $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
      //  $row['Code']=htmlentities($row['Code']);

    $data []=$row;
  		}//end while
  		//print_r($data);
  		echo json_encode($data); 

	}//end if GETPRODUCTS
	if($_GET['action']=="searchProducts")
	{
	//	print_r($_POST);
//		print_r($_GET);
		$searchbox="";
$data=array();
		if(isset($_GET['ItemName']) && $_GET['ItemName']!="")
		$ItemName="i.Name like '%".$_GET['ItemName']."%' and ";
		else
		$ItemName="";

		if(isset($_GET['CompanyID']) && $_GET['CompanyID']!="")
		$CompanyID=" i.CompanyID =".$_GET['CompanyID']." and ";
		else
		$CompanyID="";

		if(isset($_GET['Under']) && $_GET['Under']!="")
		$Under="i.Under=".$_GET['Under']." and ";
		else
		$Under="";
		//	
		if(isset($_GET['Code']) && $_GET['Code']!="")
		$Code="i.AdditionalInfo2 like '%".$_GET['Code']."%' and ";
		else
		$Code="";

		if(isset($_GET['Size']) && $_GET['Size']!="")
		$Size="i.Size like '%".$_GET['Size']."%' and ";
		else
		$Size="";

		if(isset($_GET['AdditionalInfo5']) && $_GET['AdditionalInfo5']!="")
		$AdditionalInfo5="i.AdditionalInfo5 like '%".$_GET['AdditionalInfo5']."%' and ";
		else
		$AdditionalInfo5="";
		//i.AdditionalInfo5	
		$searchbox=$ItemName."".$Under."".$Code."".$Size."".$AdditionalInfo5."";

	/*	$search=array(
    'i.Name' =>(isset($_GET['ItemName']))?$_GET['ItemName']:"",
   	'i.CompanyID' =>(isset($_GET['CompanyID']))?$_GET['CompanyID']:"",
   	'i.Under' =>(isset($_GET['Under']))?$_GET['Under']:"",
   	'i.Attr2' =>(isset($_GET['Code']))?$_GET['Code']:"",
    'i.Size' =>(isset($_GET['Size']))?$_GET['Size']:"",
   'i.AdditionalInfo5' =>(isset($_GET['AdditionalInfo5']))?$_GET['AdditionalInfo5']:"");
   foreach($search as $key =>$value)
   {
   	$values="";
   	if(getDataType($connection,"inventory",str_replace("i.","",$key))==1)
					{
						if($value!="")
						$values="like '%".$value."%'";
					}
					else
					{
						if($value!="")
					$values ="=".$value;	
					}
		if($values!="")			
   		$searchbox .=" and $key $values";
   	
   }*/

    	 $sql="select   ROW_NUMBER() OVER (
      ORDER BY i.[CompanyID]
   ) row_num,i.Name as ItemName,inv.Name as ProductCategoryName,i.under,i.AdditionalInfo2 as Code,i.Make as Brand,i.Rating as Color,i.Model as Size,
   g.AdditionalInfo1 as CompanyShortForm,i.CompanyID as CompanyId ,'' as col_Action,i.ID as ID from inventory as i
   left outer join Inventory as inv on i.Under=Inv.ID
   left outer join Godowns as g  on i.CompanyID=g.godownid
    where i.[group]=0 and i.active=1 and i.ProductBaseType='ITEM' ".$searchbox."  order by 		CompanyID";
	$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
	//'.$row["CategoryID"].'
	//$limit=425;//
	//echo  odbc_num_rows($result);
  while ($row = odbc_fetch_array($result)) {
        $row['col_Action']='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this,'.$row["ID"].');"></i>&nbsp;&nbsp;&nbsp;  <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this,'.$row["ID"].');"></i>';
      //  $row['ItemName']=htmlspecialchars($row['ItemName']);
      //  $row['ProductCategoryName']=getnamesingle("inventory","Name","Under",$row['ProductCategoryName'],$connection);
      // $row['CompanyShortForm']=getnamesingle("Godowns","AdditionalInfo1","GodownID",$row['CompanyShortForm'],$connection);
      //  $row['Code']=htmlentities($row['Code']);
        	foreach ($row as $key => $value) {
        		# code...
        		$row[$key]=utf8_encode($value);
        	}
    $data []=$row;
  		}//end while
  		//print_r($data);
  		echo json_encode($data); 
	}

	if($_GET['action']=="DeleteProductSetup")
	{
		   odbc_autocommit($connection, FALSE);

		$ID=$_GET['ID'];
		$sql="delete from inventory where ID=".$ID;
			odbc_exec($connection, $sql);
		
		if (!odbc_error())
 		  {
    	  odbc_commit($connection);
$res=array('status'=>"ok",'description'=>'Data Deleted Sucessfully');  			}
		else
		{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Deleted');

		}
		
		echo json_encode($res);//implode(",",$res);		
	}
}
		if(isset($_GET['action']) && $_GET['action']=="InsertItemInformation")
		{
			   odbc_autocommit($connection, FALSE);

			$fields=array();
			$fields=array_keys($_POST);
			$ProductBaseType=$_GET['ProductBaseType'];
		//	print_r($_POST);
//return;
		//	print_r( $_FILES);
		//	singlegetname()
/*			$data= '['.$fields[0].'""}]';
			$fields=json_decode($data);
			//print_r($fields[0]);
			$d=$fields[0];*/
			if(isset($_POST['ID']))
			$ID=$_POST['ID'];
			else
			$ID=0;
	/*	$_POST['Barcode']=$_POST['ProductCode'];
		$_POST['Brand']='';
*/
		/*	if(isset($d->ID))
			$ID=$d->ID;
			else
				$ID=0;
		*/	/* $Under = $d->Under;
                    $UnitID = $d->$UnitID;
                    $Rating = $d->(color).attr('$Color');
                    $Model = $d->(size).attr('$Size');
                    $Name = txtProductName.val();
                    $AdditionalInfo1 = txtCode.val();
                    $Barcode =  txtBarcode.val();
                    $Make =  txtBrand.val();
                    $StandardPrice3 = txtCost.val();
                    $StandardPrice2 = txtRetail.val();
                    $StandardPrice1 = txtWholeSale.val();
                    $MinPriceLevel = txtMinPrice.val();
                    $CommissionPercent = txtComissionPercent.val();
                    $CommissionAmount = txtComissionAmount.val();
                    $MinQtyLevel = txtMinQty.val();
                    $MaxQtyLevel = txtMaxQty.val();
                    $AdditionalInfo2 = txtAdditionalInfo2.val();
                    $AdditionalInfo3 = $(country).attr('$Country');                    
                    $AdditionalInfo5 = $(supplier).attr('$COAID');
                    $CompanyID = $(company).attr('$GodownID');
                    $Attr1 = $(application).attr('$Application');
                    $Details = txtDetails.val();
                    $InitiateDate = txtInitiateDate.val();
                    $VATPercent = txtVATPercent.val();
                    $picture =   $('#picture').val();
                    $IsNonStockAble = IsNonStockAble;
                    $ID = txtID;
                    $LastModificationTimeStamp = txtLastModificationTimeStamp;   
                    Data.SideBarID=SideBarID; 
                    Data.ProductBaseType=ProductBaseType;*/
                    $fieldsname="";
                    $values="";
                    if($ID=="")
                    $ID=0;

                     $sql="select * from inventory where ID=".$ID;
                    $result=odbc_exec($connection,$sql);
                 	if(odbc_num_rows($result)>0)
                 	{
					//update code here
                 		$updatedata="";
                 		$ppic=$_FILES['picture']['name'];
	if($ppic!="")
		{
			$newfile=rand()*1200;
			$ext=strrchr($ppic,".");
			$newpic=$newfile.$ext;
			save($_FILES['picture'],'',"images/");	
			rename("images/".$ppic,"images/".$newpic);
			$_POST['PictureLocation']=$newpic;
		}
                 				foreach ($_POST as $key => $value) 
                 				{

   if($key!="SideBarID" &&  $key!="VehicleTypeDetail" && $key!="ID" && $key!="InitiateDate" && $key!="LastModificationTimeStamp")
									{

										if(getDataType($connection,"inventory",$key)==1)
										{

											$values="'".str_replace("_"," ",$value)."',";
										}
										else
										{
						if($value=="")$value="0";
						if($value=="on")$value="1";
						if($value=="option1")$value="0";					
										$values ="".$value.",";	
										}
										

									$updatedata.=$key."=".$values;
									}
				
                 				}
                 				$updatedata=substr($updatedata,0,strlen($updatedata)-1);
                 		 $sql="update inventory set $updatedata where ID=".$ID;
                 	}// end query if for update query    
                    else
                    {

$ppic=$_FILES['picture']['name'];
	if($ppic!="")
		{
			$newfile=rand()*1200;
			$ext=strrchr($ppic,".");
			$newpic=$newfile.$ext;
			save($_FILES['picture'],'',"images/");	
			rename("images/".$ppic,"images/".$newpic);
			$_POST['PictureLocation']=$newpic;
		}
                    //code for insert 
			foreach ($_POST as $key => $value) {
				# code...
				if($key!="SideBarID" && $key!="Barcode" &&  $key!="VehicleTypeDetail" && $key!="ID")
				{
				$fieldsname.=$key.",";

					if(getDataType($connection,"inventory",$key)==1)
					{

						$values.="'".str_replace("_"," ",$value)."',";
					}
					else
					{
						if($value=="")$value="0";
						if($value=="on")$value="1";
						if($value=="option1")$value="0";						
					$values .="".$value.",";	
					}
				}
				
			}
			$ID=getMaxId("inventory","ID",$connection)+1;
$KeyField=generatecode("Inventory","count(*)","ProductBaseType='ITEM'",$connection);
           	$KeyField2=str_pad($KeyField,7,"0",STR_PAD_LEFT);
           	$KeyField="I-".$KeyField2;
$values=str_replace("NaN-NaN-NaN",date("Y-m-d"),$values);
			$fieldsname=substr($fieldsname,0,strlen($fieldsname)-1);
			$values=substr($values,0,strlen($values)-1);
				$sql="insert into inventory (ID,ProductBaseType,Degree,KeyField,Barcode,[group],$fieldsname) values('$ID','$ProductBaseType',2,'$KeyField','$KeyField',0,$values)";
				}//end else for insert query 
			//	echo $sql;
			odbc_exec($connection, $sql) or die(odbc_error().$sql);
		    if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}
//		$res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
		echo json_encode($res);//implode(",",$res);		
		}
function getDataType($conn,$table,$field)
{
	$data=array();
   $sql="select data_type from information_schema.columns where table_name='$table' and column_name='$field'";
$result=odbc_exec($conn,$sql);
if(odbc_num_rows($result)>0)
{
  $data=odbc_fetch_array($result);

//print_r($data);
if($data['data_type']=="varchar" || $data['data_type']=="nvarchar" || $data['data_type']=="time" || $data['data_type']=="datetime" || $data['data_type']=="date" || $data['data_type']=="smalldatetime" || $data['data_type']=="time")
{
		return true;
} 
else 
	{
		return false;
	}
}
else
{
	return false;
} //echo json_encode($data);// print_r($data); 

}

?>