<?php 

$year = $_REQUEST['year']
 ?>
 
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <title><?= $config['CompanyName'] ?></title>
 
     <!-- Bootstrap -->
     <link href="../css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="../css/bootstrap-combobox.css" />
 
     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
     <!--[if lt IE 9]>
       <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
       <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="../js/bootstrap.min.js"></script>
       	 <script src="../js/bootstrap-combobox.js"></script>
       	 <script src="../js/excellentexport.js"></script>
				 <script src="../js/functions.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
       //        $('.grpline').css("width", "100px");
							
             });
						 
						 function manualUpdate(){
								if(confirm('Are you sure you want to import the quota data from: ' + '<?= date("m/d/y", filemtime('uploads/salesmanquota.csv')) ?>')){
									$.get('import_csv.php?for=salesmanquota&a=replace', function(data){
										//data = JSON.parse(data);
										alert("Processed Rows: " + data.result.trueCount + "\n" + 'Failures: ' + data.result.falseCount +  "\n End Result: " + data.result.result);
										location.reload();
									});
								}
						 }
           </script>

     <![endif]-->
	<link rel="stylesheet" href="../css/styles.css"/>
	
   </head>
   <body>
   
       <?php include("navbar.php"); ?>     

   
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
<div class="container " style="padding-top: 10px; width: 100%;">
	<div class="panel panel-default">
	  <div class="panel-heading form-inline">
			<?php
			if(!isset($_REQUEST['print'])){
				$idTag = "managesalesmanquota-data";
			}else{
				$idTag = "managesalesmanquota";
			}
			?>
	   <a class="btn btn-success hidden-print pull-right" role="button" href="#" download="ManageSalesmanQuota<?= $year ?>.xls" href="#" onclick="return ExcellentExport.excel(this, '<?= $idTag ?>', 'Manage Salesman Quota');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>
	  <a class="btn btn-success hidden-print pull-right" style="margin-right: 10px;"role="button"  href="#" data-toggle="tooltip" onclick="manualUpdate()" data-placement="left" title="">Manual Update (<?= date("m/d/y", filemtime('uploads/salesmanquota.csv')) ?>) </a>
		<a class="btn btn-warning hidden-print pull-right" style="margin-right: 30px;"role="button"  href="#" data-toggle="tooltip" onclick="showSales()" data-placement="left" title="">Toggle Show Sales</a>
		<a class="btn btn-primary hidden-print pull-right" style="margin-right: 30px;"role="button"  href="#" data-toggle="tooltip" onclick="window.location = window.location + '&print'" data-placement="left" title="">Exportable Version</a>
	  	<script>
				var salesShown = false;
				function showSales(){
					if(salesShown === false){
						for(var i= 0; i<$('.quotaCell').length; i++){
							$($('.quotaCell')[i]).append("<span class='salesCell' style='background-color: yellow;'><br>" + moneyFormat($($('.quotaCell')[i]).parent().attr('data-mtd')) + "</span>");
						}
						for(var i= 0; i<$('.salesmanTotalCell').length; i++){
							$($('.salesmanTotalCell')[i]).append("<span class='salesCell' style='background-color: yellow;'><br>" + moneyFormat($($('.salesmanTotalCell')[i]).attr('data-ytd')) + "</span>");
						}
						salesShown = true;
					}else{
							$('.salesCell').remove();
							salesShown = false;
					}
									
					
				}
				
			</script>
	  	
	  		    <h3 class="panel-title">Salesman Quota <?= $year ?></h3><br />
				
	  </div>
	  <div class="panel-body">
			
	  	<table class="table table-hover table-condensed" id="managesalesmanquota">
	  		<thead class="fixedHeader">
	  			<tr>
	  				<th>SM</th>
	  				<th>January </th>
					<th>February </th>
					<th>March </th>
					<th>April </th>
					<th>May </th>
					<th>June </th>
					<th>July </th>
					<th>August </th>
					<th>September </th>
					<th>October </th>
					<th>November </th>
					<th>December </th>
					<th>Total</th>
					<th>Edit</th>
	  			</tr>
	  			
	  		</thead>
				<tbody class="scrollContent">
	    <?php 
	    $query = "SELECT Salesman, FullName FROM `SALESMAN_QUOTA` left join `SALESMAN` on SALESMAN.ID = SALESMAN_QUOTA.Salesman WHERE Year = " . $_REQUEST['year'] . " GROUP BY Salesman HAVING SUM(Goal) > 0 ORDER BY Salesman";
		$result = mysqli_query($con, $query);
		$months = array(1,2,3,4,5,6,7,8,9,10,11,12);
	  $totalMonth = array(0,0,0,0,0,0,0,0,0,0,0,0,0);
		$totalTargetMonth = array(0,0,0,0,0,0,0,0,0,0,0,0,0);
		$totalMTDMonth = array(0,0,0,0,0,0,0,0,0,0,0,0,0);
		$grandTotal = 0;
		$totalYTD = 0;
		while($row = mysqli_fetch_array($result)){
			echo "<tr>
	   			<td>" . $row['Salesman'] . "</td>";
			$totalSalesman = 0;
			$salesmanYTD = 0;
			$salesmanYTDTarget = 0;
			foreach($months as $month){
				$goal = 0;
				
				$query2 = "SELECT * FROM SALESMAN_QUOTA WHERE Year = " . $_REQUEST['year'] . " AND Month = $month AND Salesman = '" . $row['Salesman'] . "'";
				$result2 = mysqli_query($con, $query2);
				$remainingDays = 0;
				$workingDays = getWorkingDays($month, $_REQUEST['year']);
				$lastDay = date("t", strtotime($month . "/2/" . $_REQUEST['year'])-(24*60*60));
					
				if($_REQUEST['year'] . "-" . str_pad($month, 2, '0', STR_PAD_LEFT) == date('Y-m')){
					$today = date("d", time()-(24*60*60));
					$remainingDays = 0;
					for($i = $today; $i < $lastDay; $i++ ){
						if(date('w', strtotime(date('m') . '/' . $i . '/' . date('y'))) != 5 && date('w', strtotime(date('m') . '/' . $i . '/' . date('y'))) != 6){
							$remainingDays++;
							
						}
					}
					//$remainingDays = $remainingDays . " -> " . $_REQUEST['year'] . "-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "==" .  date('Y-m');
				}elseif($_REQUEST['year'] . "-" . str_pad($month, 2, '0', STR_PAD_LEFT) > date('Y-m')){
					$today = 1;
					$remainingDays = 0;
					for($i = $today; $i < $lastDay; $i++ ){
						if(date('w', strtotime(date('m') . '/' . $i . '/' . date('y'))) != 5 && date('w', strtotime(date('m') . '/' . $i . '/' . date('y'))) != 6){
							$remainingDays++;
							
						}
					}
					//$remainingDays = $remainingDays . " -> " . $_REQUEST['year'] . "-" . str_pad($month, 2, '0', STR_PAD_LEFT) . ">" .  date('Y-m');
				}else{
					$remainingDays = 0;
					//$remainingDays = $remainingDays . " -> " . $_REQUEST['year'] . "-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "<=" .  date('Y-m');
				}
				$goal = 0;
				$row2['MTD'] = 0;
				$arrow = '';
				$arrowColor = '';
				$arrowTag = '';
				$target = 0;
				if(mysqli_num_rows($result2) > 0){
					$row2 = mysqli_fetch_array($result2);
					$goal = $row2['Goal'];
					$totalMonth[$month] += $goal;
					$totalMTDMonth[$month] += $row2['MTD'];
					$totalSalesman += $goal;
					$salesmanYTD += $row2['MTD'];
					$grandTotal += $goal;
					$totalYTD += $row2['MTD'];
					$target = ($goal/$workingDays)*($workingDays-$remainingDays);
					//var_dump($remainingDays);
					if($target == 0){
						//$target = 1;
					}
					if($remainingDays>0){
						
						$arrow = $row2['MTD']/$target>= 1?"up":"down";
						$word = $row2['MTD']/$target >= 1?"Over":"Short";
						$difference = $row2['MTD'] - $target;
						$salesmanYTDTarget += $target;
						$totalTargetMonth[$month] += $target;
					}else{
						$arrow = $row2['MTD']/$row2['Goal'] >= 1?"up":"down";
						$word = $row2['MTD']/$row2['Goal'] >= 1?"Over":"Short";
						$difference = $row2['MTD'] - $row2['Goal'];
						$salesmanYTDTarget += $row2['Goal'];
						$totalTargetMonth[$month] += $row2['Goal'];
					}
					
					$arrowColor = $arrow == "up"?"blue":"red";
					if($row2['MTD'] == 0){
						$arrowTag = "";	
					}else{
						$arrowTag = "<span style=\"color: $arrowColor;\" class=\"glyphicon glyphicon-arrow-" . ($arrow) . "\" aria-hidden=\"true\"></span>";
					}
					
					
				}
				echo "<td data-target=\"" . $target . "\" data-word=\"" . $word . "\" data-difference=\"" . $difference . "\" data-salesmanname=\"" . $row['FullName'] . "\" alt=\"" . $row2['MTD'] . "\" data-mtd=\"" . $row2['MTD'] . "\" onclick=\"editSalesmanQuota(this)\" data-salesman=\"" . $row['Salesman'] . "\" data-year=\"$year\" data-month=\"" . $month . "\" data-quota=\"" . $goal . "\" data-originalquota=\"" . $goal . "\"><a class='quotaCell' href='#'>" . moneyFormat($goal) . "</a>$arrowTag</td>";
			}
			$arrowYTD = $salesmanYTD/$salesmanYTDTarget >= 1?"up":"down";
			$arrowColorYTD = $arrowYTD == "up"?"blue":"red";
			$wordYTD = $salesmanYTD/$salesmanYTDTarget >= 1?"Over":"Short";
			$differenceYTD = $salesmanYTD - $salesmanYTDTarget;
			$arrowTagYTD = "<span style=\"color: $arrowColorYTD;\" class=\"glyphicon glyphicon-arrow-" . ($arrowYTD) . "\" aria-hidden=\"true\"></span>";
			echo "<td id='totalSalesman-" . $row['Salesman'] . "' style='font-weight: bold;white-space: nowrap;'  class='salesmanTotalCell' data-ytd='$salesmanYTD'>" . moneyFormat($totalSalesman) . $arrowTagYTD . "</td>";
		?>
				<td>
					<div class="form-inline">
						<div class="form-group">
							<div class="input-group">
								<input style="width: 45px;" type="text" data-salesman="<?= $row['Salesman'] ?>" data-year="<?= $year ?>" data-type="SalesmanYear" class="form-control" id="PercentSalesman-<?= $row['Salesman'] ?>" placeholder="%">
								<div class="input-group-addon"><a class="saveRow" onclick="bulkSave(this)" href="#"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span></a></div>
							</div>
						</div>
					</div>
				</td>
		<?php
			echo "</tr>";
		}
		echo "<tr>";
		for($i = 0; $i <= 12; $i++){
			
			$arrowMonth = @($totalMTDMonth[$i]/$totalTargetMonth[$i] >= 1)?"up":"down";
			$arrowColorMonth = $arrowMonth == "up"?"blue":"red";
			$wordMonth = @($totalMTDMonth[$i]/$totalTargetMonth[$i] >= 1)?"Over":"Short";
			$differenceMonth = $totalMTDMonth[$i] - $totalTargetMonth[$i];
			$arrowTagMonth = "<span style=\"color: " . $arrowColorMonth . ";\" class=\"glyphicon glyphicon-arrow-" . ($arrowMonth) . "\" aria-hidden=\"true\"></span>";
			//echo "<td id='totalSalesman-" . $row['Salesman'] . "' style='font-weight: bold;'>" . moneyFormat($totalSalesman) . $arrowTagYTD . "</td>";
			//var_dump($arrowColorMonth);
			
			
			if($i != 0){
				echo "<td id='totalMonth-$i' style='white-space: nowrap;'><b>" . moneyFormat($totalMonth[$i]) . $arrowTagMonth . '</b><br><i>' . moneyFormat($totalMTDMonth[$i]) . "<br><b>" . $wordMonth . '</b>: ' . round($totalMTDMonth[$i]/$totalMonth[$i]*100,2) . "%" . "</i></td>";
			}else{
				echo "<td style='font-weight: bold;'>Total</td>";
			}
		}
		echo "</tr>";
		?>
				<tr>
				<?php
					for($i = 0; $i <= 12; $i++){
						if($i != 0){
				?>
					<td>
							<div class="form-inline">
								<div class="form-group">
									<div class="input-group">
										<input style="width: 45px;" data-month="<?= $i ?>" data-year="<?= $year ?>" data-type="MonthYear" type="text" class="form-control" id="Percent-<?= $i ?>" placeholder="%">
										<div class="input-group-addon"><a class="saveRow" onclick="bulkSave(this)" href="#"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span></a></div>
									</div>
								</div>
							</div>
						</td>
				
				<?php
						}else{
							echo "<td style='font-weight: bold;'></td>";
						}
					}
				
				?>
						
				</tr>
				</tbody>
	     </table>
	
	  </div>
	  <div class="panel-footer" style="height: 100px;" >
	  	<div style="float: right; font-weight: bold;">
				<span>Grand Total: </span><span><big id="totalQuota"><?= moneyFormat($grandTotal) ?></big></span>
				<br />
				<span>Total YTD: </span><span style="background-color: yellow;"><big><?= moneyFormat($totalYTD) ?></big></span>
				
				<!--
				<div class="form-inline">
					<div class="form-group">
						<div class="input-group">
							<input style="width: 45px;" data-year="<?= $year ?>" data-type="FullYear" type="text" class="form-control" id="Percent-<?= $i ?>" placeholder="%">
							<div class="input-group-addon"><a class="saveRow" onclick="bulkSave(this)" href="#"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span></a></div>
						</div>
					</div>
				</div>
			-->
			</div>
	  </div>
	  
	</div>

