<?php
require_once("../includes/config.php");
$docid = base64_decode($_REQUEST['id']);
//// bin allocation details
$sql_bindet = "SELECT * FROM bin_allocation where partcode='" . $docid . "'";
$res_bindet = mysqli_query($link1, $sql_bindet);

$res = mysqli_query($link1, "select brandid,productid,psubcatid,itemtypeid from partcode_master where partcode='" . $docid . "'");
$row = mysqli_fetch_assoc($res);
/////////////// after hitting save button
if ($_POST) {
	if ($_POST['saveButton'] == 'Save') {
		///// make a string token
        $msgToken = md5($_POST['saveButton'] . $_POST['changebin_id'] . $_POST['partcode']);
        //and check it against the stored value:
        $sessionMsgToken = isset($_SESSION['changeBinToken']) ? $_SESSION['changeBinToken'] : '';
        if ($msgToken != $sessionMsgToken) {//if its different:          
		//save the session var:
		$_SESSION['changeBinToken'] = $msgToken;
    	//// initialize transaction parameters
        $flag = true;
        mysqli_autocommit($link1, false);
        $err_msg = "";
        //// check atleast one entry should be done 
        $loc = $_POST['location_code'];
        $item = $_POST['partcode'];
        $bin_no = $_POST['bin_no'];
        
        $bin_qty = $_POST['bin_qty'];
        $sum_qty = array_sum($_POST['qty']);
        $len = count($_POST['qty']);
        ////////// check change qty with available bin qty
        if ($bin_qty >= $sum_qty) {
        	////// pick all bins and insert in change bin table
            for ($i = 0; $i < $len; $i++) {
                $stock_type = $_POST['stock_type'][$i];
                $bin = $_POST['bin_no'][$i];
                $qty = $_POST['qty'][$i];
                if ($bin != "" && $qty!=0) {
                	$bin_id = getAnyDetails($bin, "bin_id", "bin_no", "bin_master", $link1);
                    /// update request no detail in bin allocation table \\					
                    $req_res1 = mysqli_query($link1, "UPDATE bin_allocation set qty=qty-$qty where location_code='" . $loc . "' and partcode='" . $item . "' and stock_type='" . $stock_type . "' and bin_id='".$_POST['changebin_id']."'");
                    //// check if query is not executed
                    if (!$req_res1) {
                        $flag = false;
                        $err_msg = "Error Code1: " . mysqli_error($link1);
                    }
                    $res = mysqli_fetch_array(mysqli_query($link1, "SELECT bin_id from bin_allocation where location_code='" . $loc . "' and partcode='" . $item . "' and bin_id='" . $bin_id . "' and stock_type='" . $stock_type . "'"));
                    if ($res['bin_id'] == "") {
                    	// insert request no detail in bin allocation table \\	
                    	$req_res3 = mysqli_query($link1, "INSERT INTO bin_allocation set  bin_id='" . $bin_id . "',location_code='" . $loc . "', partcode='" . $item . "', stock_type='" . $stock_type . "',qty='" . $qty . "',update_by ='" . $_SESSION['userid'] . "' , update_date ='" . $datetime . "'");
                    	//// check if query is not executed
                    	if (!$req_res3) {
                        	$flag = false;
                        	$err_msg = "Error Code3: " . mysqli_error($link1);
                    	}
                    }else {

                        echo "UPDATE bin_allocation set qty=qty+$qty ,update_by ='" . $_SESSION['userid'] . "' , update_date ='" . $datetime . "' where location_code='" . $loc . "' and partcode='" . $item . "' and stock_type='" . $stock_type . "' and bin_id='" . $bin_id . "'";
                    	// update request no detail in bin allocation table \\					
                    	$req_res4 = mysqli_query($link1, "UPDATE bin_allocation set qty=qty+$qty ,update_by ='" . $_SESSION['userid'] . "' , update_date ='" . $datetime . "' where location_code='" . $loc . "' and partcode='" . $item . "' and stock_type='" . $stock_type . "' and bin_id='" . $bin_id . "'");
                    	//// check if query is not executed
                    	if (!$req_res4) {
                        	$flag = false;
                        	$err_msg = "Error Code4: " . mysqli_error($link1);
						}
					}
					// insert change bin table \\
					$req_res2 = mysqli_query($link1, "INSERT INTO change_bin set location_code='" . $loc . "', partcode='" . $item . "', bin_no='" . $bin . "',bin_qty='" . $qty . "',ref_bin ='" . $_POST['ref_no'] . "',action ='IN',updatedate ='" . $datetime . "'");
					 //// check if query is not executed
					if (!$req_res2) {
						$flag = false;
						$err_msg = "Error Code2: " . mysqli_error($link1);
					}
                }
            }// close for loop
        }else {
			$flag = false;
        	//you've sent this already!
        	$err_msg = "Change bin qty should not greater than current bin qty";
		}
        ////// insert in activity table////
        $flag = dailyActivity($_SESSION['userid'], $_POST['ref_no'], "BIN CHANGE", "UPDATE", $ip, $link1, $flag);
        ///// check both master and data query are successfully executed
        if ($flag) {
            mysqli_commit($link1);
            $msg = "Bin ".$_POST['ref_no']." is successfully changed.";
            $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);
    } else {
        //you've sent this already!
        $msg = "Re-submission is not allowed";
        $cflag = "warning";
        $cmsg = "Warning";
    }
    ///// move to parent page
    header("location:inventory_status.php?location=" . $_REQUEST['location'] . "&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>

            ////// function for open model to vendor prices details
            function openModel(docid, stock, location,binid) {
                $.get('bin_change.php?doc_id=' + docid + '&stock_type=' + stock + '&loc=' + location +'&bin_id='+ binid, function (html) {
                    $('#courierModel .modal-body').html(html);
                    $('#courierModel').modal({
                        show: true,
                        backdrop: "static"
                    });
                });

            }
        </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> Current Bin</h2><br/>
                   
                    <div class="form-group"  id="page-wrap" style="margin-left:10px;">
                        <div class="panel-group">
                            <div class="panel panel-success table-responsive">
                                <div class="panel-heading"><i class="fa fa-newspaper-o fa-lg"></i>&nbsp;&nbsp;Current Bin</div>
                                <div class="panel-body">
                                    <table class="table table-bordered" width="100%">
                                        <tbody>
                                            <tr>
                                                <td width="20%"><label class="control-label">Product</label></td>
                                                <td width="30%">
                                                    <?= getAnyDetails($docid, "part_name", "partcode", "partcode_master", $link1) . "(" . $docid . ")"; ?>

                                                </td>
                                                <td width="20%"><label class="control-label">Brand</label></td>
                                                <td width="30%">
                                                    <?= getAnyDetails($row["brandid"], "brand", "brandid", "brand_master", $link1); ?></td>
                                            </tr>
                                            <tr>
                                                <td width="20%"><label class="control-label">Product Category</label></td>
                                                <td width="30%"><?= getAnyDetails($row["productid"], "product_name", "productid", "product_master", $link1); ?>
                                                </td>
                                                <td width="20%"><label class="control-label">Product Sub Category</label></td>
                                                <td width="30%"><?= getAnyDetails($row["psubcatid"], "prod_sub_cat", "psubcatid", "product_sub_category", $link1); ?>
                                                </td>
                                            </tr>

                                        </tbody>
                                    </table>
                                </div><!--close panel body-->
                            </div><!--close panel-->
                        </div>

                        <div class="form-group">
                            <div class="col-md-12">
                                <table class="table table-bordered" width="100%">
                                    <thead>
                                        <tr class="<?= $tableheadcolor ?>">
                                            <th width="20%" style="text-align: center;">Current Bin No.</th>
                                            <th width="20%" style="text-align: center;">Current Bin QTY</th>
                                            <th width="20%" style="text-align: center;">Stock Type</th>
                                            <th width="20%" style="text-align: center;">Change Bin</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $i = 0;
                                        while ($row_bindet = mysqli_fetch_assoc($res_bindet)) {
                                            ?>
                                            <tr>
                                                <td width="26%">
                                                    <?php echo $bin_no = getAnyDetails($row_bindet["bin_id"], "bin_no", "bin_id", "bin_master", $link1); ?>  
                                                </td>
                                                <td width="10%" style="text-align: right;"><?= $row_bindet["qty"] ?></td>
                                                <td width="10%" style="text-align: center;">
                                                    <?php
                                                    if ($row_bindet["stock_type"] == 'ok-qty') {
                                                        echo 'Ok';
                                                    }else if ($row_bindet["stock_type"] == 'damage-qty') {
                                                        echo 'IQC Rejection';
                                                    }else if ($row_bindet["stock_type"] == 'faulty-qty') {
                                                        echo 'Vender Rejection';
                                                    } else {
                                                        echo 'Process Rejection';
                                                    }
                                                    ?>  
                                                </td>
                                                <td width="10%" style="text-align: center;"><a href='#' onClick ="openModel('<?= $docid ?>', '<?= $row_bindet["stock_type"] ?>', '<?= $row_bindet["location_code"] ?>','<?=$row_bindet["bin_id"]?>')" title='Change Bin'><i class='fa fa-exchange fa-lg faicon' title='Change Bin'></i></a>
                                                </td>
                                            </tr>
                                            <?php
                                            $i++;
                                        }
                                        ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-5" style="display:inline-block; float:left"></div>
                            <div class="col-md-7" style="display:inline-block; float:right" align="left">
                                <button title="Back" type="button" class="btn<?= $btncolor ?>" onClick="window.location.href = 'inventory_status.php?location=<?= $_REQUEST['location'] ?>&stock_type=<?= $_REQUEST['stock_type'] ?>&prod_cat=<?= $_REQUEST['prod_cat'] ?>&product_sub_category=<?= $_REQUEST['product_sub_category'] ?>&brandname=<?= $_REQUEST['brandname'] ?><?= $pagenav ?>'"><i class="fa fa-reply fa-lg"></i>&nbsp;&nbsp;Back</button>
                            </div>
                        </div>

                        <!-- Start Model Mapped Modal -->
                        <div class="modal modalTH fade" id="courierModel" role="dialog">
                            <form class="form-horizontal" role="form" id="frm1" name="frm1" method="post">
                                <div class="modal-dialog modal-dialogTH modal-lg">

                                    <!-- Modal content-->
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                                            <h2 class="modal-title" align="center"><i class='fa <?= $fa_icon ?>'></i> Bin Change</h2>
                                                 <h4 align="center"><span id="error_msg" class="red_small" style="text-align:center"></span></h4>
                                        </div>
                                        <div class="modal-body modal-bodyTH">
                                            <!-- here dynamic task details will show -->
                                        </div>
                                        <div class="modal-footer">
                                        	<button class='btn<?= $btncolor ?>' id="save" type="submit" name="saveButton" value="Save" onClick="checkAllRows();"><i class="fa fa-save fa-lg"></i>&nbsp;&nbsp;Save</button>&nbsp;
                                            
                                            <button type="button" id="btnCancel" class="btn<?= $btncolor ?>" data-dismiss="modal"><i class="fa fa-window-close fa-lg"></i> Close</button>
                                        </div>

                                    </div>
                                </div>
                            </form>
                        </div><!--close Model Mapped modal-->
                    </div>
                </div>
            </div>
        </div>
        <div id="loader"></div>
        <?php
        include("../includes/footer.php");
        include("../includes/connection_close.php");
        ?>
    </body>
</html>