<?php

session_start();

if($_SESSION['dbName']==""){
header("location:../index.php");
}

include("config.inc.php");

set_time_limit(0);

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



$querylog=" select FI_PurchasesVATMod, ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(Login_negativeQty,0) As Login_negativeQty, ifNull(Login_Purchase_Pending,0) As Login_Purchase_Pending, ifNull(Login_location,0) As Login_location  ".
		  " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."') ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}

$txtvisitid 		    = $_GET['txtvisitid']; if ($txtvisitid == ""){$txtvisitid = $_POST["txtvisitid"];}
$mode 		    = $_GET['mode']; if ($mode == ""){$mode = $_POST["mode"];}

$newdate = explode("/",$txtDate);
$txtDate = $newdate[2]."-".$newdate[1]."-".$newdate[0];

if($txtvisitstarthr == '') $txtvisitstarthr='00';
if($txtvisitstartmn == '') $txtvisitstartmn='00';

$visitStart = $txtDate." ".$txtvisitstarthr.":".$txtvisitstartmn.":00";

if($txtvisitendhr == '') $txtvisitendhr='00';
if($txtvisitendmn == '') $txtvisitendmn='00';

$visitEnd = $txtDate." ".$txtvisitendhr.":".$txtvisitendmn.":00";

if($visit_followup != '0'){
	$newdate = explode("/",$txtFollowDate);
	$txtFollowDate = $newdate[2]."-".$newdate[1]."-".$newdate[0];
	if($txtvisitfollowhr == '') $txtvisitfollowhr='00';
	if($txtvisitfollowmn == '') $txtvisitfollowmn='00';

	$visitfollowtime = $txtFollowDate." ".$txtvisitfollowhr.":".$txtvisitfollowmn.":00";
}

if($txtfollowchk == '' ) $txtfollowchk = 0;

if($txtMainOfficeId == '') $txtMainOfficeId = "NULL";
if($txtBranchOfficeId == '') $txtBranchOfficeId = "NULL";
if($txtcustomerprojectId == '') $txtcustomerprojectId = "NULL";


if($txtvisitprice == '') $txtvisitprice = "NULL";
else $txtvisitprice = "'".mysql_real_escape_string($txtvisitprice)."'";	
if($txtvisitpayterms == '') $txtvisitpayterms = "NULL";
else $txtvisitpayterms = "'".mysql_real_escape_string($txtvisitpayterms)."'";

if($txtvisitcredit == '') $txtvisitcredit = "NULL";
else $txtvisitcredit = "'".mysql_real_escape_string($txtvisitcredit)."'";	
if($txtvisitgift == '') $txtvisitgift = "NULL";
else $txtvisitgift = "'".mysql_real_escape_string($txtvisitgift)."'";	

if($txtvisitresult == '') $txtvisitresult = "NULL";
else $txtvisitresult = "'".mysql_real_escape_string($txtvisitresult)."'";	
if($txtvisitcommision == '') $txtvisitcommision = "NULL";
else $txtvisitcommision = "'".mysql_real_escape_string($txtvisitcommision)."'";

if($txtvisitrequest == '') $txtvisitrequest = "NULL"; 
else $txtvisitrequest = "'".mysql_real_escape_string($txtvisitrequest)."'";	 

if($txtvisitnote == '') $txtvisitnote = "NULL"; 
else $txtvisitnote = "'".mysql_real_escape_string($txtvisitnote)."'";	 


$message='';

if($mode == 'Post'){
	fbegin();	
	$txtvisitid = get_nextsequence('visit_reference','',$connection); 
	fcommit();
	$query = "insert into visit (visit_reference, customer_code, salesmen_code, visit_date, visit_starttime, visit_endtime";
	if($Visit_type != '0') $query=$query.", Visit_type";
	if($txtfollowchk != '0') $query=$query.", Visit_followupdate, visit_followTime ";
	if($txtvisitnote != '') $query=$query.", visit_note";
	$query=$query.",visit_followup, visit_request, visit_priceoffered, visit_paymentterms, visit_creditlimit, visit_gift, 
			 visit_result, visit_commission, visit_mainofficeId, visit_branchofficeId, visit_projectId) ".
			 "values ".
			 "($txtvisitid, '$txtClientCode','$txtSalesmanCode', '$txtDate','$visitStart', '$visitEnd'";
	if($Visit_type != '0') $query=$query.",'$txtvisittype'";	
	if($txtfollowchk != '0') $query=$query.", '$txtFollowDate','$visitfollowtime' ";	
	if($txtvisitnote != '') $query=$query.",$txtvisitnote";
			 
	$query=$query.",$txtfollowchk, $txtvisitrequest, $txtvisitprice,$txtvisitpayterms,$txtvisitcredit,$txtvisitgift,
				$txtvisitresult,$txtvisitcommision,$txtMainOfficeId,$txtBranchOfficeId,$txtcustomerprojectId) ";
	//echo $query;exit;
	$result = mysql_query($query,$connection);
	if ($result) $message='';
	else {
		$txtvisitid = "";
		$ErrorExists = 1;
		$message  = mysql_error(); 
		frollback();
	}
	
} else if($mode == 'Edit'){
	
	$query = "update visit set ".
			"customer_code= '$txtClientCode', ".
			"salesmen_code= '$txtSalesmanCode', ".
			"visit_date= '$txtDate', ".
			"visit_starttime = '$visitStart' ,".
			"visit_endtime = '$visitEnd' ";
	if($Visit_type != '0') $query=$query.", Visit_type= '$txtvisittype' ";
	if($txtfollowchk == '1' ) $query=$query.", Visit_followupdate= '$txtFollowDate', visit_followTime = '$visitfollowtime' ";	
	if($txtvisitnote != '') $query=$query.", visit_note= $txtvisitnote ";
	$query=$query.", visit_followup=$txtfollowchk, visit_request= $txtvisitrequest, ".
			"visit_priceoffered = $txtvisitprice, 
			visit_paymentterms = $txtvisitpayterms, 
			visit_creditlimit = $txtvisitcredit, 
			visit_gift = $txtvisitgift, 
			 visit_result = $txtvisitresult, 
			 visit_commission = $txtvisitcommision, 
			 visit_mainofficeId = $txtMainOfficeId, 
			 visit_branchofficeId = $txtBranchOfficeId, 
			 visit_projectId = $txtcustomerprojectId ".
			 "where  visit_reference = $txtvisitid";
	//echo $query; exit;
	$result = mysql_query($query,$connection);
	
	if ($result) $message='';
	else {
		$txtvisitid = "";
		$ErrorExists = 1;
		$message  = mysql_error(); 
		frollback();
	}
	
}else if($mode == 'delete'){
	$query  = "delete from visit where visit_reference = $txtvisitid"; 
	$result = mysql_query($query,$connection);
	if ($result) $message='';
	else {
		$ErrorExists = 1;
		$message  = mysql_error(); 
		frollback();
	}
	header ("Location: ./Form_VisitSearch.php");exit;
}