</div>       
<script type="text/javascript">
	function bulkSave(element){
		var inputField = $($(element).parent().siblings()[0]);
		var InputType = inputField.attr('data-type');
		var InputYear = inputField.attr('data-year');
		var PercentAmount = parseFloat(inputField.val());
		if(!isNaN((PercentAmount))){
			if(InputType == "MonthYear"){
				var InputMonth = inputField.attr('data-month');
				console.log("Subir un " +  PercentAmount + "% al mes : " + InputMonth + " year: " + InputYear +"");
				$.get('mod.php?p=salesmanquota&a=functions&f=bulkSaveQuota&type=' + InputType + '&axis=' + InputMonth + '&percent=' + PercentAmount + '&year=' + InputYear, function(data){
						data = JSON.parse(data);
						if(data.result === true){
							location.reload();
						}else{
							alert('Unexpected error: ' + data.error);
						}
						
					});
			}else if(InputType == "SalesmanYear"){
				var InputSalesman = inputField.attr('data-salesman');
				console.log("Subir un " +  PercentAmount + "% al vendedor : " + InputSalesman + " year: " + InputYear +"");
				$.get('mod.php?p=salesmanquota&a=functions&f=bulkSaveQuota&type=' + InputType + '&axis=' + InputSalesman + '&percent=' + PercentAmount + '&year=' + InputYear, function(data){
						data = JSON.parse(data);
						if(data.result === true){
							location.reload();
						}else{
							alert('Unexpected error: ' + data.error);
						}
					});
			}else if(InputType == "FullYear"){
				$.get('mod.php?p=salesmanquota&a=functions&f=bulkSaveQuota&type=' + InputType + '&axis=' + null + '&percent=' + PercentAmount + '&year=' + InputYear, function(data){
						data = JSON.parse(data);
						if(data.result === true){
							location.reload();
						}else{
							alert('Unexpected error: ' + data.error);
						}
					});
			}
		}else{
			alert('Please enter a valid number');
			inputField.focus();
			return;	
		}
	}
	function editSalesmanQuota(cell){
		clearSalesmanModal();
		cell = $(cell);
		$('#editSalesmanQuotaSalesman').val(cell.attr('data-salesman'));
		$('#editSalesmanQuotaSalesmanName').val(cell.attr('data-salesmanname'));
		$('#editSalesmanQuotaMonthYear').val(cell.attr('data-month') + ' - ' + cell.attr('data-year'));
		$('#editSalesmanQuotaMonth').val(cell.attr('data-month'));
		$('#editSalesmanQuotaYear').val(cell.attr('data-year'));
		$('#editSalesmanQuotaMTD').val(moneyFormat(cell.attr('data-mtd'))	);
		$('#editSalesmanQuotaTarget').val(moneyFormat(cell.attr('data-target')));
		$('#editSalesmanQuotaQuota').val(cell.attr('data-quota'));
		$('#editSalesmanQuotaOriginalQuota').val(cell.attr('data-quota'));
		$('label[for=editSalesmanQuotaDifference]').text(cell.attr('data-word'));
		$('#editSalesmanQuotaDifference').val(moneyFormat(cell.attr('data-difference')));
		$('#editSalesmanQuota').modal('show');
	}
	function clearSalesmanModal(){
		$('#editSalesmanQuotaSalesman').val('');
		$('#editSalesmanQuotaSalesmanName').val('');
		$('#editSalesmanQuotaMonthYear').val('');
		$('#editSalesmanQuotaMonth').val('');
		$('#editSalesmanQuotaYear').val('');
		$('#editSalesmanQuotaMTD').val('');
		$('#editSalesmanQuotaTarget').val('');
		$('#editSalesmanQuotaQuota').val('');
		$('#editSalesmanQuotaOriginalQuota').val('');
		$('label[for=editSalesmanQuotaDifference]').text('Short or Over');
		$('#editSalesmanQuotaDifference').val('');
	}
	function saveSalesmanQuota(){
		var month = $('#editSalesmanQuotaMonth').val();
		var year = $('#editSalesmanQuotaYear').val();
		var salesman = $('#editSalesmanQuotaSalesman').val();
		var quota = $('#editSalesmanQuotaQuota').val();
		$.get('mod.php?p=salesmanquota&a=functions&f=saveQuotaData&year=' + year + '&month=' + month + '&sid=' + salesman + '&quota=' + quota, function(data){
				if(data.trim() === "true"){
					$('#editSalesmanQuota').modal('hide');
					location.reload();
				}else{
					alert('There has been an error: \n' + data);
				}
			});
	}
	$('.quotaCell').click(function(e) {
    e.preventDefault();
});
	function reloadQuota(){
		var cells = $('td');
		var totalQuota = 0;
		for(var i = 0; i < cells.length; i++){
			if(hasAttr(cells[i],'data-quota')){
				totalQuota += parseFloat($(cells[i]).attr('data-quota'));
				$(cells[i]).find('a').text(moneyFormat($(cells[i]).attr('data-quota')));
				//console.log($(cells[i]).attr('data-quota'));
			}
		}
		$('#totalQuota').text(moneyFormat(totalQuota));
	}
	function hasAttr(item, attribute){
		var attr = $(item).attr(attribute);

		// For some browsers, `attr` is undefined; for others,
		// `attr` is false.  Check for both.
		if (typeof attr !== typeof undefined && attr !== false) {
				return true;
		}else{
				return false;
		}
	}
	
	function updateBulkQuota(field){
		if(hasAttr(field, "data-type")){
			var percent = parseFloat($(field).val());
			if($(field).val() === ""){
				percent = 0;	
			}
			
			
			if(isNaN(percent)){
				
				alert('Please enter a valid number');
				$(field).focus();
				return;
			}else{
				$(field).val(percent);
			}
			percent = percent/100;
			percent += 1;
			switch($(field).attr('data-type')){
				case "SalesmanYear":
					var Salesman = $(field).attr('data-salesman');
					var Year = $(field).attr('data-year');
					var salesmanTotal = 0;
					var fieldList = $('td[data-salesman=' + Salesman +'][data-year=' + Year + ']');
					for(var i = 0; i < fieldList.length; i++){
						var currQuota = $($(fieldList)[i]).attr('data-originalquota');
						
						$($(fieldList)[i]).attr('data-quota', currQuota*percent);
						salesmanTotal += parseFloat($($(fieldList)[i]).attr('data-quota'));
					}
					$('#totalSalesman-' + Salesman).text(moneyFormat(salesmanTotal));
					reloadQuota();
					break;
				case "MonthYear":
					var Month = $(field).attr('data-month');
					var Year = $(field).attr('data-year');
					var monthTotal = 0;
					var fieldList = $('td[data-month=' + Month +'][data-year=' + Year + ']');
					for(var i = 0; i < fieldList.length; i++){
						var currQuota = $($(fieldList)[i]).attr('data-originalquota');
						
						$($(fieldList)[i]).attr('data-quota', currQuota*percent);
						monthTotal += parseFloat($($(fieldList)[i]).attr('data-quota'));
						//console.log(monthTotal);
					}
					$('#totalMonth-' + Month).text(moneyFormat(monthTotal));
					reloadQuota();
					break;
				case "FullYear":
					
					var fieldList = $('input [data-year=2017]');
					break;
			}
		}else{
			
		}
		
	}
	$('input').on('change', function(){
		updateBulkQuota(this);
		
		});
	function scrolify(tblAsJQueryObject, height){
        var oTbl = tblAsJQueryObject;
				

        // for very large tables you can remove the four lines below
        // and wrap the table with <div> in the mark-up and assign
        // height and overflow property  
        var oTblDiv = $("<div/>");
        oTblDiv.css('height', height);
        oTblDiv.css('overflow','scroll');               
        oTbl.wrap(oTblDiv);

        // save original width
        oTbl.attr("data-item-original-width", oTbl.width());
        oTbl.find('thead tr td').each(function(){
            $(this).attr("data-item-original-width",$(this).width());
        }); 
        oTbl.find('tbody tr:eq(0) td').each(function(){
            $(this).attr("data-item-original-width",$(this).width());
        });                 


        // clone the original table
        var newTbl = oTbl.clone();
				oTbl.attr('id', oTbl.attr('id') + "-data");
        // remove table header from original table
        oTbl.find('thead tr').remove();                 
        // remove table body from new table
        newTbl.find('tbody tr').remove();   

        oTbl.parent().parent().prepend(newTbl);
        newTbl.wrap("<div/>");

        // replace ORIGINAL COLUMN width                
        newTbl.width(newTbl.attr('data-item-original-width'));
        newTbl.find('thead tr th').each(function(){
            $(this).width($(this).attr("data-item-original-width"));
        });     
        oTbl.width(oTbl.attr('data-item-original-width'));
				var index = 0;
        oTbl.find('tbody tr:eq(0) td').each(function(){
            $(this).width($(this).attr("data-item-original-width"));
						$(newTbl.find('thead tr th')[index]).width($(this).attr("data-item-original-width"));
						index++;
        });                 
    }
		 $(document).ready(function(){
				<?php
				if(!isset($_REQUEST['print'])){
				?>
        scrolify($('#managesalesmanquota'), 550); // 160 is height
				<?php
				}
				?>
    });
</script>

   </body>
   
 </html>
 <?php
 
 
 ?>