<?php
 	session_start(); 
	if(!isset($_SESSION['linkarisesuloginsesion']))
	{
		header('Location: index.php');
		return;
	}
	if($_SESSION['linkariseutype']!='Superuser'){
			header('Location: index.php');
		return;
	}
	
	if($_SERVER['REQUEST_METHOD'] === 'POST')
	{
		if(!isset($_POST['_token']) || ($_POST['_token']!==$_SESSION['_token'] ) )
		{
			header('Location: index.php');
			return;
		}
	}
	$samid=$_SESSION['linkarisesumid'];
	$_SESSION['_token']=bin2hex(openssl_random_pseudo_bytes(16));
	date_default_timezone_set("Asia/Singapore");
	$mdate= date('Y-m-d');
	 $mdatetime= date('Y-m-d H:i:s');
	
	include("connect.php");
	$cmpname=$_POST['cmpname'];
	$cmptype=$_POST['cmptype'];
	$cpname=$_POST['cpname'];
	$cpmobile=$_POST['cpmobile'];
	$cmpaddress=$_POST['cmpaddress'];
	$username=$_POST['username'];
	$usermobile=$_POST['usermobile'];
	$userdesignation="Admin";
	$userloginid=$_POST['userloginid'];
	
	$usersecurepasword=md5($_POST['userpassword']);
	$companyprefix=$_POST['companyprefix'];
	$companytollerance=$_POST['cmptollerance'];
	

	
	$eve = "select * from res_company_master where companycontectno='$cpmobile'";
	$re = mysqli_query($conn, $eve);
	if(mysqli_num_rows($re) > 0)
	{
		$_SESSION['msg1'] = "Business already registered.";
		header('Location: businessregisteradd.php');
	}
	else
	{	
			$evemaxq = "SELECT max(cmpno) AS maxcmno FROM res_company_master";
	$remaxq = mysqli_query($conn, $evemaxq);
	while($rtmaxq = mysqli_fetch_assoc($remaxq))
	{
		$cmno=$rtmaxq['maxcmno'];
	}
	$cmno1=$cmno+1;
	 $number = str_pad("$cmno1", 6, "0", STR_PAD_LEFT);
			
			$eve1 = "INSERT INTO res_company_master (companyname,companyaddress,companycontactperson,companytype,companycontectno,companyprefix,cmpno,companyno,addedby,addedon,updatedon,updatedby,companytollerance) VALUES 
			('$cmpname', '$cmpaddress','$cpname','$cmptype','$cpmobile','$companyprefix','$cmno1','$number',$samid,'$mdatetime','$mdatetime',$samid,'$companytollerance')";
			if ($conn->query($eve1) === TRUE)
			{
				$brmid = $conn->insert_id;						
				 $eve23 = "INSERT INTO res_user_master (username, userdesignation, usermobile, userloginid, usersecurepasword, userstatus,companymid,addedby,addedon,updatedby,updatedon) VALUES ( '$username', '$userdesignation', '$usermobile', '$userloginid', '$usersecurepasword', 'Active','$brmid','0','$mdatetime','0','$mdatetime')";
				if ($conn->query($eve23) === TRUE)
				{
					
				}
		
				$_SESSION['msg'] = "user successfully added.";
			}
			else{
				$_SESSION['msg'] = "error";
			}
	}
	header('Location: businessregister.php');
?>