<?php 
ini_set('max_execution_time', 300);
	$header_file=APPPATH.'views/include/header.php';
	require($header_file);
	$sidenav_file=APPPATH.'views/include/sidenav.php';
	require($sidenav_file);	
?>
<style>
/*table>tbody>tr>:nth-last-child(4) {
  color: lime!important;
}
table>thead>tr>:nth-last-child(4) {
  color: lime!important;
}*/
</style>
    <!-- BEGIN: Content-->
    <div class="app-content content">
      <div class="content-overlay"></div>
      <div class="content-wrapper">
        <div class="content-header row">
          <div class="content-header-left col-md-12 col-12 mb-2 breadcrumb-new">
            <h3 class="content-header-title mb-0 d-inline-block">Average Purchase Cost Price</h3>
            <div class="row breadcrumbs-top d-inline-block">
              <div class="breadcrumb-wrapper col-12">
                <ol class="breadcrumb">
                  <li class="breadcrumb-item"><a href="#">Home</a>
                  </li>
                  <li class="breadcrumb-item"><a href="#">Report</a>
                  </li>
                  <li class="breadcrumb-item active">Average Purchase Cost Price
                  </li>
                </ol>
              </div>
            </div>
          </div>
          
        </div>
        <div class="content-body"><!-- Basic form layout section start -->
<section id="basic-form-layouts">
	<div class="row justify-content-md-center " ng-app="reportApp">
		<div class="col-md-12" ng-controller="reportCtrl">
			<div class="card">
				
				<div class="card-content collapse show">
					<div class="card-body">
					<form autocomplete="off" method="POST" action="<?php echo site_url('ExcelReport/searchCostVolume/');?>" >
					<div class="row">
								<div class="col-md-3">
									<div class="form-group">
										<!--<input class="form-control pickadate datepicker picker__input picker__input--active" type="text" name="fmonth"  id="fmonth" required data-uk-datepicker="{format:'DD-MM-YYYY'}" placeholder="From Date">-->
									<input type="text" name="fmonth" id="fmonth" class="form-control date-picker">
									</div>
								</div>
								<div class="col-md-3">
									<div class="form-group">
										<!--<input class="form-control pickadate datepicker picker__input picker__input--active" type="text" name="tmonth"  id="tmonth" required data-uk-datepicker="{format:'DD-MM-YYYY'}" placeholder="To Date">-->
										<input type="text" name="tmonth" id="tmonth" class="form-control date-picker">
									</div>
								</div>
								<div class="col-md-2">
									<div class="form-group">
										<select id="branch" name="branch" class="form-control select2" >
											<option value="">Branch</option>
											<?php  foreach($branch as $row)
												{
											?>
												<option value="<?php echo $row->branch_name; ?>"><?php echo $row->branch_name; ?></option>
											<?php
												} 
											?>
										</select>
									</div>
								</div>
							
								<div class="col-md-1">
									<div class="form-group">
										<input type="submit" name="submit" class="btn btn-primary " value="Search" >
									</div>
								</div>
							</div>
						</form>
								<!--<div ng-if="acrcount==0">
										<h6>No Records</h6>
								</div>
								<div ng-if="acrcount!=0" id="tresponse" class="table-responsive">
								
    								<table id="user_table" class="table table-striped table-bordered nowrap dtable" >
    									<thead>
    									
    										<tr >
    											<th ng-repeat="key in getKeys(acr[0])">{{key}}</th>
    									</thead>
    									<tbody>
    										<tr ng-repeat="row in acr">
    											<td ng-repeat="col in getKeys(acr[0])">{{row[col] | myNumber : 2}}</td>
    										</tr>
    									</tbody>
    								</table>
    							</div>-->
    							
    					<!--		 <div class="table-responsive">
                                        	<?php
		/*		if(isset($_POST['submit'])) {
					 
				//	if (isset($result_display)) {
						//echo "<p><u>Result</u></p>";
					//	if ($result_display == 'No record found !') {
						//	echo $result_display;
						//	} else {
						?>
						
						<table border='1' class='uk-table'>
                                            <thead>
                                                <tr>
                                                    <th >Category Name</th>
                                                    <th >Item Name</th>
                                                    <th >UOM</th>
                                                    <?php
                                                     // echo "dgf";
				$start = $month = strtotime($_POST['fmonth']);
$end = strtotime($_POST['tmonth']);
while($month <= $end)
{
     ?><th ><?php $ymonth=date('F Y', $month); echo date('M Y', $month), PHP_EOL;
     $month = strtotime("+1 month", $month); ?></th><?php
}          
                                                    ?>
                                                    
                                                </tr>
                                                
                                            </thead>
                                     
                                            
                                          
                                        </table>
                                        
						
						<?php //}
				//	}
				}else{ ?>
				
			
                                       
                                        <?php } */ ?>
                                        
				
                                    </div>-->
                               <!--  <?php   //if(isset($_POST['submit'])) { ?>
                                    <input type="hidden" name="fmonth1" id="fmonth1" class="form-control" value="<?php //echo $_POST['fmonth']; ?>">
                                    <input type="hidden" name="tmonth1" id="tmonth1" class="form-control" value="<?php //echo $_POST['tmonth']; ?>">
                                    <?php //} ?>-->
                                    <div id="raw_material"> </div>
							</div>
					</div>
				</div>
			</div>
		</div>
	</div>

