<?php

session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}
include("config.inc.php");
include("function.inc.php");
include("Functions_Synchro.php");


$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}

$query_login="select login_belongstogrp from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$resultlogin=mysql_query($query_login,$connection) or die(mysql_error());


$perpage=$_POST['perpage'];
$row_login=mysql_fetch_row($resultlogin);
$belongstogroup=$row_login[0];



//Read From Module Table
$querymodule=" Select ifNull(Module_Synchro,0) As Module_Synchro,module_autoledger From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$query_setup=" Select base1 As base1, base2 as base2, Setup_Branch, ifnull(alwaysClearPage,0) as alwaysClearPage from setup";
$result= mysql_query($query_setup,$connection) or die( mysql_error());
while($rowsetup=mysql_fetch_array($result)){
	extract($rowsetup);
}

if($alwaysClearPage == 1) $pageclear=1;
else $pageclear =0;
  

$actionmode=$_POST['actionmode']; if($actionmode == '') $actionmode=$_GET['actionmode'];

 //my code
	if($actionmode=='getledgergroup'){	
		$ledger_number=$_GET['ledger_number'];

		$query="select ifNull(ledger_number,0) AS ledger_numbers,Ledger_BelongsToGroup from ledger where ledger_number=$ledger_number";
		//echo $query;exit;
		$result=mysql_query($query,$connection);
		$row_num=mysql_num_rows($result);

		if($row_num>0){
			$query_if_ledgerdt_found="select ifNull(ledger_number,0),Ledger_BelongsToGroup from ledger
											where ledger_number like '$ledger_number%' and Ledger_BelongsToGroup=0";
		//	echo $query_if_ledgerdt_found;
			$result1=mysql_query($query_if_ledgerdt_found);
			$row_num1=mysql_num_rows($result1);
				while($rowledgerdt=mysql_fetch_array($result1)){
					extract($rowledgerdt);
				}
				if($row_num1==0){
					$ledgetdtserial.=$ledger_number;
					$ledgetdtserial.="0001";

					header("Location: Form_ledger.php?&msg=noledgerdt&ledgetdtserial=$ledgetdtserial");
				}
				if($row_num1>0){
					$query_getlastnum="select max(ledger_number) AS gratest_ledger_number from ledger where ledger_number like '$ledger_number%' and Ledger_BelongsToGroup=0";
					$result2=mysql_query($query_getlastnum);
					$row_num=mysql_num_rows($result);
					while($rowledgerdt2=mysql_fetch_array($result2)){
						extract($rowledgerdt2);
					}
					$ledger_number_plus=$gratest_ledger_number+1; 
					header("Location: Form_ledger.php?&msg=hasledgerdt&ledger_number_plus=$ledger_number_plus");
				}
		
		}
		else
			header("Location: Form_ledger.php?&msg=ledgernotfound&ledger_number=$ledger_number&txtKeyword=$txtKeyword&perpage=$perpage");	
	}



 
  $project_code = "".$project_code;
  if($project_code == '')
	$project_code= "NULL";
  else
	$project_code="'$project_code'";
  
  $costcenter_code = "".$costcenter_code;
  if($costcenter_code == '')
	$costcenter_code= "NULL";
  else
	$costcenter_code="'$costcenter_code'";
  
  
    
 if(empty($cashtype_code))
  $cashtype_code= 'null' ;
else
  $cashtype_code="'$cashtype_code'";
  
 if (!empty($deactivatedate))	{
	$deactivatedate  = explodeword($deactivatedate);
	$deactivatedate  = "'$deactivatedate'";

}	
else {$deactivatedate= 'null';}

if(empty($acctypename) && $acctypename!='0')
  $acctypename= 'null' ;
else
 $acctypename="'$acctypename'";


if(empty($ledger_deactivate))
	$ledger_deactivate=0;

if(empty($ledger_requireddetail))
	$ledger_requireddetail=0;

	if(empty($ledger_sequence))
	$ledger_sequence=0;
	
	if(empty($ledger_length))
	$ledger_length=0;
	
if(empty($ledger_activity))
  $ledger_activity= 'null' ;
else
  $ledger_activity="'$ledger_activity'";
  
  
$ledger_name = ereg_replace("'", "\'", $ledger_name);
$ledger_name2 = ereg_replace("'", "\'", $ledger_name2);
$ledger_number = ereg_replace("'", "\'", $ledger_number);
$ledger_number2 = ereg_replace("'", "\'", $ledger_number2);
$ledger_description = ereg_replace("'", "\'", $ledger_description);
$document = ereg_replace("'", "\'", $document);

