<?php
session_start(); 

	if(!isset($_SESSION['linkarisecrm']))
	{
		header('Location: index.php');
		return;
	}
	
	include("connect.php");
	include("connectp.php");
	include("removespecial.php");
	
	date_default_timezone_set("Asia/Kolkata");
	$mdate1= date('Y-m-d H:i:s');
	$mdate2= date('d-m-Y');
	$cdate= date('Y-m-d');
	
	$par1 = $_SESSION['linkariseumobile'];
	$ipaddress = "";

	if (getenv('HTTP_CLIENT_IP'))
		$ipaddress = getenv('HTTP_CLIENT_IP');
	else if(getenv('HTTP_X_FORWARDED_FOR'))
		$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
	else if(getenv('HTTP_X_FORWARDED'))
		$ipaddress = getenv('HTTP_X_FORWARDED');
	else if(getenv('HTTP_FORWARDED_FOR'))
		$ipaddress = getenv('HTTP_FORWARDED_FOR');
	else if(getenv('HTTP_FORWARDED'))
		$ipaddress = getenv('HTTP_FORWARDED');
	else if(getenv('REMOTE_ADDR'))
		$ipaddress = getenv('REMOTE_ADDR');
	else
		$ipaddress = 'UNKNOWN';
	
	$userserver=$_SERVER['HTTP_USER_AGENT'];
	$eve = "insert into res_user_log (lid,mobile,lastupdatedtime,pagename,taskname,ipaddress,useragentdetail) values(NULL,'$par1','$mdate1','Item','Add Item','$ipaddress','$userserver')";
	$re = mysqli_query($conn, $eve);
	
	
	$itemid=$_POST['itemid'];
	$ioutqty=$_POST['ioutqty'];
	$inqty=$ioutqty;
	$ioutunit="";
	$inunit="";
	$itransremarks=removespecialchar($_POST['itransremarks']);
	$q = $db7->prepare("select * from res_item_master where itemid =:p1");
	$q->bindValue(':p1', "$itemid");
	//$q->bindValue(':p2',  "$par2");
	$q->execute();
	
	$response = array();
	$posts = array();
	
	$result="0";
	
	if ($q->rowCount() > 0)
	{
		$i=1;
		while($i<=$q->rowCount())
		{
			$rt = $q->fetch(PDO::FETCH_ASSOC);
			$iunitmasterstock=$rt['iunitmasterstock'];
			$iunitmaster=$rt['iunitmaster'];
			$iunit1kg=$rt['iunit1kg'];
			
			$iunitnos=$rt['iunitnos'];
			
			break;				
		}
		
		$iunitmasterstock2=$iunitmasterstock-$inqty;
		$eve1 = "INSERT INTO res_item_detail (itemid,itransactiontype,iinouttype,itemtrandate,ioutqty,ioutqtyactual,ioutunit,ioutunitactual,itransremarks,ilateststockback) 
		VALUES('$itemid','Direct Out','Out','$cdate','$ioutqty','$ioutqty','$ioutunit','$iunitmaster','$itransremarks','$iunitmasterstock2')";	
		if ($conn->query($eve1) === TRUE)
		{
			$last_id = $conn->insert_id;
			$eve2 = "update res_item_master set iunitmasterstock=$iunitmasterstock2  where itemid=$itemid";	
			if ($conn->query($eve2) === TRUE)
			{
				$last_id = $conn->insert_id;
				$_SESSION['msg'] = "Record has been added successfully";
			}
		}
		else
		{
			$_SESSION['msg1'] = "Error";
		}
	}
	
	header("Location: item.php");
?>