if($message == '' && ($mode=='Post' or $mode=='Edit' ) )
	header ("Location: ./Form_Visit.php?mode=$mode&txtvisitid=$txtvisitid");
else if($message == '' && $mode=='delete' )
	header ("Location: ./Form_Visit.php");
else if($message != '') 
	header ("Location: ./Form_Visit.php?message=".$message);

function get_nextsequence($SeqField , $ProjCostCent ,$connection)
{
	//mysql_query("START TRANSACTION",$connection);
	$query = "Select ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject , ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter From Module ";
	$result= mysql_query($query,$connection) or die( mysql_error());
	while($rowmodule=mysql_fetch_array($result)){
		extract($rowmodule);
	}
		
	$query = "Select Count(*) From Sequence";

	if ($ProjCostCent != '' && $Module_ReferenceByCostcenter == 1)
		$query = $query."  Where Sequence.CostCenter = '".$ProjCostCent."'";
	else if ($ProjCostCent != '' && $Module_ReferenceByProject == 1)
		$query = $query."  Where '".$ProjCostCent."' Like Concat(Sequence.Project,'%') ";	
		
	$result1=mysql_query($query,$connection)	or die( mysql_error());
	$row=mysql_fetch_row($result1);
	$Countt = $row[0];
	 
	 
	if ($Countt==0)
	{
		if ($ProjCostCent != '' && $Module_ReferenceByCostcenter == 1)
			$query = "Insert Into Sequence (".$SeqField.",CostCenter) Values (1,'".$ProjCostCent."')";
		else if ($ProjCostCent != '' && $Module_ReferenceByProject == 1)	
			$query = "Insert Into Sequence (".$SeqField.",Project) Values (1,'".$ProjCostCent."')";
		else	
			$query = "Insert Into Sequence (".$SeqField.") Values (1)";
			
		$result1=mysql_query($query,$connection)	or die( mysql_error());
	}	
	else
	{
		if ($ProjCostCent == '') 
		{
			$query = "Update Sequence Set ".$SeqField."=LAST_INSERT_ID(ifnull(".$SeqField.",0)+1) Where Sequence.CostCenter is null and Sequence.Project is null";
			$result1=mysql_query($query,$connection)	or die( mysql_error());
		}
		else
		{
			if ($Module_ReferenceByCostcenter == 1)
				$query = "Update Sequence Set ".$SeqField."=LAST_INSERT_ID(ifnull(".$SeqField.",0)+1) Where Sequence.CostCenter = '".$ProjCostCent."'";
			else if ($Module_ReferenceByProject == 1)
				$query = "Update Sequence Set ".$SeqField."=LAST_INSERT_ID(ifnull(".$SeqField.",0)+1) Where '".$ProjCostCent."' Like Concat(Sequence.Project,'%')";
			
			$result1=mysql_query($query,$connection)	or die( mysql_error());
		}
		
	}

		
	$query = " SELECT LAST_INSERT_ID()";
	$result1=mysql_query($query,$connection)	or die( mysql_error());
	$row=mysql_fetch_row($result1);
	$NextValue = $row[0];
	if ($NextValue =='')
		$NextValue = 1 ;
 	
	//mysql_query("COMMIT",$connection);
	return $NextValue;
}

function fbegin()
{
	mysql_query("START TRANSACTION");
}
function fcommit(){
	mysql_query("COMMIT");
}
function frollback()
{
	mysql_query("ROLLBACK");
}

?>