<?php
include_once('database_connection.php');
$Userid=$_SESSION['userid'];

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

		$master=array_keys($_POST);
		$details=array_values($_POST);
		//print_r($details);
		 $master1="[".str_replace(',"detail":',"}",$master[0])."]";
		//$master=array_keys($master[0]);

		$masterdata=json_decode($master1);
		if(isset($details) && $details[0]!="")
		{
		$detail=array_keys($details[0]);
		 $detail="[".$detail[0]."]";
		$detaildata=json_decode($detail);
		}
		else
		{
			$detaildata="";
		}
		//print_r($detaildata);
		$VoucherID=0;
	//	print_r($masterdata);
	$data=$masterdata[0];	
	$under=$data->Under;
	$NatureID=isset($data->NatureID)?$data->NatureID:getnamesingle("accounts","NatureID","under",$under,$connection);
	$COAID=isset($data->COAID)?$data->COAID:0;
	$Group=isset($data->Group)?$data->Group:0;	
	$Attr1=isset($data->Attr1)?$data->Attr1:'';	
	$Attr2=isset($data->Attr2)?$data->Attr2:'';
	$Attr3=isset($data->Attr3)?$data->Attr3:'';
	$CostCenterID=isset($data->CostCenterID)?$data->CostCenterID:'0';	
