<?php
require_once("../includes/config.php");
///// get access location details
$access_loc = getAccessLocation($_SESSION['userid'], $link1);
/////////check approval is applicable or not
$apply_app = getAnyDetails(base64_decode($_REQUEST['pid']),"apply_approval","tabid","tab_master",$link1);
//////////////
if (isset($_REQUEST['location'])) {
    $selloc = $_REQUEST['location'];
} else {
    $selloc = "";
}
if (isset($_REQUEST['stock_type'])) {
    $selstoktyp = $_REQUEST['stock_type'];
} else {
    $selstoktyp = "";
}
$stock = explode(" ", $selstoktyp);
if ($stock[0] == 'Fresh') {
    $select_field = "ok_qty";
} else if ($stock[0] == 'Damage') {
    $select_field = "damage_qty";
}
////// if we want to Add stock conversion
if ($_POST) {
    if ($_REQUEST['save'] == 'Save') {
        //// initialize transaction parameters
        $flag = true;
        mysqli_autocommit($link1, false);
        $err_msg = "";
		if($apply_app=="Y"){ $current_status = 3;}else{ $current_status = 4;}
        //// check atleast one entry should be done
        if (is_array($_POST['avil_stock'])) {
            $location = $_POST['location'];
            $stock_type = $_POST['stock_type'];
            $remark = $_POST['remark'];
            $len = count($_POST['avil_stock']);
            if ($len > 0) {
                /////// pick stock conversion series from document counter
                $rs = mysqli_fetch_array(mysqli_query($link1, "SELECT doc_str,doc_count from document_counter where doc_type='SC' and location_code='" . $location . "'"));
                if ($rs['doc_str']) {
                    $req_no = $rs['doc_count'] + 1;
                    $request_no = $rs['doc_str'] . str_pad($req_no, 5, 0, STR_PAD_LEFT);
                    // insert request no detail in parent table \\
                    $req_res1 = mysqli_query($link1, "INSERT INTO stock_conversion_master set location_code='" . $location . "',conversion_type='" . $stock_type . "', system_ref_no='" . $request_no . "', status='".$current_status."',remark='" . $remark . "',entry_date='" . $today . "',entry_time='" . $currtime . "',entry_by='" . $_SESSION['userid'] . "',entry_ip='" . $ip . "'");
                    //// check if query is not executed
                    if (!$req_res1) {
                        $flag = false;
                        $err_msg = "Error Code1: " . mysqli_error($link1);
                    }
                    ////// pick all parts and insert in data table
                    //$total_qty = 0;
                    for ($i = 0; $i < $len; $i++) {
                        $item = $_POST['part'][$i];
                        $qty = $_POST['conver_qty'][$i];
                        if ($item != "" && $qty != "0") {
                            // insert model qty detail in child table \\
                            $req_res2 = mysqli_query($link1, "INSERT INTO stock_conversion_data set system_ref_no='" . $request_no . "', partcode='" . $item . "', qty='" . $qty . "',conversion_type='" . $stock_type . "'");
                            //// check if query is not executed
                            if (!$req_res2) {
                                $flag = false;
                                $err_msg = "Error Code2: " . mysqli_error($link1);
                            }
                        
                        }
                    }// close for loop
                } else {
                    $flag = false;
                    $err_msg = "Error Code2.1 :Document series not found for request to location.";
                }
            }//if($total_qty == 0)
            else {
                $flag = false;
                $err_msg = "Error Code4: You have not selected any part.";
            }
        }
        //update document count
        $req_res3 = mysqli_query($link1, "UPDATE document_counter set doc_count = doc_count+1 where doc_type='SC' and location_code='" . $location . "'");
        if (!$req_res3) {
            $flag = false;
            $err_msg = "Error Code3: " . mysqli_error($link1);
        }

        ////// insert in activity table////
        $flag = dailyActivity($_SESSION['userid'], $request_no, "STOCK CONVERSION", "ADD", $ip, $link1, $flag);
        ///// check both master and data query are successfully executed
        if ($flag) {
            mysqli_commit($link1);
            $msg = "Stock Conversion Request is created with ref. no. " . $request_no;
            $cflag = "success";
            $cmsg = "Success";
        } else {
            mysqli_rollback($link1);
            $msg = "Request could not be processed " . $err_msg . ". Please try again.";
            $cflag = "danger";
            $cmsg = "Failed";
        }
        mysqli_close($link1);
        ///// move to parent page
        header("location:stock_conversion_list.php?msg=" . $msg . "&chkflag=" . $cflag . "&chkmsg=" . $cmsg . "" . $pagenav);
        exit;
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title><?= siteTitle ?></title>
        <link rel="shortcut icon" href="../images/titleimg.png" type="image/png">
        <script src="../js/jquery.js"></script>
<?php
include("../includes/fontawesome.html");
include("../includes/main_css.html");
include("../includes/bootstrap.html");
?>
<script>
///// after hit submit button processing image will show
$(document).ready(function () {
	var spinner = $('#loader');
    $("#frm1").validate({
    	submitHandler: function (form) {
        	if (!this.wasSent) {
            	this.wasSent = true;
                $(':submit', form).val('Please wait...')
                                  .attr('disabled', 'disabled')
                                  .addClass('disabled');
                spinner.show();
                form.submit();
			} else {
             	return false;
			}
		}
	});
});
////// force to enter number value upto 6 places
$(document).ready(function () {
	$('.number').on('input', function () {
		match = (/(\d{0,10})[^.]*((?:\.\d{0,6})?)/g).exec(this.value.replace(/[^\d.]/g, ''));
		this.value = match[1] + match[2];
	});
});
/////// add new row 
$(document).ready(function () {
	$("#add_row").click(function () {
		var numi = document.getElementById('rowno');
		var itm = "part[" + numi.value + "]";
		var preno = document.getElementById('rowno').value;
		var num = (document.getElementById("rowno").value - 1) + 2;
		numi.value = num;
		if ((document.getElementById(itm).value != "") || ($("#addr1_" + numi.value + ":visible").length == 0)) {
			var r = '<tr id="addr1_' + num + '"><td width="30%"><div style="display:inline-block;float:right;width: 90%;"><select name="part[' + num + ']" id="part[' + num + ']" class="form-control required selectpicker show-tick" required style="display: block !important;" onChange="getStock(' + num + ');getQty();"><option value="">--Select Part--</option><?php $res_pro = mysqli_query($link1, "select partcode,part_name,bom_unit,purchase_unit from partcode_master where status='1' order by part_name")or die(mysqli_error($link1));
while ($row_pro = mysqli_fetch_assoc($res_pro)) { ?><option value="<?= $row_pro['partcode'] ?>"><?= $row_pro['part_name'] . " (" . $row_pro['partcode'] . ")" ?></option><?php } ?></select></div><div style="display:inline-block;float:left;"><i class="fa fa-close fa-lg" onClick="fun_remove(' + num + ');"></i></div></td><td width="15%"><input type="text" name="avil_stock[' + num + ']" class="form-control number required" required readonly  id="avil_stock[' + num + ']" /></td><td width="15%"><input type="text" name="conver_qty[' + num + ']" class="form-control number required" required id="conver_qty[' + num + ']" onkeyup="getQty()"/><p id="error_qty[' + num + ']" style="color:red"></p></td></tr>';
			$('#itemsTable1').append(r);
			makedropdown();
		}
	});
});
/////// remove new added row
function fun_remove(con) {
	var c = document.getElementById('addr1_' + con);
	c.parentNode.removeChild(c);
	con--;
	document.getElementById('rowno').value = con;
}
///// make dynamic dropdown
function makedropdown() {
	$('.selectpicker').selectpicker({
		liveSearch: true
	});
}
////// get part inventory
function getStock(indxx) {
	var locc = document.getElementById("location").value;
	var selpart = document.getElementById("part["+indxx+"]").value;
	var stock11 = '<?=$select_field?>';
	//alert(stock11);
	if(locc == ''){
	   alert("Please select location!"); 
	}else if(stock11==''){
	   alert("Please select conversion type!"); 
	}else{
		$.ajax({
			type: 'post',
			data: {avl_stock: selpart, indx: indxx, loc: locc},
			url: '../includes/getAzaxFields.php',
			asyn: false,
			success: function (data) {
				var stk = data.split("~");
				if(stock11=="ok_qty"){ 
					document.getElementById("avil_stock[" + indxx + "]").value = stk[1];
				}else{
					document.getElementById("avil_stock[" + indxx + "]").value = stk[2];
				}
			}
		});
	}
	checkDuplicatePart(indxx, selpart);
}
///// function for checking duplicate partcode
function checkDuplicatePart(fldIndx1, val) {
	if (val != '') {
		var check2 = "part[" + fldIndx1 + "]";
		var qty12 = "avil_stock[" + fldIndx1 + "]";
		var flag = 1;
		for (var i = 0; i <= fldIndx1; i++) {
			var check1 = "part[" + i + "]";
		
			if (fldIndx1 != i && document.getElementById(check2).value != '' && document.getElementById(check1).value != '') {
				if ((document.getElementById(check2).value == document.getElementById(check1).value)) {

					document.getElementById("error_msg").innerHTML = "Duplicate Part selection";
					document.getElementById(check2).value = "";
					document.getElementById(qty12).value = "0.00";
					flag *= 0;
				} else {
					document.getElementById("error_msg").innerHTML = "";
					flag *= 1;
					///do nothing
				}
			}
		}//// close for loop
		if (flag == 0) {
			return false;
		} else {
			return true;
		}
	}
}
////////////////// Calculate Tax/////////////////////
                function checkAllRows() {
                    var rowno1 = document.getElementById("rowno").value;
                    var flag = 1;
                    if (rowno1 >= 0) {
                        for (var j = 0; j < rowno1; j++) {
							var convqty = "conver_qty[" + j + "]";
							var avlqty = "avil_stock[" + i + "]";
                            var check2 = "part[" + j + "]";
                            for (var i = 0; i <= rowno1; i++) {
                                if (j != i) {
                                    var check1 = "part[" + i + "]";
                                    var rqty = "avil_stock[" + i + "]";
                                    if (document.getElementById(check2).value == document.getElementById(check1).value) {
                                        document.getElementById("error_msg").innerHTML = "Duplicate Part selection";
                                        document.getElementById(check1).value = "";
                                        document.getElementById(rqty).value = '';
                                        flag *= 0;
                                    }else {
                                        flag *= 1;
                                    }
                                }
                            }
							alert(parseFloat(document.getElementById(avlqty).value,6) +"<"+ parseFloat(document.getElementById(convqty).value,6));
							if(parseFloat(document.getElementById(avlqty).value,6) < parseFloat(document.getElementById(convqty).value,6)){
								flag *= 0;
							}
                        }
                        if (flag == 0) {
							$("#save").attr("disabled","disabled");
                            return false;
                        } else {
							$("#save").removeAttr("disabled");
                            return true;
                        }
                    }
                }
function getQty(){
	var max_cnt = document.getElementById("rowno").value;
	var flg=1;
	for(var i=0; i<=max_cnt; i++){
		if(document.getElementById("avil_stock["+i+"]").value){
			var avlqty = parseFloat(document.getElementById("avil_stock["+i+"]").value,6);
		}else{
			var avlqty = 0;
		}
		if(document.getElementById("conver_qty["+i+"]").value){
			var val = parseFloat(document.getElementById("conver_qty["+i+"]").value,6);
		}else{
			var val = 0;
		}
		//alert(rq_qt_dt +"<"+ val);
		if(avlqty < val){
			document.getElementById("error_qty["+i+"]").innerHTML = "Conversion qty should be less than available qty.";
			document.getElementById("error_qty["+i+"]").style.display = "block";
			flg *=0;
		}else{
			document.getElementById("error_qty["+i+"]").innerHTML = "";
			document.getElementById("error_qty["+i+"]").style.display = "none";	
			flg *=1;
		}
	}
	/////
	if(flg==1){
		document.getElementById("save").disabled = false;
	}else{
		document.getElementById("save").disabled = true;
	}
}				
        </script>
        <script src="../js/bootstrap-select.js"></script>
        <link href="../css/bootstrap-select.css" rel="stylesheet"/>
        <script src="../js/jquery.validate.js"></script>
        <link href="../css/loader.css" rel="stylesheet"/>
    </head>
    <body>
        <div class="container-fluid">
            <div class="row content">
<?php
include("../includes/leftnav_admin.php");
?>
                <div class="<?= $screenwidth ?>">
                    <h2 align="center"><i class="fa <?= $fa_icon ?>"></i> Add Stock Conversion</h2><br/>
                    <div class="form-group"  id="page-wrap" style="margin-left:10px;">
                        <form id="frm1" name="frm1" class="form-horizontal" action="" method="post">
                            <div class="form-group">         
                                <div class="col-md-6"><label class="col-md-5 control-label">Location</label>
                                    <div class="col-md-6" align="left">
                                        <select name="location" id="location" class="form-control custom-select required" onchange="this.form.submit()">
                                            <option value=''>--Please Select--</option>
<?php
$res_maploc = mysqli_query($link1, "select location_code,locationname from location_master where statusid='1' and location_code in (" . $access_loc . ") order by locationname ");
while ($row_maploc = mysqli_fetch_assoc($res_maploc)) {
    ?>
                                                <option value="<?= $row_maploc['location_code'] ?>" <?php if ($selloc == $row_maploc['location_code']) {
        echo 'selected';
    } ?>><?= $row_maploc['locationname'] . " (" . $row_maploc['location_code'] . ")" ?></option>
<?php } ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6"><label class="col-md-5 control-label"> Conversion Type </label>	  
                                    <div class="col-md-6" align="left">
                                        <select name="stock_type" id="stock_type" class="form-control custom-select required" onchange="this.form.submit()">
                                            <option value=''>--Please Select--</option>               	    
                                            <option value="Fresh To Damage" <?php if ($selstoktyp == "Fresh To Damage") {
    echo 'selected';
} ?>>Fresh To Damage</option>    
                                            <option value="Damage To Fresh" <?php if ($selstoktyp == "Damage To Fresh") {
    echo 'selected';
} ?>>Damage To Fresh</option>                    
                                        </select>
                                    </div>
                                </div>
                                <span id="error_msg" class="red_small" style="margin-left: 420px;"><?= $msg ?></span>
                            </div><!--close form group-->
                            <div class="form-group">
                                <div class="col-md-12">
                                    <table class="table table-bordered" width="100%" id="itemsTable1">
                                        <thead>
                                            <tr class="<?= $tableheadcolor ?>">
                                                <th width="30%">Partcode</th>
                                                <th width="15%">Available Stock</th>
                                                <th width="15%">Conversion Qty</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr id="addr1_0">
                                                <td width="30%">
                                                    <select name="part[0]" id="part[0]" class="form-control required selectpicker show-tick" required onChange="getStock(0);getQty();">
                                                        <option value="">--Select Part--</option>
<?php
$res_pro = mysqli_query($link1, "select partcode,part_name from partcode_master where  status='1' order by part_name")or die(mysqli_error($link1));
while ($row_pro = mysqli_fetch_assoc($res_pro)) {
    ?>
                                                            <option value="<?= $row_pro['partcode'] ?>"><?= $row_pro['part_name'] . " (" . $row_pro['partcode'] . ")" ?></option>
<?php } ?>
                                                    </select></td>
                                                <td width="15%">
                                                    <input type="text" name="avil_stock[0]" class="form-control number required" required readonly id="avil_stock[0]"/>
                                                </td>
                                                <td width="15%">
                                                    <input type="text" name="conver_qty[0]" class="form-control number required" required id="conver_qty[0]" onkeyup="getQty()"/>
                                                    <p id="error_qty[0]" style="color:red"></p>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-12">
                                    <div class="col-md-4">
                                        <button class='btn<?= $btncolor ?>' id="add_row" type="button" name="add" value="Add"><i class="fa fa-plus-circle fa-lg"></i>&nbsp;&nbsp;Add Stock Part</button>
                                        <input type="hidden" name="rowno" id="rowno" value="0"/>
                                    </div>
                                    <div class="col-md-6"><label class="col-md-3 control-label"> Remark </label>
                                        <div class="col-md-8" align="left">
                                        <textarea name="remark" id="remark" class="form-control addressfield"></textarea>
                                        </div>
                                        </div>
                                </div>
                            </div>          


                            <div class="form-group">
                                <div class="col-md-4" style="display:inline-block; float:left">

                                </div>
                                <div class="col-md-8" style="display:inline-block; float:right" align="left">
                                    <button class='btn<?= $btncolor ?>' id="save" type="submit" name="save" value="Save" onClick="checkAllRows();"><i class="fa fa-save fa-lg"></i>&nbsp;&nbsp;Save</button>
                                    <button title="Back" type="button" class="btn<?= $btncolor ?>" onClick="window.location.href = 'stock_conversion_list.php?<?= $pagenav ?>'"><i class="fa fa-reply fa-lg"></i>&nbsp;&nbsp;Back</button>
                                </div>
                            </div>
                        </form>
                    </div>

                </div>

            </div>
        </div>
        <div id="loader"></div>
<?php
include("../includes/footer.php");
include("../includes/connection_close.php");
?>
    </body>
</html>