</section>
<!-- // Basic form layout section end -->
        </div>
      </div>
    </div>
    <?php //require('include/theme_customizer.php');?>

   <?php 
  $footer_file=APPPATH.'views/include/footer.php';
	require($footer_file);
	?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>
<script type="text/javascript">
<?php if(isset($_POST['submit'])) {
			
			$start = $month = strtotime($_POST['fmonth']);
			$end = strtotime($_POST['tmonth']);
}        
	?>   
	$(function() {
		var item = [];
		var items = "", item_name = "";
		var fproduct = "";
		var count = 1;
	/*	var fmonth = $('#fmonth1').val();
		var tmonth = $('#tmonth1').val();
	//	var dt = new Date(fmonth);
         dt.setMonth( dt.getMonth() + 1 );
        //var months = (tmonth.getFullYear() - fmonth.getFullYear()) * 12;
       // var x = monthDiff(new Date(fmonth), new Date(tmonth));
       //var x = monthDiff(new Date(2000, 01), new Date(2000, 02));
      // var months = tmonth.getMonth() - fmonth.getMonth() + (12 * (to.getFullYear() - from.getFullYear()));

	//	alert(dt);*/
		$.getJSON('https://gsrgroup.biz/inv_demo_carnival/item_list3.json',function(data) {
			
			
				items += "<table border='1' class='table table-striped table-bordered nowrap dtable'>";
			//	items += "<tr><th>Category Name</th><th>Item Name</th><th>UOM</th><th style='width:100px'>Qty</th><th>Remarks</th></tr>";
			   items += "<tr><th>Category Name</th><th>Item Name</th><th>UOM</th><?php while($month <= $end){ $smonth=date('Y-m-d', $month);   $lmonth=date('Y-m-t', $month); ?><th><?php  echo date('F Y', $month);$month = strtotime("+1 month", $month); ?></th><?php } ?></tr>";
				for(i in data.products)
				{
					
					//	$.each(data.products[i].items, function(j,e) {
					items += "<tr>" + "<td>" + data.products[i].category_name + "</td>" + "<td>" +data.products[i].item_name+ "</td>" + "<td>" +data.products[i].uom+ "</td>";
					for(j in data.products[i].items)
					{
						items += "<td>" + data.products[i].items[j].grn_price + "</td>";
					} 
					items += "</tr>";
				//}
				}
				count++;
				items += "</table>"; 
				
			//}
			//alert(items);
			$('#raw_material').append(items);
			//$(items).appendTo("#item_table tbody");
		});
		
		
	});