$ledger_number=trim($ledger_number);
$ledger_numberPrv=trim($ledger_numberPrv);


if($ledger_number=='' and $module_autoledger==1)
{
    $query = " select ledger_length - length(Ledger_number) from ledger where Ledger_number = '".$ledger_group."'";
    $result = mysql_query($query, $connection);
	$row=mysql_fetch_row($result);
	$length = $row[0];


$query = " select lpad(ifnull(max(substr(ledger_number,length('".$ledger_group."')+1,".$length.")),0) + 1 ,".$length.",'0')from ledger where ledger_number like '".$ledger_group."%' ";
//echo $query;exit;
$result = mysql_query($query, $connection);
$row=mysql_fetch_row($result);
$newledger = $row[0];


$ledger_number =  $ledger_group.$newledger;
	
}

$ErrorExist = 0;

// Assets Parameters
if ($showAsset == '') $showAsset = 0;

if ($assetcrdt != ''){
	$ErrorExist = check_ledger($assetcrdt, $connection);
	$message = "Save not Allowed. Check for Asset Credit Ledger ";
}

if ($assetdbt != ''){
	$ErrorExist = check_ledger($assetdbt, $connection);
	$message = "Save not Allowed. Check for Asset Credit Ledger ";
} 

// richard insert
if($actionmode=='insert' && $ErrorExist == 0){	
	$query="Insert into ledger
		(Ledger_number, Ledger_name, Ledger_desc, Ledger_grpdet, Ledger_activity, Acctype_increment, Document, Ledger_number2, Ledger_name2, Project_Code, Ledger_BelongsToGroup, CashType_Code, Ledger_RequiredDetail,
		CostCenter_code, Ledger_Deactivate,Ledger_inactivedate, Currency_code, Ledger_inactive, ledger_type, Owner_Branch, ledger_sequence,ledger_length, ledger_asset ";
	if ($showAsset == 1)	
	$query .= " , ledger_assetPer, ledger_assetCode, ledger_assetDebit, ledger_assetCredit, ledger_assetSequence, ledger_assetLength ";    
	$query .= " ) values ('".$ledger_number."','".$ledger_name."','".$ledger_description."','".$ledger_grpdet."',$ledger_activity,$acctypename,'".$document."','".$ledger_number2."','".$ledger_name2."',
			$project_code,$belongstogroup,$cashtype_code,'".$ledger_requireddetail."',$costcenter_code,'".$ledger_inactive."',$deactivatedate,'".$currency_code."','".$ledger_inactive."','".$ledgertype."', 
			'".$Setup_Branch."', '".$ledger_sequence."', '".$ledger_length."', ".$showAsset." ";
	if ($showAsset == 1)	
	$query .= " , ".GetSQLValueString($assetper,'double').", ".GetSQLValueString($assetcode,'text').", ".GetSQLValueString($assetdbt,'text').", ".GetSQLValueString($assetcrdt,'text')." 
				,	".GetSQLValueString($assetseq,'double').", ".GetSQLValueString($assetlength,'double')." ";
	$query .= " ) ";
	
	$result = mysql_query($query, $connection);
	

	
	
	$message    = mysql_error();
	
	if($config['log_file'] == 1){
		$transType = "I";
		$company = explode("_", $_SESSION['dbName']);
		$currCompany = strtoupper($company[0]);	
		$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$ledger_number', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'ledger', '$currCompany')";
		//echo $query_insertToHistory;exit;
		$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
	}
	
	if ($result) {
		
		
		 
		  
		  
					 
				$queryledger="select ledger_id from ledger where ledger_number = '$ledger_number'";
				$resultledger=mysql_query($queryledger,$connection) or die(mysql_error());
				while($rowledger=mysql_fetch_array($resultledger)){
					extract($rowledger);
				}
				
				 


		
// send notification
		$queryacc = "SELECT user_code, ifnull(nbrofdays,0), ifnull(view_access,0) FROM ".$_SESSION['dbLabel'].".notification_access
												where notification_name='ledger_created' and ifnull(view_access,0) = 1 ";
		$resacc = mysql_query($queryacc, $connection);
		
		
									
		//echo $queryacc;
		while ($rwacc = mysql_fetch_array($resacc)){
		$querynot = "call sendNotification('ledger_created', '$rwacc[0]', $rwacc[1], $rwacc[2], $ledger_id, '" .$_SESSION['useraccount'] ."') ";
		 // echo $querynot;exit;
										
		$resnot = mysql_query($querynot, $connection);
		}		
		
			
// end send notification
			
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'I','LEDGER','',$ledger_number,$Setup_Branch);
		}
	}
	
	if($ledgertype=='1' && $result){	

		$insert_client=" Insert into clients (Ledger_number, Ledger_name, Ledger_desc, Project_Code, CostCenter_code, Client_deactivate, Client_deactivatedate, Owner_Branch, Currency_code, Client_CreationDate) ".
					   " values ('".$ledger_number."', '".$ledger_name."', '".$ledger_description."', $project_code, $costcenter_code, '".$ledger_inactive."', $deactivatedate, '".$Setup_Branch."', 
					   '".$currency_code."', now() )";
		$insert_result=mysql_query($insert_client,$connection);			
		$message    = mysql_error();	

		if ($insert_result) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'I','CLIENTS','',$ledger_number,$Setup_Branch);
			}
		}		
	}
	else if($ledgertype=='2' && $result){	
		$insert_supplier=" Insert into suppliers (Ledger_number, Ledger_name, Ledger_desc, Project_Code, CostCenter_code, Owner_Branch, currency_code, Supplier_CreationDate) ".
					     " values ('".$ledger_number."', '".$ledger_name."', '".$ledger_description."', $project_code, $costcenter_code, '".$Setup_Branch."', '".$currency_code."', now())";
		$insert_result=mysql_query($insert_supplier,$connection);			
		$message    = mysql_error();	

		if ($insert_result) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'I','SUPPLIERS','',$ledger_number,$Setup_Branch);
			}
		}		
	}
	else if($ledgertype=='3' && $result){	

		$insert_salesman=" Insert into salesmen (Ledger_number, Ledger_name, Ledger_desc, Owner_Branch, currency_code, salesman_CreationDate, salesmen_deactivate, salesmen_deactivatedate) ".
					     " values ('".$ledger_number."', '".$ledger_name."', '".$ledger_description."', '".$Setup_Branch."', '".$currency_code."', now(), '".$ledger_inactive."', $deactivatedate)";
		$insert_result=mysql_query($insert_salesman,$connection);			
		$message    = mysql_error();	

		if ($insert_result) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'I','SALESMEN','',$ledger_number,$Setup_Branch);
			}
		}	
	}				
}

