<?php
define('DOCUMENT_ROOT_CLASS','../../');
define('DOCUMENT_ROOT_INC_FOLDER','inc/');
$filepath = realpath(dirname(__FILE__));
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_2"){
    require "../../inc/ajax_header.php";
    $product_id = $_POST["product_id"];
    $getData = $commonFunctions->getRowData('invty_pdt_details'," WHERE id = '".$product_id."'");
    $stock_count = !empty($getData['stock_count'])?$getData['stock_count']:0;
    $barcode_value = !empty($getData['barcode_value'])?$getData['barcode_value']:"-";
    $price = !empty($getData['price'])?$getData['price']:0;
    echo json_encode(array("stock_count"=>$stock_count,"barcode_value"=>$barcode_value,"price"=>$price));
    exit();
}
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call"){
    require "../../inc/ajax_header.php";
    $product_id = $_POST["product_id"];
    $warehouse_id = $_POST["warehouse_id"];
    $getData = $commonFunctions->getRowData('invty_pdt_stock_mgt'," WHERE product_id = '".$product_id."' and warehouse_id = '".$warehouse_id."' ");
    $stock_count = !empty($getData['stock_count'])?$getData['stock_count']:0;
    $inventory_id = !empty($getData['stock_id'])?$getData['stock_id']:0;
    echo json_encode(array("stock_count"=>$stock_count,"inventory_id"=>$inventory_id));
    exit();
} 
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_1"){
    require "../../inc/ajax_header.php";
    $stock_mov_id = $_POST['stock_mov_id'];
    $stock_mvt_status = $_POST['stock_mvt_status'];
    if($stock_mvt_status == 3){
        $commonFunctions->updateData('invty_pdt_stock_mgt_mov'," WHERE stock_mov_id = '".$stock_mov_id."' " , " stock_mvt_status = '".$stock_mvt_status."' ","");
        $commonFunctions->updateData('invty_pdt_stock_mgt_logs'," WHERE stock_mov_id = '".$stock_mov_id."' " , " stock_mvt_status = '".$stock_mvt_status."' ","");

        Session::set('msg', '<div class="alert alert-success alert-dismissible mt-3" id="flash-msg">
          <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
          <strong>Success !</strong> Wow, Your Stock Movement Status updated Successfully !</div>');
        exit();
    }else{
        $do_not_upd = 0;
        $stockArr = $commonFunctions->getRowData('invty_pdt_stock_mgt_mov'," WHERE stock_mov_id = '".$stock_mov_id."' ");
        if(!empty($stockArr)){
            $currentStockArr = $commonFunctions->getRowData('invty_pdt_stock_mgt'," WHERE product_id = '".$stockArr['product_id']."' AND warehouse_id = '".$stockArr['move_warehouse_id']."' ");
            if(!empty($currentStockArr['stock_id'])){
                // minus stock from move stock
                $last_stock_count = $commonFunctions->getname($stockArr['stock_id'],"invty_pdt_stock_mgt","stock_count","stock_id");
                $upd_stock_count = $last_stock_count - $stockArr['move_stock_count'];
                
                if($upd_stock_count >= 0){
                    $commonFunctions->updateData('invty_pdt_stock_mgt'," WHERE stock_id = '".$stockArr['stock_id']."' " , " stock_mvt_status = '".$stock_mvt_status."',stock_count = '".$upd_stock_count."' ","");

                    //update move stock
                    $stock_count1 = $currentStockArr['stock_count'] + $stockArr['move_stock_count'];
                    $commonFunctions->updateData('invty_pdt_stock_mgt'," WHERE stock_id = '".$currentStockArr['stock_id']."' " , " stock_mvt_status = '".$stock_mvt_status."',stock_count = '".$stock_count1."' ","");
                }else{
                    $do_not_upd = 1;
                }
            }else{
                $last_stock_count = $commonFunctions->getname($stockArr['stock_id'],"invty_pdt_stock_mgt","stock_count","stock_id");
                $upd_stock_count = $last_stock_count - $stockArr['move_stock_count'];
                if($upd_stock_count >= 0){
                    $commonFunctions->updateData('invty_pdt_stock_mgt'," WHERE stock_id = '".$stockArr['stock_id']."' " , " stock_mvt_status = '".$stock_mvt_status."',stock_count = '".$upd_stock_count."' ","");
                    
                    $added_by = $_SESSION['id'];
                    $commonFunctions->addData('invty_pdt_stock_mgt'," (product_id,warehouse_id,stock_count,added_by,stock_mvt_status ) VALUES ('".$stockArr['product_id']."','".$stockArr['move_warehouse_id']."','".$stockArr['move_stock_count']."','".$added_by."','".$stock_mvt_status."' ) ",'');
                }else{
                    $do_not_upd = 1;
                }
            }
            if($do_not_upd == 0){
                $commonFunctions->updateData('invty_pdt_stock_mgt_mov'," WHERE stock_mov_id = '".$stock_mov_id."' " , " stock_mvt_status = '".$stock_mvt_status."' ","");
                $commonFunctions->updateData('invty_pdt_stock_mgt_logs'," WHERE stock_mov_id = '".$stock_mov_id."' " , " stock_mvt_status = '".$stock_mvt_status."' ","");

                Session::set('msg', '<div class="alert alert-success alert-dismissible mt-3" id="flash-msg">
                  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                  <strong>Success !</strong> Wow, Your Stock Movement Status updated Successfully !</div>');
                exit();
            }else{
                Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg">
                  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                  <strong>Error !</strong> Sorry something went wrong from server side !</div>');
                exit();
            }
        }
    }
}
require "../../inc/header.php";
$msg = Session::get('msg');
Session::set("msg", NULL);
if(!empty($_POST) and @$_POST["action"] != "ajax_call_1" and @$_POST["action"] != "ajax_call"){
    $added_by = $_SESSION['id'];
    $last_id = $commonFunctions->addData('invty_pdt_stock_mgt_mov'," (stock_id,product_id,current_warehouse_id,current_stock,added_by,move_warehouse_id,move_stock_count,appr_staff_id,accept_staff_id) VALUES ('".$_POST['inventory_id']."','".$_POST['product_id']."','".$_POST['warehouse_id']."','".$_POST['stock_count']."','".$added_by."','".$_POST['move_warehouse_id']."','".$_POST['move_stock_count']."','".$_POST['appr_staff_id']."','".$_POST['accept_staff_id']."') ",'');

    $commonFunctions->addLogData('invty_pdt_stock_mgt_logs'," (product_id,warehouse_id,stock_count,added_by,message,stock_mov_id,move_warehouse_id,move_stock_count,appr_staff_id,accept_staff_id,stock_mvt_type,stock_mvt_status) VALUES ('".$_POST['product_id']."','".$_POST['warehouse_id']."','".$_POST['stock_count']."','".$added_by."','Stock Movement Successfully','".$last_id."','".$_POST['move_warehouse_id']."','".$_POST['move_stock_count']."','".$_POST['appr_staff_id']."','".$_POST['accept_staff_id']."','2','2' ) ");
    if($last_id > 0){
        Session::set('msg', '<div class="alert alert-success alert-dismissible mt-3" id="flash-msg">
          <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
          <strong>Success !</strong> Wow, Your Information added Successfully !</div>');
        echo "<script>window.location.href='stock-movements.php?state=list';</script>";
    }else{
        Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg">
<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
<strong>Error !</strong> Data not inserted !</div>');
        echo "<script>window.location.href='';</script>";
    }
}
?>

    <!-- Page-Title -->
    <div class="row">
        <div class="col-sm-12">
            <div class="page-title-box">
                <div class="row">
                    <div class="col">
                        <h4 class="page-title"><?php echo ($_GET['state'] != "list")?"Stock Movements":"Stock & Inventory List "; ?></h4>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="javascript:void(0);">Products & Services</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);">Inventory</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);"><?php echo ($_GET['state'] != "list")?"Stock Movement / Transfer":"Stock Movement / Transfer"; ?></a></li>
                        </ol>
                    </div><!--end col-->
                    <div class="col-auto align-self-center">
                        
                        <?php if(@$_GET['state'] == "list"){ ?>
                            
                        <?php }else{ ?>
                            <!-- <button type="button" class="btn btn-sm btn-outline-primary save_form">Save</button>
                            <button type="button" class="btn btn-sm btn-outline-danger clear_form">Clear</button> -->
                            <a href="stock-movements.php?state=list"><button type="button" class="btn btn-sm btn-outline-secondary">Back to Stock & Inventory List </button></a>
                        <?php } ?>
                    </div><!--end col-->  
                </div><!--end row-->                                                              
            </div><!--end page-title-box-->
        </div><!--end col-->
    </div><!--end row-->
    <!-- end page title end breadcrumb -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title"> 
                        <div class="form-row">
                            <div class="form-group searchForm col-md-6">    
                                <a class="btn btn-soft-primary" href="stock-movements.php?state=add" role="button" ><i class="fas fa-plus mr-2"></i> Create Stock Movements </a>
                            </div>  
                            <div class="form-group searchForm col-md-6">
                                <?php if(empty($_GET['state']) OR (!empty($_GET['state']) and $_GET['state'] == "list")): ?>
                                <form action="" id="searchForm" method="GET">
                                    <div class="form-row">
                                        <div class="form-group searchForm col-md-8">
                                            <input type="text" name="search" id="search" placeholder="Search" class="form-control" value="<?php echo @$_GET['search']; ?>">
                                            <input type="hidden" name="state" value="<?php echo @$_GET['state']; ?>">
                                            <input type="hidden" name="page" value="<?php echo @$_GET['page']; ?>">
                                        </div>
                                        <div class="form-group searchForm col-md-4">
                                            <button type="submit" id="searchbtn" class="btn btn-primary"> <i class="fa fa-search"></i> Search</button>
                                            <button type="button" id="clearbtn" class="btn btn-danger"> <i class="fa fa-trash"></i> Clear</button>
                                        </div>
                                    </div>
                                </form>
                                <?php endif; ?>
                            </div>
                        </div>
                    </h4>
                    <?php echo !empty($msg)?$msg:''; ?>        
                </div>
       
                <div class="card-body">
                    <div class="row">
                        <?php if(@$_GET['state'] != "list"): ?>
                            <?php 
                            $error_ = 0;
                                if(@$_GET['inventory_id'] != ''){
                                    $editData = $commonFunctions->getRowData('invty_pdt_stock_mgt'," WHERE stock_id = '".$_GET['inventory_id']."' ");
                                }
                            ?>
                            <div class="col-md-12">
                                <!--div class="main-card mb-3 card">
                                    <div class="card-body"-->
                                        <form id="stock_movements_form" action="" method="post" enctype="multipart/form-data">
                                            <input type="hidden" name="inventory_id" id="inventory_id" value="<?php echo ($_GET['state'] == 'edit')?@$_GET['inventory_id']:0;?>">
                                            <div class="step-1">
                                                <div class="form-row">
                                                    <div class="col-md-6 position-relative form-group">
                                                        <label for="label" class="">Label / Product Name <span class="error">*</span></label>
                                                        <?php $prdtData = $commonFunctions->getData('invty_pdt_details',''); ?>
                                                        <select class="form-control select2" name="product_id" id="product_id">
                                                            <option value=""></option>
                                                            <?php foreach ($prdtData as $rw) { ?>
                                                                <option value="<?php echo $rw['id'];?>" <?php echo (@$editData['product_id'] == $rw['id'] OR @$_GET["product_id"] == $rw['id'])?"selected":"";?>><?php echo $rw['label']; ?></option>
                                                            <?php } ?>
                                                        </select>
                                                        <label id="product_id-error" class="error" for="product_id"></label>
                                                    </div>
                                                    <div class="col-md-6 position-relative form-group">
                                                        <!-- <label for="stock_count" class="">Stock Count <span class="error">*</span></label> -->
                                                        <input name="stock_count" id="stock_count" placeholder="Please enter stock count" type="hidden" class="form-control" value="<?php echo @$editData['stock_count'];?>" required="">
                                                    </div>
                                                    <div class="col-md-12">
                                                        <table style="width: 100% !important;" class="table datatable_t table-hover table-striped table-bordered">
                                                            <thead>
                                                                <tr>
                                                                    <th>Product Name#</th>
                                                                    <th><span class="product_name_label"></span></th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <tr>
                                                                    <th>Barcode#</th>
                                                                    <th><span class="barcode_label"></span></th>
                                                                </tr>
                                                                <tr>
                                                                    <th>Selling Price#</th>
                                                                    <th><span class="selling_price_label"></span></th>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div> 
                                                    <div class="col-md-6 position-relative form-group">
                                                        <button type="button" class="mt-1 btn btn-outline-primary btn-step-1">Next >></button>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="step-2" style="display: none;">
                                                <div class="form-row">
                                                    <div class="col-md-12 position-relative form-group">
                                                        <label class="">Product Name - <span class="product_name_label"></span></label>
                                                    </div>
                                                    <div class="col-md-6 position-relative form-group">
                                                        <label for="warehouse_id" class="">Select Current Warehouse <span class="error">*</span></label>
                                                        <?php $warehouseData = $commonFunctions->getData('invty_wrhus',' WHERE status = 0 '); ?>
                                                        <select class="form-control select21" name="warehouse_id" id="warehouse_id" required="">
                                                            <option value=""></option>
                                                            <?php foreach ($warehouseData as $rw) { ?>
                                                                <option value="<?php echo $rw['id'];?>" <?php echo (@$editData['warehouse_id'] == $rw['id'] OR @$_GET['warehouse_id'] == $rw['id'])?"selected":"";?>><?php echo $rw['short_name_location']; ?></option>     
                                                            <?php } ?>
                                                        </select>
                                                        <label id="warehouse_id-error" class="error" for="warehouse_id"></label>
                                                    </div>
                                                    <div class="col-md-6 position-relative form-group">
                                                        <?php $product_name = (!empty($editData))?@strtoupper($commonFunctions->getname(@$editData['product_id'],"invty_pdt_details","label","id")):"-"; ?>
                                                        <?php $stock_count=0; if(!empty($editData)){ $stock_count = @$editData['stock_count']; } ?>

                                                        <label style="margin-top: 35px;font-weight: 600;">= <span class="productStock"><?php echo $stock_count; ?></span> ( Current Stock for "<span class="productName"><?php echo $product_name; ?></span>" )
                                                        </label>
                                                    </div>
                                                    <div class="col-md-6 position-relative form-group">
                                                        <label for="move_warehouse_id" class="">Select Destination Warehouse <span class="error">*</span></label>
                                                        <?php $warehouseData = $commonFunctions->getData('invty_wrhus',' WHERE status = 0 '); ?>
                                                        <select class="form-control select21" name="move_warehouse_id" id="move_warehouse_id" required="">
                                                            <option value="">Select Destination Warehouse</option>
                                                            <?php foreach ($warehouseData as $rw) { ?>
                                                                <option value="<?php echo $rw['id'];?>" ><?php echo $rw['short_name_location']; ?></option>     
                                                            <?php } ?>
                                                        </select>
                                                        <label id="move_warehouse_id-error" class="error" for="move_warehouse_id"></label>
                                                    </div>
                                                    <div class="col-md-6 position-relative form-group">
                                                        <label for="stock_count" class="">&nbsp;</label>
                                                        <input name="move_stock_count" id="move_stock_count" placeholder="Enter the stock count that you want to move" type="number" class="form-control" value="" required="" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" max="<?php echo @$editData['stock_count'];?>" min='1'>
                                                        <label id="move_stock_count-error" class="error" for="move_stock_count"></label>
                                                    </div>
                                                    <div class="col-md-6 position-relative form-group">
                                                        <button type="button" class="mt-1 btn btn-outline-secondary back_to_first">Back <<</button>
                                                        <button type="button" class="mt-1 btn btn-outline-primary btn-step-2">Next >></button>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="step-3" style="display: none;">
                                                <div class="form-row">
                                                    <div class="col-md-12 position-relative form-group">
                                                        <label class="">Product Name - <span class="product_name_label"></span></label>
                                                    </div>
                                                    <div class="col-md-4 position-relative form-group">
                                                        <label class="">Current Warehouse</label>
                                                        <br>
                                                        <label class="form-control" style="font-weight: 600;"><span class="current_warehouse_name_label"></span>
                                                    </div>
                                                    <div class="col-md-2 position-relative form-group" style="padding-top: 18px;text-align: center;">
                                                        <br>
                                                        =
                                                    </div>
                                                    <div class="col-md-4 position-relative form-group" style="padding-top: 18px;">
                                                        <br>
                                                        <span class="productStock">0</span> ( Requested <span class="move_stock_count_label">0</span> to Move )
                                                        </label>
                                                    </div>
                                                    <div class="col-md-2 position-relative form-group" style="padding-top: 18px;">
                                                    </div>

                                                    <div class="col-md-4 position-relative form-group">
                                                        <label class="">Destination Warehouse</label>
                                                        <br>
                                                        <label class="form-control" style="font-weight: 600;"><span class="destination_warehouse_name_label"></span>
                                                    </div>
                                                    <div class="col-md-2 position-relative form-group" style="padding-top: 18px;text-align: center;">
                                                        <br>
                                                        =
                                                    </div>
                                                    <div class="col-md-4 position-relative form-group" style="padding-top: 18px;">
                                                        <br>
                                                        <span class="destinationProductStock">0</span> ( Requesting <span class="move_stock_count_label">0</span> )
                                                        </label>
                                                    </div>
                                                    <div class="col-md-2 position-relative form-group" style="padding-top: 18px;">
                                                    </div>
                                                    <div class="col-md-6 position-relative form-group">
                                                        <label for="warehouse_id" class="">Select the Staff for Approval <span class="error">*</span></label>
                                                        <?php $staffData = $commonFunctions->getData('sys_erp_adm_user',' WHERE erp_sys_user_isActive = 0 '); ?>
                                                        <select class="form-control select21" name="appr_staff_id" id="appr_staff_id" required="">
                                                            <option value="">Select</option>
                                                            <?php foreach ($staffData as $rw) { 
                                                                $role = $commonFunctions->getname($rw['erp_sys_user_roleid'],"sys_erp_adm_user_roles","role","id");
                                                             ?>
                                                                <option value="<?php echo $rw['id'];?>" ><?php echo $rw['erp_sys_user_name_first']." ".$rw['erp_sys_user_name_last']."(".$role.")"; ?></option>     
                                                            <?php } ?>
                                                        </select>
                                                        <label id="appr_staff_id-error" class="error" for="appr_staff_id"></label>
                                                    </div>
                                                    <div class="col-md-6 position-relative form-group">
                                                        <label for="warehouse_id" class="">Select the Staff who will Accept/Complete the Transafer at Destination Warehouse <span class="error">*</span></label>
                                                        <?php $staffData = $commonFunctions->getData('sys_erp_adm_user',' WHERE erp_sys_user_isActive = 0 '); ?>
                                                        <select class="form-control select21" name="accept_staff_id" id="accept_staff_id" required="">
                                                            <option value="">Select</option>
                                                            <?php foreach ($staffData as $rw) { 
                                                                $role = $commonFunctions->getname($rw['erp_sys_user_roleid'],"sys_erp_adm_user_roles","role","id");
                                                             ?>
                                                                <option value="<?php echo $rw['id'];?>" ><?php echo $rw['erp_sys_user_name_first']." ".$rw['erp_sys_user_name_last']."(".$role.")"; ?></option>     
                                                            <?php } ?>
                                                        </select>
                                                        <label id="accept_staff_id-error" class="error" for="accept_staff_id"></label>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <button type="button" class="mt-1 btn btn-outline-secondary back_to_sec">Back <<</button>

                                                        <button type="submit" class="mt-1 btn btn-outline-primary">Submit</button>
                                                    </div>
                                                </div>                      
                                            </div>
                                        </form>
                                    <!--/div>
                                </div-->
                            </div>
                        <?php else: ?>
                            <div class="col-md-12">
                                <!--div class="main-card mb-3 card">
                                    <div class="card-body"-->
                                        <style type="text/css">
                                            tr {cursor: pointer;}
                                        </style>
                                        <?php 
                                        $targetpage = "stock-movements.php?state=list";
                                        $limit1 = 50;
                                        $limit = 50;
                                        $total_pages = $commonFunctions->getData('invty_pdt_stock_mgt_mov','');
                                        $total_pages = count($total_pages);
                                        $stages = 1;
                                        $page = @$_GET['page'];
                                        if($page){
                                            $start = ($page - 1) * $limit; 
                                        }else{
                                            $start = 0; 
                                        } 
                                        $search_con = "";
                                        if(!empty($_GET['search'])){
                                            $search_con = " AND current_stock LIKE '%".$_GET['search']."%' OR move_warehouse_id LIKE '%".$_GET['search']."%' ";
                                            $productArr = $commonFunctions->getIDs('invty_pdt_details','id'," WHERE label LIKE '%".$_GET['search']."%' OR reference_number LIKE '%".$_GET['search']."%' OR barcode_value LIKE '%".$_GET['search']."%' ");
                                            $prd_ids = $productArr['ids'];
                                            if(!empty($prd_ids)){ $search_con .= "  OR product_id IN(".$prd_ids.") "; }
                                            
                                            $warehArr = $commonFunctions->getIDs('invty_wrhus','id'," WHERE short_name_location LIKE '%".$_GET['search']."%' ");
                                            $whr_ids = $warehArr['ids'];
                                            if(!empty($whr_ids)){ $search_con .= "  OR current_warehouse_id IN(".$whr_ids.") "; }

                                            $moveWarehArr = $commonFunctions->getIDs('invty_wrhus','id'," WHERE short_name_location LIKE '%".$_GET['search']."%' ");
                                            $whr_ids1 = $moveWarehArr['ids'];
                                            if(!empty($whr_ids1)){ $search_con .= "  OR move_warehouse_id IN(".$whr_ids1.") "; }

                                        }
                                        $where = " WHERE stock_mov_id ".$search_con." ORDER BY stock_mov_id DESC LIMIT $start, $limit ";
                                        // Initial page num setup
                                        if ($page == 0){ $page = 1; }
                                        $prev = $page - 1;  
                                        $next = $page + 1;  
                                        $lastpage = ceil($total_pages/$limit);  
                                        $LastPagem1 = $lastpage - 1;    
                                        $paginate = '';
                                        if($lastpage > 1)
                                        {       
                                            $paginate .= "<div class='paginate'>";
                                            // Previous

                                            if ($page > 1){
                                                $paginate.= "<a href='$targetpage&page=$prev'>Previous</a>";
                                            }else{
                                                $paginate.= "<span class='disabled'>Previous</span>";   }
                                            // Pages    
                                            if ($lastpage < 2 + ($stages * 2))  // Not enough pages to breaking it up
                                            {   
                                                for ($counter = 1; $counter <= $lastpage; $counter++)
                                                {
                                                    if ($counter == $page){
                                                        $paginate.= "<span class='current'>$counter</span>";
                                                    }else{
                                                        $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                                }
                                            }
                                            elseif($lastpage > 2 + ($stages * 2))   // Enough pages to hide a few?
                                            {
                                                // Beginning only hide later pages
                                                if($page < 1 + ($stages * 2))   
                                                {
                                                    for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
                                                    {
                                                        if ($counter == $page){
                                                            $paginate.= "<span class='current'>$counter</span>";
                                                        }else{
                                                            $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                                    }
                                                    $paginate.= "...";
                                                    $paginate.= "<a href='$targetpage&page=$LastPagem1'>$LastPagem1</a>";
                                                    $paginate.= "<a href='$targetpage&page=$lastpage'>$lastpage</a>";
                                                }
                                                // Middle hide some front and some back
                                                elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2))
                                                {
                                                    $paginate.= "<a href='$targetpage&page=1'>1</a>";
                                                    $paginate.= "<a href='$targetpage&page=2'>2</a>";
                                                    $paginate.= "...";
                                                    for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
                                                    {
                                                        if ($counter == $page){
                                                            $paginate.= "<span class='current'>$counter</span>";
                                                        }else{
                                                            $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                                    }
                                                    $paginate.= "...";
                                                    $paginate.= "<a href='$targetpage&page=$LastPagem1'>$LastPagem1</a>";
                                                    $paginate.= "<a href='$targetpage&page=$lastpage'>$lastpage</a>";
                                                }
                                                // End only hide early pages
                                                else
                                                {
                                                    $paginate.= "<a href='$targetpage&page=1'>1</a>";
                                                    $paginate.= "<a href='$targetpage&page=2'>2</a>";
                                                    $paginate.= "...";
                                                    for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
                                                    {
                                                        if ($counter == $page){
                                                            $paginate.= "<span class='current'>$counter</span>";
                                                        }else{
                                                            $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}
                                                    }
                                                }       
                                            }       
                                                    // Next
                                            if ($page < $counter - 1){ 
                                                $paginate.= "<a href='$targetpage&page=$next'>Next</a>";
                                            }else{
                                                $paginate.= "<span class='disabled'>Next</span>";
                                                }
                                            $paginate.= "</div>";   
                                        }
                                        $invtData = $commonFunctions->getData('invty_pdt_stock_mgt_mov',$where);

                                        $startP = $limit + $start;
                                        if($startP > @count($invtData) ){
                                            $startP = @count($invtData) + $start;
                                        }
                                        /*$invtData1 = $commonFunctions->getData('invty_pdt_stock_mgt_mov','');
                                        echo "<span style='padding: 2px 5px 2px 5px;margin: 2px;border: 1px solid #999;text-decoration: none;color: #666;font-size: 15px;'>Listing ".$start." - ".$startP."</span>";
                                        echo "<span style='padding: 2px 5px 2px 5px;margin: 2px;border: 1px solid #999;text-decoration: none;color: #666;font-size: 15px;'>Total Listed Records ".@count($invtData1)."</span>";*/
                                        echo "<div style='float: right;'>".$paginate."</div>";?>
                                        <table style="margin-top: 10px;width: 100% !important;" class="table datatable_t table-hover table-striped table-bordered">
                                            <thead>
                                                <tr>
                                                    <th class="text-center">Product Name</th>
                                                    <th class="text-center">Product Ref#</th>
                                                    <th class="text-center">Barcode Value</th>
                                                    <th class="text-center">Current Warehouse</th>
                                                    <th class="text-center">Current Stock</th>
                                                    <th class="text-center">Destination Warehouse</th>
                                                    <th class="text-center">Move Stock</th>
                                                    <th class="text-center">Stock Movements Status</th>
                                                    <th class="text-center" style="width: 11%;">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                foreach ($invtData as $row) { 
                                                    $stock_id = $row["stock_id"];
                                                ?>
                                                    <tr>
                                                        <th class="text-center">
                                                            <?php echo $commonFunctions->getname($row['product_id'],"invty_pdt_details","label","id"); ?>
                                                        </th>
                                                        <th>
                                                            <?php
                                                            echo $commonFunctions->getname($row['product_id'],"invty_pdt_details","reference_number","id"); ?>
                                                        </th>
                                                        <th>
                                                            <?php
                                                            echo $commonFunctions->getname($row['product_id'],"invty_pdt_details","barcode_value","id"); ?>
                                                        </th>
                                                        <th class="text-center">
                                                            <?php echo $commonFunctions->getname($row['current_warehouse_id'],"invty_wrhus","short_name_location","id");
                                                            ?>
                                                        </th>
                                                        <th class="text-center">
                                                            <?php echo $row['current_stock']; ?>
                                                        </th>
                                                        <th class="text-center">
                                                            <?php echo $commonFunctions->getname($row['move_warehouse_id'],"invty_wrhus","short_name_location","id");
                                                            ?>
                                                        </th>
                                                        <th class="text-center">
                                                            <?php echo $row['move_stock_count']; ?>
                                                        </th>
                                                        <th class="text-center">
                                                            <?php 
                                                            if($row['stock_mvt_status'] == 1){
                                                                echo "Drafted";
                                                            }
                                                            if($row['stock_mvt_status'] == 2){
                                                                echo "Inprogress";
                                                            }
                                                            if($row['stock_mvt_status'] == 3){
                                                                echo "Approved";
                                                            }
                                                            if($row['stock_mvt_status'] == 4){
                                                                echo "Completed";
                                                            }
                                                            ?>
                                                        </th>
                                                        <th>
                                                            <?php 
                                                                if($row['stock_mvt_status'] < 3 and $row['appr_staff_id'] == $_SESSION['id']){
                                                                    echo "<button type='button' class='btn btn-outline-primary' onclick='change_stock_status(".$row['stock_mov_id'].",3)' style='padding-left: 5px !important;padding-right: 5px !important;'>Start Transfer";
                                                                }
                                                            ?>
                                                            <?php 
                                                                if($row['stock_mvt_status'] == 3 and $row['accept_staff_id'] == $_SESSION['id']){
                                                                    echo "<button type='button' class='btn btn-outline-success' onclick='change_stock_status(".$row['stock_mov_id'].",4)'>Accept";
                                                                }
                                                            ?>
                                                        </th>
                                                    </tr>
                                                <?php } ?>
                                            </tbody>
                                        </table>
                                    <!--/div>
                                </div-->
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div> <!-- end col -->
    </div> <!-- end row -->

<?php require "../../inc/footer.php"; ?>
<script type="text/javascript">
    $("#expand").click(function(){
        var accordioninput = $("#accordioninput").val();
        if(accordioninput == 0){
            //$(".accordion-class").html("<i class='dripicons-arrow-thin-down'></i>");
            $("#accordioninput").val(1);
        }else{
            //$(".accordion-class").html("<i class='dripicons-arrow-thin-right'></i>");
            $("#accordioninput").val(0);
        }
    })
    function redirect_(uri){
        window.location.href = uri;
    }
    $("#clearbtn").click(function(){
        $("#search").val('');
        $("#searchForm").submit();
    });
    /*$("#searchbtn").click(function(){
        currLoc = $(location).attr('href');
        window.location.href = currLoc+"&search="+$("#search").val();
    });
    $("#clearbtn").click(function(){
        currLoc = $(location).attr('href');
        window.location.href = currLoc;
    });*/
    $(document).ready(function() {       
        $('#product_image').bind('change', function() {
            var a=(this.files[0].size);
            if(a > 524288) {
                $("#product_image").val('');
                Swal.fire(
                    'Warning',
                    'Please make sure file size should not be more than 512kb!',
                    'error'
                )
                //alert('Please make sure file size should not be more than 512kb!');
            };
            var ext=(this.files[0].type);
            if($.inArray(ext, ['image/png','image/jpg','image/jpeg']) == -1) {
                Swal.fire(
                    'Warning',
                    'Only .png, .jpg and .jpeg format is allowed.',
                    'error'
                )
            }
        });
    });
    $(".save_form").click(function(){
        var label = $("#label").val();
        var reference_number = $("#reference_number").val();
        if(label != '' && reference_number != ''){
            $("#stock_movements_form").submit();
        }else{
            Swal.fire(
                'Error',
                'Please fill all required fields!',
                'error'
            )
        }
    });
    $(".clear_form").click(function(){
        $("#stock_movements_form").trigger("reset");
    });
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script type="text/javascript">
    $("#stock_movements_form").validate();
    $("#product_id,#warehouse_id").change(function(){
        var product_id = $("#product_id option:selected").val();
        var product_id1 = $("#product_id option:selected").text();

        $(".product_name_label").html(product_id1);
        var warehouse_id = $("#warehouse_id option:selected").val();
        if(product_id != ''){
            $("#product_id-error").html("");
            $("#warehouse_id-error").html("");
            //window.location.href = "";
            $.ajax({
                type: 'POST',
                url: "",
                data: {"product_id":product_id,"warehouse_id":warehouse_id,"action":"ajax_call"},
                success: function(response) { 
                    obj = JSON.parse(response);
                    $(".productName").html($("#product_id option:selected").text());
                    $(".productStock").html(obj.stock_count);
                    $("#move_stock_count").attr("max",obj.stock_count);
                    $("#inventory_id").val(obj.inventory_id);

                    $.ajax({
                        type: 'POST',
                        url: "",
                        data: {"product_id":product_id,"action":"ajax_call_2"},
                        success: function(response1) { 
                            obj1 = JSON.parse(response1);
                            $(".barcode_label").text(obj1.barcode_value);
                            $(".selling_price_label").text(obj1.price);
                        }
                    });
                }
            });
        }
    });
    function change_stock_status(stock_mov_id,stock_mvt_status){
        $.ajax({
            type: 'POST',
            url: "",
            data: {"stock_mov_id":stock_mov_id,"stock_mvt_status":stock_mvt_status,"action":"ajax_call_1"},
            success: function(response) { 
                window.location.href='';
            }
        });
    }
    $(".back_to_sec").click(function(){
        $(".step-2").css("display","block");
        $(".step-3").css("display","none");
    });
    $(".back_to_first").click(function(){
        $(".step-1").css("display","block");
        $(".step-2").css("display","none");
    });
    $(".btn-step-1").click(function(){
        var product_id = $("#product_id option:selected").val();
        if(product_id != ''){
            $(".step-1").css("display","none");
            $(".step-2").css("display","block");
            $("#product_id-error").html("");
        }else{
            $("#product_id-error").html("Please select product.");
        }
    });
    $(".btn-step-2").click(function(){
        var warehouse_id = $("#warehouse_id option:selected").val();
        var move_warehouse_id = $("#move_warehouse_id option:selected").val();
        var move_stock_count = $("#move_stock_count").val();
        if(warehouse_id != "" && move_warehouse_id != "" && move_stock_count != ""){
            $("#warehouse_id-error").html("");
            $("#move_warehouse_id-error").html("");
            $("#move_stock_count-error").html("");
            $(".step-2").css("display","none");
            $(".step-3").css("display","block");
        }else{
            if(warehouse_id == ""){
                $("#warehouse_id-error").html("Please select warehouse.");
            }
            if(move_warehouse_id == ""){
                $("#move_warehouse_id-error").html("Please select move warehouse.");
            }
            if(move_stock_count == ""){
                $("#move_stock_count-error").html("Please move stock.");
            }
        }
    });
    $("#warehouse_id").change(function(){
        $("#warehouse_id-error").html("");
        var warehouse_text = $("#warehouse_id option:selected").text();
        $(".current_warehouse_name_label").html(warehouse_text);
    });
    $("#move_warehouse_id").change(function(){
        $("#move_warehouse_id-error").html("");
        var warehouse_text = $("#move_warehouse_id option:selected").text();
        $(".destination_warehouse_name_label").html(warehouse_text);
    });
    $("#move_stock_count").keyup(function(){
        $("#move_stock_count-error").html("");
        var productStock = $(".productStock").html();
        var move_stock_count = $("#move_stock_count").val();
        $(".destinationProductStock").text(parseInt(productStock) - parseInt(move_stock_count));
        $(".move_stock_count_label").text(move_stock_count);
    });
</script>
<?php if(!empty($_GET["product_id"])){ ?>
<script type="text/javascript">
    $("#warehouse_id").change();
    $(".btn-step-1").click();
    $("#warehouse_id").change();
</script>
<?php } ?>