<?php 
define('DOCUMENT_ROOT_CLASS','../../');
define('DOCUMENT_ROOT_INC_FOLDER','inc/');
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call"){
    require "../../inc/ajax_header.php";
    $product_id = $_POST["product_id"];
    $table = 'invty_pdt_stock_mgt';
    if(!empty($_GET['inventory_id'])){
        $table = 'invty_pdt_stock_mgt_repl';
    }
    $getData = $commonFunctions->getData($table," WHERE product_id = '".$product_id."'");
    $arr["data"] = array();
    foreach ($getData as $rw) {
        $arr["data"][] = array("warehouse_id"=>$rw["warehouse_id"],"stock_count"=>$rw["stock_count"]);
    }
    echo json_encode($arr);
    exit();
}
$filepath = realpath(dirname(__FILE__));
require "../../inc/header.php";
$msg = Session::get('msg');
Session::set("msg", NULL);
if(!empty($_POST)){
    if(empty($_POST['product_id'])){
        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> Please select product!</div>');
        echo "<script>window.location.href='';</script>";
    }else{
        $affected_rows = 0;
        if($_POST['action'] == "add"){
            $added_by = $_SESSION['id'];
            for ($i=0; $i < @count($_POST['warehouse_id']); $i++) { 
                $last_id = $commonFunctions->addData('invty_pdt_stock_mgt_repl'," (product_id,warehouse_id,stock_count,added_by,stock_mvt_type) VALUES ('".$_POST['product_id']."','".$_POST['warehouse_id'][$i]."','".$_POST['stock_count'][$i]."','".$added_by."','2') ",'');

                $commonFunctions->addLogData('invty_pdt_stock_mgt_repl_logs'," (product_id,warehouse_id,stock_count,added_by,message,stock_id,stock_mvt_type) VALUES ('".$_POST['product_id']."','".$_POST['warehouse_id'][$i]."','".$_POST['stock_count'][$i]."','".$added_by."','New Stock Added','".$last_id."','2') ");
                if(!empty($last_id)){ $affected_rows++;}
            }
            if($affected_rows > 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-replenishment.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>";
            }
        }
        if($_POST['action'] == "edit"){
            $affected_rows = 0;
            $updated_by = $_SESSION['id'];
            for ($i=0; $i < @count($_POST['warehouse_id']); $i++) { 
                $last_id = $_POST['inventory_id'];
                $commonFunctions->updateData('invty_pdt_stock_mgt_repl'," WHERE stock_id = '".$_POST['inventory_id']."' ", " product_id='".$_POST['product_id']."',warehouse_id='".$_POST['warehouse_id'][$i]."',stock_count='".$_POST['stock_count'][$i]."',updated_by='".$updated_by."',stock_mvt_type = '2' ",'');

                $commonFunctions->addLogData('invty_pdt_stock_mgt_repl_logs'," (product_id,warehouse_id,stock_count,added_by,message,stock_id,stock_mvt_type) VALUES ('".$_POST['product_id']."','".$_POST['warehouse_id'][$i]."','".$_POST['stock_count'][$i]."','".$updated_by."','Stock Updated','".$last_id."','2') ");
                if(!empty($last_id)){ $affected_rows++;}
            }
            if($affected_rows > 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 updated Successfully !</div>');
                echo "<script>window.location.href='stock-replenishment.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 updated !</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")?"Add Stock Replenishment":"Stock Replenishment 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")?"Add Stock Replenishment":"Stock Replenishment List "; ?></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-replenishment.php?state=list"><button type="button" class="btn btn-sm btn-outline-secondary"> Back to Stock Replenishment 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-replenishment.php?state=add" role="button" ><i class="fas fa-plus mr-2"></i> Create Stock Replenishment </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_repl'," 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_inventory_form" action="" method="post" enctype="multipart/form-data">
                                            <input type="hidden" name="action" value="<?php echo ($_GET['state'] == 'edit')?'edit':'add';?>">
                                            
                                            <input type="hidden" name="inventory_id" value="<?php echo ($_GET['state'] == 'edit')?@$_GET['inventory_id']:0;?>">

                                            <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="0">Select</option>
                                                        <?php foreach ($prdtData as $rw) { ?>
                                                            <option value="<?php echo $rw['id'];?>" <?php echo (@$editData['product_id'] == $rw['id'])?"selected":"";?> ><?php echo $rw['label']; ?></option>     
                                                        <?php } ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    
                                                </div>
                                                <div class="after-add-more col-md-12">
                                                    <?php $warehouseData = $commonFunctions->getData('invty_wrhus',' WHERE status = 0 '); 
                                                    foreach ($warehouseData as $r) {
                                                    ?>
                                                    <div class="form-row">
                                                        <div class="col-md-6 position-relative form-group">
                                                            <label for="warehouse_id" class="">Warehouse</label>
                                                            <select class="form-control " name="warehouse_id[]" id="warehouse_id">
                                                                <option value="<?php echo $r['id'];?>" <?php echo (@$editData['warehouse_id'] == $r['id'])?"selected":"";?> ><?php echo $r['short_name_location']; ?></option>     
                                                            </select>
                                                        </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_<?php echo $r['id'];?>" placeholder="Please enter stock count" type="text" class="form-control stock_count_class" value="0" required="">
                                                        </div>  
                                                        <!-- <div class="col-md-2 position-relative form-group change">
                                                            <br>
                                                            <?php if(empty($_GET['inventory_id'])): ?>
                                                                <a class="btn btn-success add-more">+ Add More</a>
                                                            <?php endif; ?>
                                                        </div> -->     
                                                    </div> 
                                                    <?php } ?>      
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <button type="submit" class="mt-1 btn btn-primary">Submit</button>
                                                </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-replenishment.php?state=list";
                                        $limit1 = 50;
                                        $limit = 50;
                                        $total_pages = $commonFunctions->getData('invty_pdt_stock_mgt_repl','');
                                        $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 stock_count 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 warehouse_id IN(".$whr_ids.") "; }

                                        }
                                        $where = " WHERE stock_id ".$search_con." ORDER BY stock_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_repl',$where);

                                        $startP = $limit + $start;
                                        if($startP > @count($invtData) ){
                                            $startP = @count($invtData) + $start;
                                        }
                                        /*$invtData1 = $commonFunctions->getData('invty_pdt_stock_mgt_repl','');
                                        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">Selling Price</th>
                                                    <th class="text-center">Physical Stock</th>
                                                    <th class="text-center">Total Value</th>
                                                    <th class="text-center">Warehouse</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                foreach ($invtData as $row) { 
                                                    $stock_id = $row["stock_id"];
                                                ?>
                                                    <tr onclick="redirect_('stock-replenishment.php?state=edit&inventory_id=<?php echo $stock_id;?>')" >
                                                        <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>
                                                            <?php
                                                            echo $commonFunctions->getname($row['product_id'],"invty_pdt_details","price","id"); ?>
                                                        </th>
                                                        <th class="text-center"><?php echo $row['stock_count'];?></th>
                                                        
                                                        <th class="text-center"><?php 
                                                            $stock_count = (int)$row['stock_count'];
                                                            $selling_price = (int)$commonFunctions->getname($row['product_id'],"invty_pdt_details","price","id");
                                                            echo $stock_count * $selling_price;
                                                        ?></th>

                                                        <th class="text-center">
                                                            <?php echo $commonFunctions->getname($row['warehouse_id'],"invty_wrhus","short_name_location","id");
                                                            ?>
                                                        </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_inventory_form").submit();
        }else{
            Swal.fire(
                'Error',
                'Please fill all required fields!',
                'error'
            )
        }
    });
    $(".clear_form").click(function(){
        $("#stock_inventory_form").trigger("reset");
    });

    $(document).ready(function() {
        $("body").on("click",".add-more",function(){ 
            var html = '<div class="form-row">\
                <div class="col-md-5 position-relative form-group">\
                    <label for="warehouse_id" class="">Warehouse</label>\
                    <?php $warehouseData = $commonFunctions->getData('invty_wrhus',' WHERE status = 0 '); ?>
                    <select class="form-control " name="warehouse_id[]" id="warehouse_id">\
                        <option value="0">Select</option>\
                        <?php foreach ($warehouseData as $rw) { ?>
                            <option value="<?php echo $rw['id'];?>" <?php echo (@$editData['warehouse_id'] == $rw['id'])?"selected":"";?> ><?php echo $rw['short_name_location']; ?></option>     \
                        <?php } ?>
                    </select>\
                </div>\
                <div class="col-md-5 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="text" class="form-control" value="<?php echo @$editData['stock_count'];?>" required="">\
                </div>  \
                <div class="col-md-2 position-relative form-group change">\
                    <br>\
                    <label for="">&nbsp;</label><a class="btn btn-danger remove">- Remove</a>\
                </div>\
            </div>';
            //$(html).find(".change").html("<label for=''>&nbsp;</label><br/><a class='btn btn-danger remove'>- Remove</a>");
            $(".after-add-more").last().after('<div class="after-add-more col-md-12">'+html+'</div>');
        });
        $("body").on("click",".remove",function(){ 
            $(this).parents(".after-add-more").remove();
        });
    });
$("#product_id").change(function(){
    var product_id = $("#product_id option:selected").val();
    if(product_id != ''){
        //window.location.href = "";
        $.ajax({
            type: 'POST',
            url: "",
            data: {"product_id":product_id,"action":"ajax_call"},
            success: function(response) { 
                obj = JSON.parse(response);
                $(".stock_count_class").val(0);
                for (var i = 0; i < obj.data.length; i++) {
                    $("#stock_count_"+obj.data[i]['warehouse_id']).val(obj.data[i]['stock_count']);
                }
            }
        });
    }
});
$(document).ready(function(){
    if("<?php echo @$_GET['inventory_id'];?>" != ''){
        var product_id = $("#product_id option:selected").val();
        if(product_id != ''){
            //window.location.href = "";
            $.ajax({
                type: 'POST',
                url: "",
                data: {"product_id":product_id,"action":"ajax_call"},
                success: function(response) { 
                    obj = JSON.parse(response);
                    $(".stock_count_class").val(0);
                    for (var i = 0; i < obj.data.length; i++) {
                        $("#stock_count_"+obj.data[i]['warehouse_id']).val(obj.data[i]['stock_count']);
                    }
                }
            });
        } 
    }
});
</script>