$Attr17=isset($data->Attr17)?$data->Attr17:'';
$Attr4=isset($data->Attr4)?$data->Attr4:'';
$Attr5=isset($data->Attr5)?$data->Attr5:'';
$Attr6=isset($data->Attr6)?$data->Attr6:'';
$Attr7=isset($data->Attr7)?$data->Attr7:'';
$Attr8=isset($data->Attr8)?$data->Attr8:'';
$Attr9=isset($data->Attr9)?$data->Attr9:'';
$Attr10=isset($data->Attr10)?$data->Attr10:'';
$Attr11=isset($data->Attr11)?str_replace("_", ".",$data->Attr11):'';
$Attr12=isset($data->Attr12)?str_replace("_", " ",$data->Attr12):'';
$Attr13=isset($data->Attr13)?$data->Attr13:'';
$Attr14=isset($data->Attr14)?$data->Attr14:'';
$Attr15=isset($data->Attr15)?$data->Attr15:'';
$Attr16=isset($data->Attr16)?$data->Attr16:'';
$Attr17=isset($data->Attr17)?$data->Attr17:'';
$Attr18=isset($data->Attr18)?$data->Attr18:'';
$Attr19=isset($data->Attr19)?$data->Attr19:'';
$Attr20=isset($data->Attr20)?$data->Attr20:'';
$FixedAssetAcquireDate=isset($data->FixedAssetAcquireDate)?$data->FixedAssetAcquireDate:'';
$COAName=isset($data->AccountTitle)?$data->AccountTitle:'';
	if(isset($data->COAID)  && $data->COAID!=0)
	{
   $sql="update accounts set Under=".$data->Under.",CostCenterID=".$CostCenterID.",COAName='".$COAName."',
            Attr2='".$Attr2."',
            Attr1='".$Attr1."',
            Attr3='".$Attr3."',
            Attr4='".$Attr4."',
            Attr5='".$Attr5."', 
            Attr6='".$Attr6."',
            Attr7='".$Attr7."',
            Attr8='".$Attr8."',
            Attr9='".$Attr9."',
            Attr10='".$Attr10."',
            Attr11='".$Attr11."',
            Attr12='".$Attr12."',
            Attr13='".$Attr13."',
            Attr14='".$Attr14."',
            Attr15='".$Attr15."',
            Attr16='".$Attr16."',
            Attr17='".$Attr17."', 
            Attr18='".$Attr18."', 
            Attr19='".$Attr19."', 
            Attr20='".$Attr20."',
            FixedAssetAcquireDate='".$FixedAssetAcquireDate."'             
            where COAID=".$data->COAID;
            $LedgerID=$data->COAID;
            	odbc_exec($connection, $sql) or die(odbc_error().$sql);

	}
	else
	{
	$COAID=getMaxId("accounts","COAID",$connection)+1;
		$ParentCode=getnamesingle("accounts","GLCode","COAID",$under,$connection);
		$Degree=getnamesingle("accounts","Degree","COAID",$data->Under,$connection)+1;		
		$GLCode=0;
	/*	[{"Under":"52","CostCenterID":"1","Attr5":"6","AccountTitle":"National_Bank_of_Fujairah-(012001365768)AED","Degree":"undefined","COAID":"83","Attr4":"012001365768","Attr6":"","Attr7":"Dubai","Attr8":"","Attr9":"","Attr10":"00971552972720","Attr11":"muneeb_cheema@nbf_ae","Attr12":"Muneeb_Cheema","Attr13":"AE060380000012001365768","Attr14":"NBFUAEAFDXB","Attr15":"100065112300003","Attr16":"","Attr17":"","NatureID":13}]
*/		
	$GLCode=$ParentCode.".".generateGLCode($under,$NatureID,$connection);
	
            $sql="insert into accounts (COAID,Under,Active ,GLCode,
            CostCenterID ,
            [Group],
            Attr5 ,
            COAName ,
            Degree ,
            Attr1 ,
            Attr2 , 
            Attr3 ,                                   
            Attr4 ,
            Attr6 ,
            Attr7 ,
            Attr8 ,
            Attr9 ,
            Attr10 ,
            Attr11 ,
            Attr12 ,
            Attr13 ,
            Attr14 ,
            Attr15 ,
            Attr16 ,
            Attr17 ,
            Attr18 ,
            Attr19 ,
            Attr20 ,
            FixedAssetAcquireDate ,                                    
            NatureID)
            values(".$COAID.",".$data->Under.",1,'".$GLCode."',".
            $CostCenterID.",".
            $Group.",'".
            $Attr5."','".
            $COAName."',".
            $Degree.",'".
            $Attr1."','".
            $Attr2."','".
            $Attr3."','".                        
            $Attr4."','".
            $Attr6."','".
            $Attr7."','".
            $Attr8."','".
            $Attr9."','".
            $Attr10."','".
            $Attr11."','".
            $Attr12."','".
            $Attr13."','".
            $Attr14."','".
            $Attr15."','".
            $Attr16."','".
            $Attr17."','".
            $Attr18."','".
            $Attr19."','".
			$Attr20."','".
			$FixedAssetAcquireDate."',".
            $NatureID.")";

	odbc_exec($connection, $sql);
            $VoucherTypeID=0;
            $PeriodID=1;
            $USERID=0;
            $GROUPID=1;
            $Active=1;
            $TotalAmount=0;
            $ISDepreciationVoucher=0;
            $LocationID=1;
            $LedgerID=$COAID;
            $Narration="Opening Balance";
            $VoucherDate=date("Y-m-d m:i:s");
            $VoucherID=getMaxId("VoucherMaster","VoucherID",$connection)+1;
            if($Group==0)
            {
            $VoucherNo=generateCode("VoucherMaster","","VoucherTypeID=0",$connection)+1;
            $VoucherNo="OPV-".str_pad($VoucherNo,5,"0",STR_PAD_LEFT);
            
            $sqlvmaster="insert into VoucherMaster(VoucherID,VoucherNo,TotalAmount,Active,VoucherDate,Narration,posted,VoucherTypeID,PeriodID,LedgerID,LocationID,ISDepreciationVoucher,USERID,GROUPID) values(".$VoucherID.",'".$VoucherNo."',".$TotalAmount.",".$Active.",'".$VoucherDate."','".$Narration."',1,".$VoucherTypeID.",".$PeriodID.",".$LedgerID.",".$LocationID.",".$ISDepreciationVoucher.",".$USERID.",".$GROUPID.")";
            if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
			{
				if($_SESSION['SETTING']['OPENINGBALANCE']==true)
				{
            odbc_exec($connection,$sqlvmaster);
        		}
        	}
        	}
	}//end else for insert accounts

	//code for opening 
	//insert voucher master 
	if($VoucherID!="" && $VoucherID>0)
	{}
	else
	{
		$v=getnamewhere("VoucherMaster","VoucherID","VoucherTypeID=0 and LedgerID=".$LedgerID,$connection);
		$v=json_decode($v);
		//print_r($v);
		if(isset($v->VoucherID))
		$VoucherID=$v->VoucherID;
		//$VoucherID="select VoucherID from "
	}
	if($Group==0)
	{
		 if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
			{
				if($_SESSION['SETTING']['OPENINGBALANCE']==true)
				{
					if($VoucherID>0)
					{
					$sql="delete from VoucherDetails where VoucherID=".$VoucherID;
					odbc_exec($connection, $sql);
        			}
        		}
        	}//end opening Setting

	for($a=0;$a<count($detaildata);$a++)
	{
	
	$CostCenterID=$detaildata[$a]->CostCenterID;
	$Balance=$detaildata[$a]->Balance;
	$Debit=$Balance;
	$Credit=0;
	$CreditLedgerID=76;
	$LedgerID=$COAID;
	$AssetAcquireValue=isset($detaildata[$a]->Cost)?$detaildata[$a]->Cost:null;
	$AssetSalvageValue=isset($detaildata[$a]->SalvageValue)?$detaildata[$a]->SalvageValue:0;
    //$VoucherID=getMaxId("VoucherDetails","VoucherID",$connection)+1;

	//	$keys .=",".$key;
	//	$values .=",".$value;
	 $sql="insert into VoucherDetails(VoucherID,Debit,Credit,DebitCostCenterID,CostCenterID,LedgerID,CreditLedgerID,Narration,isDelete,AssetID,AssetCostCenterID,AssetSalvageValue,AssetAcquireValue) values($VoucherID,$Debit,$Credit,$CostCenterID,$CostCenterID,$LedgerID,$CreditLedgerID,'Opening Balance',0,$LedgerID,$CostCenterID,$AssetSalvageValue,$AssetAcquireValue)";
		 if(isset($_SESSION['SETTING']['OPENINGBALANCE']) )
			{
				if($_SESSION['SETTING']['OPENINGBALANCE']==true)
				{
					odbc_exec($connection,$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');

}
	
	}

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

		$data=array();
		$COAID=isset($_GET['COAID'])?$_GET['COAID']:0;
		if($COAID>0)
		{
		 $sql="select Debit,Credit,DebitCostCenterID as GodownID,AssetAcquireValue,AssetSalvageValue,g.Name as GodownName from VoucherDetails as vd 
		right outer join godowns as g on vd.DebitCostCenterID=g.GodownID
		where VoucherID in(select VoucherID  from VoucherMaster where VoucherNo like 'OPV-%') and (LedgerID=".$COAID." and g.active=1 and g.godowntype=0)";			
		}
		else
		{
		$sql="select Debit,Credit,AssetAcquireValue as Cost,AssetSalvageValue as SalvageValue,g.GodownID as GodownID,g.Name as GodownName,LedgerID,g.godowntype from VoucherDetails as vd 
		right outer join godowns as g on vd.ledgerid=g.GodownID where g.GodownID between 1 and 4 ";	
		/*echo $sql="select Debit,Credit,DebitCostCenterID as GodownID,g.Name as GodownName from VoucherDetails as vd 
		right outer join godowns as g on vd.DebitCostCenterID=g.GodownID
		where VoucherID in(select VoucherID  from VoucherMaster where VoucherNo like 'OPV-%') and (LedgerID=".$COAID." or gor ,.active=1 and g.godowntype=0)";*/
		}
		$result=odbc_exec($connection, $sql);
		if(odbc_num_rows($result)<1)
		{
$sql="select Debit,Credit,g.GodownID as GodownID,g.Name as GodownName,LedgerID,g.godowntype from VoucherDetails as vd 
		right outer join godowns as g on vd.ledgerid=g.GodownID where g.GodownID between 1 and 4 ";	
		$result=odbc_exec($connection, $sql);			
		}
		while($row=odbc_fetch_array($result))
		{
		$data[]=$row;	
		}
	//	print_r($data);
		echo json_encode($data);

	
	}
	if($_GET['action']=="GetAccountsMasterForm")
	{
		$data=array();
$SideBarID=$_GET['SideBarID'];		
	$permission=userrights($Userid,$SideBarID,'[Display]',$connection);
		if($permission==1)
		{
		if(isset($_GET['NatureID']) && $_GET['NatureID']!="")
		{
			$NatureID="NatureID=".$_GET['NatureID'];
		}
		else
		{
			$NatureID=	"1=1";
		}
		if(isset($_GET['Group']) && $_GET['Group']!="")
		{
			$Group="GroupID=".$_GET['Group']." and ";
		}
		else
		{
			$Group=	"";
		}
		//$NatureID=$_GET['NatureID'];
		if(isset($_GET['L2']) && $_GET['L2']!="")
		{
			$L2="L2 like '%".$_GET['L2']."%' and ";
		}
		else
		{
			$L2="";
		}
		if(isset($_GET['L3']) && $_GET['L3']!="")
		{
			$L3="L3 like '%".$_GET['L3']."%' and ";
		}
		else
		{
			$L3="";
		}
		if(isset($_GET['L1']) && $_GET['L1']!="")
		{
			$L1="COAHead like '%".$_GET['L1']."%' and ";
		}
		else
		{
			$L1="";
		}
				if(isset($_GET['Category']) && $_GET['Category']!="")
		{
			$Category="COAHead like '%".$_GET['Category']."%' and ";
		}
		else
		{
			$Category="";
		}

		if(isset($_GET['COAName']) && $_GET['COAName']!="")
		{
			$COAName="COAName like '%".$_GET['COAName']."%' and ";
		}
		else
		{
			$COAName="";
		}
		if(isset($_GET['Attr4']) && $_GET['Attr4']!="")
		{
			$Attr4="Attr4 like '%".$_GET['Attr4']."%' and ";
		}
		else
		{
			$Attr4="";
		}
				if(isset($_GET['Attr10']) && $_GET['Attr10']!="")
		{
			$Attr10="Attr10 like '%".$_GET['Attr10']."%' and ";
		}
		else
		{
			$Attr10="";
		}
				if(isset($_GET['Attr15']) && $_GET['Attr15']!="")
		{
			$Attr15="Attr15 like '%".$_GET['Attr15']."%' and ";
		}
		else
		{
			$Attr15="";
		}
		$searchbox=$COAName.$Attr4.$Attr10.$Attr15.$L1.$L2.$L3.$Group.$Category;
		
		  $sql="select * from view_fixedasset_list where $searchbox $NatureID";
		  /*$sql="select ROW_NUMBER() OVER (ORDER BY [Attr18])  as row_num,COAName,Hierarchy,Under,CostCenterID,COAID,GLCode,
(select COAName  from accounts as c where c.COAID=acc.Under) as L3,
(select COAName  from accounts as c where c.COAID=(select Under from accounts as cc where cc.COAID=acc.Under)) as L2,
(select COAName  from accounts as c where c.COAID=(select Under from accounts as cc where cc.COAID=(select Under from accounts as ccc where ccc.COAID=acc.Under))) as COAHead,Degree.
,'' as col_Action,Attr1,Attr2 as SupplierName,Attr3 as DepreicationGl,Attr4,Attr5,Attr6,Attr7,Attr8,Attr9,Attr10,Attr11,Attr12,Attr13,Attr14,Attr15,Attr16,Attr17,Attr18,Attr19 as DisposalGL,Attr20 from accounts as acc where $searchbox $NatureID";*/
			$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{
			foreach($row as $key=>$value)
			$row[$key]=utf8_encode($value);	

		/*	$row['COAName']=htmlspecialchars($row['COAName']);
			$row['COAHead']=htmlspecialchars($row['COAHead']);
			$row['L2']=htmlspecialchars($row['L2']);
			$row['L3']=htmlspecialchars($row['L3']);						*/
	$row["Attr2"]=$row["SupplierName"];
	$row["Attr19"]=$row["DisposalGL"];
	$row["Attr3"]=$row["DepreicationGl"];
	
	$row["SupplierName"]=getnamesingle('Accounts','COAName','COAID',$row["SupplierName"],$connection);
	$row["DepreicationGl"]=getnamesingle('Accounts','COAName','COAID',$row["DepreicationGl"],$connection);
	$row["DisposalGL"]=getnamesingle('Accounts','COAName','COAID',$row["DisposalGL"],$connection);
		
		$permission=userrights($Userid,$SideBarID,'[Alter]',$connection);
		if($permission==1)
		{
			$editdata='<i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editRow(this);"></i>';
		}
		else
		{
			$editdata='';
		}
		$permission=userrights($Userid,$SideBarID,'[Delete]',$connection);
		if($permission==1)
		{
			$deldata='<i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteRow(this);"></i>';
		}
		else
		{
			$deldata='';
		}
			$row["col_Action"]=''.$editdata.'&nbsp;&nbsp;&nbsp; '.$deldata;
		$data[]=$row;	
		}//end while
		}
	else
	{

	}
	//	print_r($data);
		echo json_encode($data);

	
	}
	if($_GET['action']=="GetVoucherHeads")
	{
		$data=array();
		$Type=$_GET['Type'];
		if(isset($_GET['GLStartsWith']))
		{
			$GLCode=$_GET['GLStartsWith'];
		$GLCode=" or GLCode like '".$GLCode."%'";

		}
		else
		{
		$GLCode=" ";			
		}
		 $sql="select COAID,COAName from accounts where COAName like '%".$Type."%' $GLCode";	
			$result=odbc_exec($connection, $sql);
		while($row=odbc_fetch_array($result))
		{

			foreach($row as $key=>$value)
			$row[$key]= utf8_encode($value);	

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

	}
}

?>