if($actionmode=='edit' && $ErrorExist == 0){
	
	$query_update="update ledger set
					Ledger_number='".$ledger_number."', 
					Ledger_name='".$ledger_name."', 
					Ledger_desc='".$ledger_description."',
					Ledger_grpdet='".$ledger_grpdet."', 
					Ledger_activity=$ledger_activity, 
					Acctype_increment=$acctypename, 
					Document='".$document."',
					Ledger_number2='".$ledger_number2."', 
					Ledger_name2='".$ledger_name2."',
					Project_Code=$project_code, 
					Ledger_BelongsToGroup='".$belongstogroup."',
					CashType_Code=$cashtype_code, 
					Ledger_RequiredDetail='".$ledger_requireddetail."',
					ledger_sequence='".$ledger_sequence."',
					ledger_length='".$ledger_length."',
					CostCenter_code=$costcenter_code,
					Ledger_Deactivate=$ledger_inactive,
					Ledger_inactive=$ledger_inactive,
					Ledger_inactivedate=$deactivatedate,
					Currency_code='".$currency_code."',
					ledger_type='".$ledgertype."',
					ledger_asset = ".$showAsset." ";
		
	if ($showAsset == 1)	
	$query_update .= " , ledger_assetPer = ".GetSQLValueString($assetper,'double')."
					   , ledger_assetCode = ".GetSQLValueString($assetcode,'text')."
					   , ledger_assetDebit = ".GetSQLValueString($assetdbt,'text')."
					   , ledger_assetCredit = ".GetSQLValueString($assetcrdt,'text')." 
					   , ledger_assetSequence = ".GetSQLValueString($assetseq,'double')."
					   , ledger_assetLength = ".GetSQLValueString($assetlength,'double')." ";   				
	$query_update .= " where ledger_number='".$ledger_numberPrv."'";
	//echo$query_update;exit;
	$resultedit = mysql_query($query_update, $connection);
	$message    = mysql_error();
	
	if($config['log_file'] == 1){
		$transType = "U";
		$company = explode("_", $_SESSION['dbName']);
		$currCompany = strtoupper($company[0]);	
		$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$ledger_number', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'ledger', '$currCompany')";
		//echo $query_insertToHistory;exit;
		$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
	}
	
	if ($result) {
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'U','LEDGER','',$ledger_number,$Setup_Branch);
		}
	}

	$query_type="select ifnull(ledger_type,0)
				from ledger where ledger_number='$ledger_number'";
					
				//	echo $query_type;
	$resulttype=mysql_query($query_type);
	$row_type=mysql_fetch_row($resulttype);
	$type=$row_type[0];
		
	if($type=='1' && $resultedit){	

		$update_client="Update clients set 
					Ledger_number='".$ledger_number."', 
					Client_deactivate='".$ledger_inactive."',
					Ledger_name='".$ledger_name."', 
					Ledger_desc='".$ledger_description."',
					Project_Code=$project_code,
					CostCenter_code=$costcenter_code,
					Client_deactivatedate = $deactivatedate,
					Currency_code='".$currency_code."'
					where ledger_number='$ledger_numberPrv'";
				
		$resultupdate=mysql_query($update_client,$connection);			
		$message    = mysql_error();	

		if ($resultupdate) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','CLIENTS','',$ledger_number,$Setup_Branch);
			}
		}	
	}

	if($type=='2' && $resultedit){	
		$update_supplier="Update suppliers set 
						Ledger_number='".$ledger_number."', 
						Ledger_name='".$ledger_name."', 
						Ledger_desc='".$ledger_description."',
						Project_Code=$project_code,
						CostCenter_code=$costcenter_code ,
						Currency_code='".$currency_code."'
						where ledger_number='$ledger_numberPrv'";
				
		$resultupdate=mysql_query($update_supplier,$connection);			
		$message    = mysql_error();

		if ($resultupdate) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','SUPPLIERS','',$ledger_number,$Setup_Branch);
			}
		}			
	}
				
	if($type=='3' && $resultedit){	

		$update_salesman="Update salesmen set 
						Ledger_number='".$ledger_number."', 
						Ledger_name='".$ledger_name."', 
						Ledger_desc='".$ledger_description."',
						Currency_code='".$currency_code."',
						salesmen_deactivate = '".$ledger_inactive."', 
						salesmen_deactivatedate = $deactivatedate
						where ledger_number='$ledger_numberPrv'";
			//	echo $update_salesman;exit;
		$resultupdate=mysql_query($update_salesman,$connection);			
		$message    = mysql_error();	

		if ($resultupdate) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','SALESMEN','',$ledger_number,$Setup_Branch);
			}
		}	
	}				
}