</script>
<script>
	
	var fetch = angular.module('reportApp',[]);
	fetch.controller('reportCtrl', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
						
		$scope.fetchAvgCostReport = function(){
			
			var fmonth = angular.element(document.getElementById("fmonth"));
			window.localStorage["fmonthval"] = fmonth.val();
			var tmonth = angular.element(document.getElementById("tmonth"));
			window.localStorage["tmonthval"] = tmonth.val();
			var branch = angular.element(document.getElementById("branch"));
			window.localStorage["branchval"] = branch.val();			
			//$scope.acr = [];
						
			window.location.reload(true);
		}
		
		$scope.fmonth1 = window.localStorage["fmonthval"];
		$scope.tmonth1 = window.localStorage["tmonthval"];
		$scope.branch = window.localStorage["branchval"];
		//console.log($scope.fmonth1);
		//console.log($scope.tmonth1);
		var userDate = 'February 2022';
        var date_string = moment($scope.tmonth1, "MMMM YY").format("YYYY-MM");
		console.log(date_string)
		$scope.acrcount = 0;
		$http({
			method: 'POST',
				url: '<?php echo base_url(); ?>index.php/ExcelReport/fetchAvgCostReport',
				headers: {'Content-Type': 'application/json'},
				data: JSON.stringify({fmonth:$scope.fmonth1,tmonth:$scope.tmonth1,branch:$scope.branch})
			}).then(function successCallback(response) {
			
				// Assign response to users object
				$scope.acr = response.data;
				$scope.acrcount = response.data.length;
				if($scope.acrcount == 3569)
				{
				    $scope.acrcount = 0;
				}
				else
				{
				    $scope.acrcount = response.data.length;
				}
				console.log($scope.acrcount);
								
				//datatable
				angular.element(document).ready(function() {  
					dTable = $('#user_table')  
					dTable.DataTable({
						dom: 'Bfrtip',
						"searching": true,
						buttons: [
							'csv', 'excel', 'pdf', 'print'
						]
					}); 
					
				});
				console.log($scope.acr);
				console.log("sdf");
		        //console.log($scope.getKeys);
				$scope.getKeys = function(obj) {
					//return Object.getOwnPropertyNames(obj).sort()
					console.log(Object.keys(obj).length);
					var reA = /[^a-zA-Z]/g;
                    var reN = /[^0-9]/g;
                    function sortAlphaNum(a,b) {
                        var AInt = parseInt(a, 10);
                        var BInt = parseInt(b, 10);
                    
                        if(isNaN(AInt) && isNaN(BInt)){
                            var aA = a.replace(reA, "");
                            var bA = b.replace(reA, "");
                            if(aA === bA) {
                                var aN = parseInt(a.replace(reN, ""), 10);
                                var bN = parseInt(b.replace(reN, ""), 10);
                                return aN === bN ? 0 : aN > bN ? 1 : -1;
                            } else {
                                return aA > bA ? 1 : -1;
                            }
                        }else if(isNaN(AInt)){//A is not an Int
                            return -1;//to make alphanumeric sort first return -1 here
                        }else if(isNaN(BInt)){//B is not an Int
                            return 1;//to make alphanumeric sort first return 1 here
                        }else{
                            return AInt > BInt ? 1 : -1;
                        }
                    }
                    /*var newlist = ["A1", 1, "Category", "2022-jan", "code", "2021-oct", 3, "2021-sep", 2, "A2", "A3", "2021-dec", "B10", "2021-nov", "F1", "2022-feb", "F3"].sort(sortAlphaNum);
                    console.log(newlist);
                   var newlist = ["A1", 1, "Category", "2022-01", "code", "2021-10", 3, 2021-09, 2, "A2", "A3", "2021-12", "B10", "2021-11", "F1", "2022-02", "F3"].sort(sortAlphaNum);
                    console.log(newlist);
                     const data = ["A1", 1, "Category", 2022.01, "code", 2021.10, 3, 2021.09, 2, "A2", "A3", 2021.12, "B10", 2021.11, "F1", 2022.02, "F3"];
                    const checkOfSamePattern = (a, b) => (isNaN(a) && isNaN(b)) || (!isNaN(a) && !isNaN(b));
                    const output = data.sort((a, b) => checkOfSamePattern(a, b) ? a > b ? 1 : -1 : isNaN(a) ? -1 : 1);
                    console.log(output);*/
                    
					return Object.getOwnPropertyNames(obj).slice(0, -1).sort(sortAlphaNum)
					//console.log(Object.getOwnPropertyNames(obj).slice(0, -1));
				}
			});
			
	
			window.localStorage.clear();
	}]);
/*	
var start = new Date($('#start').val());
var end = new Date($('#end').val());
var diff = Math.floor((end-start) / (365.25 * 24 * 60 * 60 * 1000));
console.log(diff);


var startDate = "11-15"

var d = new Date();
var m = d.getMonth() + 1;
var y = d.getFullYear().toString().substr(-2);
d=startDate.split("-")
counter = parseInt(d[0])
for(var i=parseInt(d[1]);i<=parseInt(y);i++)
{
  for(var j=counter;j<=12;j++){
    if(j>m && i==y){
       continue
    }
    console.log(j+"-"+i)
  }
  counter = 1;
}*/

	fetch.filter('myNumber', ['$filter', function($filter) {
        return function(value, fractionSize) {
            if (!angular.isNumber(value)) {
                return value;
            }

            return $filter('number')(value, fractionSize);
        }
    }]);
</script>
<script type="text/javascript">
	$(function() {
		$('.date-picker').datepicker({
			changeMonth: true,
			changeYear: true,
			showButtonPanel: true,
			dateFormat: 'MM yy',
			onClose: function(dateText, inst) { 
				$(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
			}
		});
	});	
</script>
	</body>
</html>