<?php
//ob_start();
include('includes/session.inc');
$Title = _('Re-Print Quote');
include('includes/SQL_CommonFunctions.inc');


	

	if (isset($_GET['dispatchitemsid'])) {
		$_SESSION['dispatchitemsid'] = stripslashes($_GET['dispatchitemsid']);
	}
	$lineitemid = $_SESSION['dispatchitemsid'];
	
if (isset($_GET['dispatchid'])) {
		$_SESSION['dispatchid'] = stripslashes($_GET['dispatchid']);
	}
	$stockrequestno= $_SESSION['dispatchid'];


//item by item fullfillment

	
	//echo "this is stock request main";
	
	
	

	

	
	
	//get lineitems
		//get stock id
	
	
		$SQL="SELECT *
					FROM stockrequest
					WHERE  dispatchid= '" . $stockrequestno . "'";
			$Result = DB_query($SQL);
$myrow = DB_fetch_array($Result);
	
	$Location= $myrow['loccode'];
	$DI= $myrow['dispatchid'];
		//get department
	
		$SQLde="SELECT departmentname
					FROM department
					WHERE departmentid='" . $myrow['departmentid'] . "'
						";
			$Resultde = DB_query($SQLde);
	$myrowde = DB_fetch_row($Resultde);
	
	$Department= $myrowde['departmentname'];
	$SQLstock="SELECT *
					FROM stockrequestitems
					WHERE dispatchid = '" . $DI . "'
					AND completed = 0";
			$Resultstock = DB_query($SQLstock);
	while ($myrowstock = DB_fetch_assoc($Resultstock)) {
		
		//echo $myrowstock['dispatchitemsid'];
		//echo "<br>";
		    $StockID = $myrowstock['stockid'];
	        $LineID = $myrowstock['dispatchitemsid'];
	      	$Quantity= $myrowstock['quantity'];
	
		    $sql="SELECT materialcost, labourcost, overheadcost, decimalplaces FROM stockmaster WHERE stockid='".$StockID."'";
			$result=DB_query($sql);
			$myrow=DB_fetch_array($result);
			$StandardCost=$myrow['materialcost']+$myrow['labourcost']+$myrow['overheadcost'];
			$DecimalPlaces = $myrow['decimalplaces'];
	         
	
	
	

			$Narrative = _('Issue') . ' ' . $Quantity . ' ' . _('of') . ' '. $StockID . ' ' . _('to department') . ' ' . $Department . ' ' . _('from') . ' ' . $Location. ' ' . _('allocated to') . ' ' . $Jobno ;

			$AdjustmentNumber = GetNextTransNo(52,$db);
			$PeriodNo = GetPeriod (Date($_SESSION['DefaultDateFormat']), $db);
			$SQLAdjustmentDate = FormatDateForSQL(Date($_SESSION['DefaultDateFormat']));

			//$Result = DB_Txn_Begin();

			// Need to get the current location quantity will need it later for the stock movement
			$SQL="SELECT locstock.quantity
					FROM locstock
					WHERE locstock.stockid='" . $StockID . "'
						AND loccode= '" . $Location . "'";
			$Result = DB_query($SQL);
			if (DB_num_rows($Result)==1){
				$LocQtyRow = DB_fetch_row($Result);
				$QtyOnHandPrior = $LocQtyRow[0];
			} else {
				// There must actually be some error this should never happen
				$QtyOnHandPrior = 0;
			}

		

				$SQL = "INSERT INTO stockmoves (
									stockid,
									type,
									transno,
									loccode,
									trandate,
									userid,
									prd,
									reference,
									jobno,
								
									qty,
									newqoh)
								VALUES (
									'" . $StockID . "',
									17,
									'" . $AdjustmentNumber . "',
									'" . $Location . "',
									'" . $SQLAdjustmentDate . "',
									'" . $_SESSION['UserID'] . "',
									'" . $PeriodNo . "',
									'" . $Narrative ."',
									'" . $Jobno ."',
									
									'" . -$Quantity . "',
									'" . ($QtyOnHandPrior - $Quantity) . "'
								)";


				$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock movement record cannot be inserted because');
				$DbgMsg =  _('The following SQL to insert the stock movement record was used');
				$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);


				/*Get the ID of the StockMove... */
				$StkMoveNo = DB_Last_Insert_ID($db,'stockmoves','stkmoveno');
				
				//insert stock in project details 
				
				
				//get costprice
				
				
				 if ($Jobno > 0 ) {
				
				
				$SQL = "INSERT INTO project_stock (
									stockid,
									projectid,
									date_received,
									location_received_from,
									department_received_from,
									qty_received,
									cost_value
							)
								VALUES (
									'" . $StockID . "',
									'" . $Jobno . "',
									'" . $SQLAdjustmentDate . "',
									
									'" . $Location . "',
									'" . $Department. "',
									'" . $Quantity . "',
									'" . $StandardCost * ($Quantity) . "'
								)";


				$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock movement record cannot be inserted because');
				$DbgMsg =  _('The following SQL to insert the stock movement record was used');
				$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);


				
				 }
				
				
				

				$SQL="UPDATE stockrequestitems
						SET completed=1
						WHERE dispatchid ='" . $DI . "'
						AND dispatchitemsid ='" . $LineID . "'";

				$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' ._('The location stock record could not be updated because');
				$DbgMsg = _('The following SQL to update the stock record was used');
				$Result = DB_query($SQL, $ErrMsg, $DbgMsg,true);

				$SQL = "UPDATE locstock SET quantity = quantity - '" . $Quantity . "'
									WHERE stockid='" . $StockID . "'
										AND loccode='" . $Location . "'";

				$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' ._('The location stock record could not be updated because');
				$DbgMsg = _('The following SQL to update the stock record was used');

				$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);

				
					
				
				
					
					
					
				
			

			
		//	echo $StockID.' - '.$AdjustmentNumber.' - '.$Location.' - '.$SQLAdjustmentDate.' - '.$PeriodNo.' - '.$Quantity.' - '.$LineID;
		//echo "<br>";
		
	

		

		
		
	}//end of while statement
	
	
			// Check if request can be closed and close if done.
			
		
					$timenow =time();

		$modifieddatetime = date("Y-m-d h:i:sa", $timenow);