if($actionmode=='delete'){
	$query_type="select ifnull(ledger_type,0) from ledger where ledger_number='$ledgernumber'";
	$resulttype=mysql_query($query_type);
	$row_type=mysql_fetch_row($resulttype);
	$type=$row_type[0];
    
	if($config['log_file'] == 1){
		$transType = "D";
		$company = explode("_", $_SESSION['dbName']);
		$currCompany = strtoupper($company[0]);	
		$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$ledgernumber', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'ledger', '$currCompany')";
		//echo $query_insertToHistory;exit;
		$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
	   }
		
	$deleteledger = "delete from ledger where ledger_number='$ledgernumber'";
	$result=mysql_query($deleteledger);
	$errornum= mysql_errno();
	
	if($errornum=='1451') {
		$message="Delete Not Allowed . Ledger Number is used .";
		if($config['log_file'] == 1){
		$query_getlastid  = "select ledger_ref_id from ".$config['dbName_history'].".ledger where ledger_trans_type = 'D' and ledger_number = '$ledgernumber' and Ledger_Trans_Schema = '".$_SESSION['dbName']."' order by ledger_ref_id desc limit 1";
        $result_getlastid = mysql_query($query_getlastid, $connection);
        $row_getlastid    = mysql_fetch_array($result_getlastid); 
        extract($row_getlastid);	

       $query_deletehistory = "delete from ".$config['dbName_history'].".ledger where ledger_ref_id = '$ledger_ref_id'";
       $result_deletehistory = mysql_query($query_deletehistory, $connection);	
		}	   
	}
	
	
	
		
	else{
		
		if ($result) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'D','LEDGER','',$ledgernumber,$Setup_Branch);
			}
		}
			
		
		if($type=='1'){
			$deleteclient = "delete from clients where ledger_number='$ledgernumber'";
			$result=mysql_query($deleteclient);
			$message    = mysql_error();
			
			if ($result) {
				if ($Module_Synchro == 1) {
					InsertSynchroLoc($connection,'D','CLIENTS','',$ledgernumber,$Setup_Branch);
				}
			}
		}
				
		if($type=='2'){
			$deletesuppliers = "delete from suppliers where ledger_number='$ledgernumber'";
			$result=mysql_query($deletesuppliers);
			$message    = mysql_error();
			
			if ($result) {
				if ($Module_Synchro == 1) {
					InsertSynchroLoc($connection,'D','SUPPLIERS','',$ledgernumber,$Setup_Branch);
				}
			}
		}

		if($type=='3'){
			$deletesalesmen = "delete from salesmen where ledger_number='$ledgernumber'";
			$result=mysql_query($deletesalesmen);
			$message    = mysql_error();
			
			if ($result) {
				if ($Module_Synchro == 1) {
					InsertSynchroLoc($connection,'D','SALESMEN','',$ledgernumber,$Setup_Branch);
				}
			}
		}
	}
		
}





