<?php
require_once("../includes/config.php");
///// check form is post
if($_POST){
	///// check save button is hitted
	if ($_POST['saveButton'] == 'Save'){
		///// extract job no. from post variable
		$docid = base64_decode($_POST['jobno']);
		///// get product planning details
		$job_master = mysqli_fetch_assoc(mysqli_query($link1,"select * from jobcard_master where system_ref_no='".$docid."'"));
		///// make a string token
		$messageIdent = md5($_POST['saveButton'] . $docid);
		//and check it against the stored value:
    	$sessionMessageIdent = isset($_SESSION['bomUseSession'])? $_SESSION['bomUseSession']:'';
    	if($messageIdent != $sessionMessageIdent){//if its different:          
        	//save the session var:
        	$_SESSION['bomUseSession'] = $messageIdent;
			//// initialize transaction parameters
			$flag = true;
			mysqli_autocommit($link1, false);
			$error_msg = "";
			/////// make sub job no. with main job no.
			$rs = mysqli_fetch_assoc(mysqli_query($link1,"SELECT max(temp_no) as doc_count from production_master where location_code ='".$job_master['location_code']."'"));
			$req_no = $rs['doc_count'] + 1;
			//$pad = str_pad($req_no,4,0,STR_PAD_LEFT);
			$docseries = "PR/".$job_master['location_code']."/".$req_no;
			////// maintain production master details
			$result1 = mysqli_query($link1,"insert into production_master set location_code='".$job_master['location_code']."', system_ref_no='".$docseries."', temp_no='".$req_no."', outcome_part='".$job_master['job_part']."', outcome_qty='".$_POST['outcome_qty']."',purchase_unit='".$job_master['purchase_unit']."', entry_by='".$_SESSION['userid']."', entry_date='".$today."',entry_time='".$currtime."',entry_ip='".$ip."',status='14',job_no='".$job_master['system_ref_no']."', planning_no='".$job_master['planning_no']."',bomid='".$job_master['bomid']."',line_no='".$_POST['line_no']."',remark='".$_POST['remark']."'");
			//// check if query is not executed
			if (!$result1) {
				$flag = false;
				$error_msg = "Error Code1: ".mysqli_error($link1);
			}
			////pick part from bom master
			$tot_qty=0;
			$res_bom = mysqli_query($link1,"SELECT id,partcode,conversion_factor,bomperunit,purchase_unit FROM jobcard_data where system_ref_no='".$docid."'");
			while($row_bom = mysqli_fetch_assoc($res_bom)){
				$postpart = "chkbox".$row_bom['id'];
				if($_POST[$postpart]!=""){
					$purqty = $_POST['outcome_qty'] * $row_bom['bomperunit'] * $row_bom['conversion_factor'];
					/////check inventory again
					$avlqty = getInventory($job_master['location_code'],$row_bom['partcode'],"ok_qty",$link1);
					if($avlqty){}else{ $avlqty=0;}
					if($avlqty >= $purqty){
						////// maintain production data details
						$result2 = mysqli_query($link1,"insert into production_data set system_ref_no='".$docseries."', partcode='".$row_bom['partcode']."',conversion_factor='".$row_bom['conversion_factor']."', consume_qty='".$purqty."',purchase_unit='".$row_bom['purchase_unit']."', part_type='BOM PART'");
						//// check if query is not executed
						if (!$result2) {
							$flag = false;
							$error_msg = "Error Code2: ".mysqli_error($link1);
						}
						////// update job card details
						$result3 = mysqli_query($link1,"update jobcard_data set consume_qty = consume_qty + '".$purqty."' where id = '".$row_bom['id']."'");
						//// check if query is not executed
						if (!$result3) {
							$flag = false;
							$error_msg = "Error Code3: ".mysqli_error($link1);
						}
						//----------------------------- inventory upadate------------------------//
						$sql_invt = "UPDATE inventory_status set ok_qty = ok_qty - '".$purqty."',updatedate='" . $datetime . "' where partcode='".$row_bom['partcode']."' and location_code='".$job_master['location_code']."' and  ok_qty >= '".$purqty."'";
						$res_invt = mysqli_query($link1,$sql_invt);
						//// check if query is not executed
						if (!$res_invt) {
							$flag = false;
							$error_msg = "Error details5: " . mysqli_error($link1) . ".";
						}
						////// insert in stock ledger table////
						if($purqty > 0){
							$result = stockLedger($docseries,$today,$row_bom['partcode'],$job_master['location_code'],$job_master['location_code'],"OUT","OK","READY STOCK","ADD",$purqty,"0.00",$_SESSION['userid'],$today,$currtime,$ip,$link1,$flag);
							$expld = explode("~",$result);
							$flag = $expld[0];
							$error_msg = $expld[1];
						}
						$tot_qty +=$purqty;
					}else{
						$flag = false;
						$error_msg = "Error details4: Qty is not available as you selected for ".$row_bom['partcode']."";
					}
				}
			}////close bom while loop
			///// update job FG or SFG in master
			$res_req = mysqli_query($link1,"update jobcard_master set ready_qty = ready_qty+'".$_POST['outcome_qty']."', bal_qty = bal_qty-'".$_POST['outcome_qty']."' where system_ref_no='".$job_master['system_ref_no']."'");
			//// check if query is not executed
			if (!$req_res) {
				$flag = false;
				$err_msg = "Error Code4.1:";
			}
			/////// update job FG or SFG in inventory
			if(mysqli_num_rows(mysqli_query($link1,"select id from inventory_status where partcode='".$job_master['job_part']."' and location_code='".$job_master['location_code']."'"))>0){
				$res_invty = mysqli_query($link1,"UPDATE inventory_status set ok_qty = ok_qty + '".$_POST['outcome_qty']."', updatedate='" . $datetime . "' where partcode='".$job_master['job_part']."' and location_code='".$job_master['location_code']."'");
			}else{
				$stk_typ = getAnyDetails($job_master['job_part'],"itemtypeid","partcode","partcode_master",$link1);
				$res_invty = mysqli_query($link1,"INSERT INTO inventory_status set ok_qty = '".$_POST['outcome_qty']."', partcode='".$job_master['job_part']."', location_code='".$job_master['location_code']."', updatedate='" . $datetime . "', purchase_unit= '".$job_master['purchase_unit']."', stock_type = '".$stk_typ."'");
			}
			///// update job FG or SFG in stock ledger
			$result = stockLedger($docseries,$today,$job_master['job_part'],$job_master['location_code'],$job_master['location_code'],"IN","OK","READY STOCK","ADD",$_POST['outcome_qty'],"0.00",$_SESSION['userid'],$today,$currtime,$ip,$link1,$flag);
			$expld = explode("~",$result);
			$flag = $expld[0];
			$error_msg = $expld[1];
			/////// update consumable items
			/////////Additional row Details///////////
			if(is_array($_POST['consum_partcode'])){
				$additem_id = $_POST['consum_partcode'];
				$addcf = $_POST['consum_cf'];
				$addqty = $_POST['consum_bom_qty'];
				$adduom = $_POST['consum_purchase_unit'];
				$len = count($_POST['consum_partcode']);
				if($len > 0){
					for($i = 0 ;$i < $len; $i++){
						$partcode = $additem_id[$i];
						$cf = $addcf[$i];
						$quan = $addqty[$i];
						$uom = $adduom[$i];
						if($quan!=""){
							if($quan > 0){
								$expl_part = explode("~",$partcode);
								/////check inventory again
								$avlqty = getInventory($job_master['location_code'],$expl_part[0],"ok_qty",$link1);
								if($avlqty){}else{ $avlqty=0;}
								if($avlqty >= $quan){
									////insert additional details into BOM request/////
									$req_res=mysqli_query($link1,"insert into production_data set system_ref_no='".$docseries."', partcode='".$expl_part[0]."',conversion_factor='".$cf."', consume_qty='".$quan."',purchase_unit='".$expl_part[2]."', part_type='CONSUME PART'");
									//// check if query is not executed
									if (!$req_res) {
										$flag = false;
										$error_msg = "Error details6: " . mysqli_error($link1) . ".";
									}
									//// update consumable inventory
									$req_res=mysqli_query($link1,"update inventory_status set ok_qty = ok_qty-'".$quan."',updatedate='" . $datetime . "' where location_code='".$job_master['location_code']."' and partcode='".$expl_part[0]."' and stock_type='1' and ok_qty > '".$quan."'");
									//// check if query is not executed
									if (!$req_res) {
										$flag = false;
										$error_msg = "Error details7: " . mysqli_error($link1) . ".";
									}
									////// insert in stock ledger table////
									if($quan > 0){
										$result = stockLedger($docseries,$today,$expl_part[0],$job_master['location_code'],$job_master['location_code'],"OUT","OK","READY STOCK","ADD",$quan,"0.00",$_SESSION['userid'],$today,$currtime,$ip,$link1,$flag);
										$expld = explode("~",$result);
										$flag = $expld[0];
										$error_msg = $expld[1];
									}
								}else{
									$flag = false;
									$error_msg = "Error details8: Qty is not available as you selected for ".$expl_part[0]."";
								}
							}//close if
						}//close if
					}//close for
				}//close if
			}//close if
			/////// Generate Scrap items
			/////////Additional row Details///////////
			if(is_array($_POST['scrap_partcode'])){
				$additem_id = $_POST['scrap_partcode'];
				$addcf = $_POST['scrap_cf'];
				$addqty = $_POST['scrap_pur_qty'];
				$adduom = $_POST['scrap_purchase_unit'];
				$len = count($_POST['scrap_partcode']);
				if($len > 0){
					for($i = 0; $i < $len; $i++){
						$partcode = $additem_id[$i];
						$cf = $addcf[$i];
						$quan = $addqty[$i];
						$uom = $adduom[$i];
						if($quan!=""){
							if($quan > 0){
								$expl_part = explode("~",$partcode);
								////insert additional details into BOM request/////
								$req_res=mysqli_query($link1,"insert into production_data set system_ref_no='".$docseries."', partcode='".$expl_part[0]."',conversion_factor='".$cf."', consume_qty='".$quan."',purchase_unit='".$expl_part[2]."', part_type='SCRAP PART'");
								//// check if query is not executed
								if (!$req_res) {
									$flag = false;
									$error_msg = "Error details9: " . mysqli_error($link1) . ".";
								}
								//// update scrap inventory
								////// search partcode is abailavel or not ///
								$checkid=mysqli_fetch_array(mysqli_query($link1,"select id from inventory_status where  partcode='".$expl_part[0]."' and location_code='".$job_master['location_code']."' "));
								if($checkid['id']==""){
									/////// get stock type from partcode master /////
									$stk_typ = getAnyDetails($expl_part[0],"itemtypeid","partcode","partcode_master",$link1);
									////////// inventory insert ///////////
									$sql_invt = "INSERT INTO inventory_status set ok_qty = '".$quan."', partcode='".$expl_part[0]."', location_code='".$job_master['location_code']."', updatedate='" . $datetime . "', purchase_unit= '".$expl_part[2]."', stock_type = '".$stk_typ."' ";
									$res_invt = mysqli_query($link1,$sql_invt);
								}else{
									////////// inventory upadate ///////////
									$sql_invt = "UPDATE inventory_status set ok_qty = ok_qty + '".$quan."', updatedate='" . $datetime . "' where partcode='".$expl_part[0]."' and location_code='".$job_master['location_code']."' ";
									$res_invt = mysqli_query($link1,$sql_invt);
								}
								//// check if query is not executed
								if (!$res_invt) {
									$flag = false;
									$error_msg = "Error details10: " . mysqli_error($link1) . ".";
								}
								////// insert in stock ledger table////
								if($quan > 0){
									$result = stockLedger($docseries,$today,$expl_part[0],$job_master['location_code'],$job_master['location_code'],"IN","OK","READY STOCK","ADD",$quan,"0.00",$_SESSION['userid'],$today,$currtime,$ip,$link1,$flag);
									$expld = explode("~",$result);
									$flag = $expld[0];
									$error_msg = $expld[1];
								}
							}
						}
					}
				}
			}
			//// check selected BOM USE qty should not be blank atleast one is selected
			if($tot_qty == 0){
				$flag = false;
				$error_msg = "Error details5.1: You have not selected any part in BOM USE";
			}
			////// insert in activity table////
			$flag =	dailyActivity($_SESSION['userid'],$docseries,"READY STOCK","ADD",$ip,$link1,$flag);
			///// insert in job history
			$flag =	jobHistory($job_master['system_ref_no'],$job_master['location_code'],"READY STOCK CREATE","14",$docseries,$_SESSION['userid'],$ip,$link1,$flag);
			///// check both master and data query are successfully executed
			if ($flag) {
				mysqli_commit($link1);
				$msg = "Stock is successfully Ready against Job Card ".$job_master['system_ref_no'];
				$cflag="success";
				$cmsg = "Success";
			} else {
				mysqli_rollback($link1);
				$msg = "Request could not be processed ".$error_msg.". Please try again.";
				$cflag="danger";
				$cmsg = "Failed";
			} 
			mysqli_close($link1);
		}else {
        	//you've sent this already!
  			$msg = "Re-submission is not allowed";
			$cflag="warning";
			$cmsg = "Warning";
    	}
		///// move to parent page
    	header("location:store_job_list.php?msg=".$msg."&chkflag=".$cflag."&chkmsg=".$cmsg."".$pagenav);
    	exit;
	}
}
?>