$fijitime = date("d-m-Y h:i:sa", $timenow);
					
					$userid = $_SESSION['UserID'];

$SQLuser = "SELECT email,realname

	               

			FROM www_users

			WHERE userid='" . $userid. "'

			";

	

			$resultuser = DB_query($SQLuser);

	

			$myrowuser = DB_fetch_array($resultuser) ;

		$emailm= $myrowuser['email'];

$realname= $myrowuser['realname'];
					
				
					
				
					
					
					$SQL = "SELECT departmentid,initiator

	               

			FROM stockrequest

			WHERE dispatchid='" . $stockrequestno. "'

			";

	

			$result = DB_query($SQL);

	

			$myrowuser = DB_fetch_array($result) ;

			$departmentid = $myrowuser['departmentid'];

			$initiator = $myrowuser['initiator'];
					
				$EmailSQL="SELECT email

					FROM www_users

					WHERE realname = '" . $initiator."'

						";

		$EmailResult = DB_query($EmailSQL);

			$myEmail=DB_fetch_array($EmailResult);

			

			$initiatoremail = $myEmail['email'];
					
					
					
$EmailSQL1="SELECT email,realname

					FROM www_users, department

					WHERE department.authoriser = www_users.userid

						AND department.departmentid = '" . $departmentid ."'";

		$EmailResult1 = DB_query($EmailSQL1);

			$myEmail1=DB_fetch_array($EmailResult1);

			
$authorisersemail = $myEmail1['email'];
$authorisersname = $myEmail1['realname'];


					
					
  $ravinesh ='rdeo@wormaldfj.com';

	$sharukh ='msharukh@wormaldfj.com';

	$sachin = 'sachin@ebusinesserp.com';

	
	$shiv='shiv.c@wormaldfj.com';
					$mosheed = 'mhussein@wormaldfj.com';

	$joseph='payablewest@wormaldfj.com';
	$vani = 'vrokobaro@wormaldfj.com';
					
						$ConfirmationText = _('This internal stock request- '.$stockrequestno.' has been Fullfilled by : '.$realname.' at '.$fijitime.'.Stock qty has been adjusted. This is for all items in this stockrequest. This was authorised by '.$authorisersname.' and created by: '.$initiator);
	        $EmailSubject = _('Stock Request- '.$stockrequestno.' fulfilled');


		
		       // mail($ravinesh,$EmailSubject,$ConfirmationText);
				// mail($sharukh,$EmailSubject,$ConfirmationText);

				 mail($mosheed,$EmailSubject,$ConfirmationText);

				 mail($sachin,$EmailSubject,$ConfirmationText);

				 mail($initiatoremail,$EmailSubject,$ConfirmationText1);

			 mail($authorisersemail,$EmailSubject,$ConfirmationText);
		

				// mail($initiatoremail,$EmailSubject,$ConfirmationText1);
		
	         //	mail($authorisersemail,$EmailSubject,$ConfirmationText);

	
	
			$SQL1= "UPDATE stockrequest
						SET closed=1,
						fulfilled_by = '".$realname."',
							date_time_fulfilled ='".$modifieddatetime."'
						WHERE dispatchid ='" . $DI. "'";

				$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' ._('The fullfill status stockrequest table record could not be updated because');
				$DbgMsg = _('The following SQL to update the stockrequest closed status record was used');
				$Result1 = DB_query($SQL1, $ErrMsg, $DbgMsg,true);		
					
			//if ($departmentid = 6 || $departmentid = 9 || $departmentid = 8 || $departmentid = 21) {

				  //mail($shiv,$EmailSubject,$ConfirmationText);
				// mail($mosheed,$EmailSubject,$ConfirmationText);
	
			//}

			//	if ($departmentid = 7 || $departmentid = 10 || $departmentid = 2 ) {

				//  mail($vani,$EmailSubject,$ConfirmationText);

				

		//	}

					
					
			//success message and redirect to a page



					
	
				
				
		$message = "Success fulfilling stockrequest no:  ".$stockrequestno.". All items in this stockrequest has been reflected in stock balances.";
echo "<script type='text/javascript'>alert('$message');</script>";
echo "<script type='text/javascript'>javascript:history.go(-1)</script>"; 
		

		

	

//include('includes/footer.inc'); 

?>