if (($actionmode=='insert' || $actionmode=='edit') && $ErrorExist == 0 && $ledger_grpdet == 0){
	$querySearch = "select replace('$ledger_number', Acctype_ledger, Ledger_Number) as newLedger, concat('$ledger_name',' ', GeneratedType_Name) as newDesc, Ledger_activity, GeneratedType_Name, Ledger_Number, 
					Acctype_ledger
					from AcctypeSetup
					inner join Acctype on acctype_code = Type_Code
					where  '$ledger_number' like concat(Acctype_ledger,'%') ";	 
	$resSearch = mysql_query($querySearch, $connection);				
	while($rwSearch = mysql_fetch_array($resSearch)){
		$newLedger = check_ledger($rwSearch[0], $connection);
		// ledger doesn't Exists
		
		if ($newLedger == 1){
			$insert = "insert into ledger (Ledger_number, Ledger_name, Ledger_desc, Ledger_grpdet, Ledger_activity, Acctype_increment, Document, Ledger_number2, Ledger_name2, Project_Code, Ledger_BelongsToGroup, CashType_Code, Ledger_RequiredDetail,
							CostCenter_code, Ledger_Deactivate,Ledger_inactivedate, Currency_code, Ledger_inactive, ledger_type, Owner_Branch, ledger_sequence,ledger_length, ledger_asset, ledger_assetPer, ledger_assetCode, ledger_assetDebit, 
							ledger_assetCredit, ledger_assetSequence, ledger_assetLength) 
					  select '$rwSearch[0]', '$rwSearch[1]', Ledger_desc, Ledger_grpdet, '$rwSearch[1]', Acctype_increment, NULL, Ledger_number2, Ledger_name2, Project_Code, Ledger_BelongsToGroup, CashType_Code, Ledger_RequiredDetail,
							CostCenter_code, Ledger_Deactivate,Ledger_inactivedate, Currency_code, Ledger_inactive, ledger_type, Owner_Branch, ledger_sequence,ledger_length, ledger_asset, ledger_assetPer, ledger_assetCode, ledger_assetDebit, 
							ledger_assetCredit, ledger_assetSequence, ledger_assetLength
							from ledger where ledger_number = '$ledger_number' ";
			$resins = mysql_query($insert, $connection);
			if($config['log_file'] == 1){
				$transType = "I";
				$company = explode("_", $_SESSION['dbName']);
				$currCompany = strtoupper($company[0]);	
				$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$rwSearch[0]', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'ledger', '$currCompany')";
				//echo $query_insertToHistory;exit;
				$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
			}
		} else {
			$update = "update ledger set Ledger_name = '$rwSearch[1]' where ledger_number = '$rwSearch[0]' ";
			$resup = mysql_query($update, $connection);			
		}
	}	
	
}

$message = ereg_replace(" ", "%20", $message);

if($actionmode=='delete'  && $actionmode!='getledgergroup')
header ("Location: ./Form_Ledger.php?actionmode=insert&message=$message&txtKeyword=$txtKeyword&perpage=$perpage&pageclear=$pageclear");
else
	if($actionmode!='getledgergroup')	{	   
header ("Location: ./Form_Ledger.php?ledger_number=$ledger_number&actionmode=editmode&typestatus=disabled&message=$message&txtKeyword=$txtKeyword&perpage=$perpage&pageclear=$pageclear");
	}
exit;


function check_ledger($ledger_number, $connection){
	$query = "select 1 from ledger where ledger_number = '$ledger_number' and Ledger_grpdet=0 ";
	$result = mysql_query($query, $connection);
	$numr = mysql_num_rows($result);
	if ($numr > 0)
		return 0;
	return 1;
}	

mysql_close($connection);

print <<<HERE
</form>
</body>
HERE;
?>
		        



