<?php $__env->startSection('CSS'); ?>
<?php echo HTML::style('DataTables/dataTables.bootstrap.min.css'); ?>

<?php echo HTML::style('DataTables/responsive.dataTables.min.css'); ?>

<?php echo HTML::style('bootstrap-daterangepicker/daterangepicker.css'); ?>

<?php echo HTML::style('bootstrap-select/css/bootstrap-select.min.css'); ?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<style type="text/css">
	@media (max-width: 450px) { .ModalEliminar .modal-dialog { width: auto; } }
	@media (min-width: 451px) { .ModalEliminar .modal-dialog { width: 450px; } }
	.dvSelect > .form-control { width: unset !important; }
</style>
<?php $__env->stopSection(); ?>


<?php $__env->startSection('Contenido'); ?>
<div class="row">
	<div class="col-md-12">
		<h2><i class="fa fa-file-pdf-o"></i> Reportes </h2>
	</div><!--/col-md-12-->
</div><!--/row-->

<div class="row">
	<div class="col-md-12">
		<?php if(Session::has('message')): ?>
		<div class="alert alert-info"><?php echo Session::get('message'); ?></div>
		<?php endif; ?>
	</div>
</div>

<div class="row">
	<div class="col-md-12">
		<div class="block-web">
			<div class="header">
				<h3 class="content-header">
					Reporte de retorno de la inversión
					<div data-toggle="buttons" class="button-group pull-right">
						<a class="refresh tooltips" data-toggle="tooltip" data-original-title="Actualizar registros" onclick="Actualizar()" href="javascript:Actualizar()" style="color: rgba(0, 0, 0, 0.3)">
							<i class="fa fa-repeat"> </i>
						</a>
					</div>
				</h3>
			</div>
			<div class="porlets-content">
				<form id="frmFiltroFechas" class="form-inline" style="padding-bottom: 15px;">
					<?php /*<?php foreach($Referencias as $indice => $Referencia): ?>
					<label class="checkbox-inline" <?php if( count($Referencias)-1 == $indice ): ?> style="padding-right: 5px;" <?php endif; ?>>
						<input type="checkbox" id="chReferencia<?php echo $Referencia->id; ?>" value="<?php echo $Referencia->id; ?>" name="chReferencia[]" checked>
						<span class="custom-checkbox"></span> <?php echo $Referencia->nombre; ?>

					</label>
					<?php endforeach; ?>
					<br>
					<br>*/ ?>
					<div class="form-group">
						<label for="FiltroFechas" style="padding-top: 10px;"> Fecha: </label>
						<input id="FiltroFechas" type="text" name="filtrofechas" value="" readonly>
					</div>
					<div class="form-group dvSelect">
						<label for="slReferencias"> Referencias: </label>
						<select class="form-control selectpicker" multiple data-live-search="true" data-selected-text-format="count" id="slReferencias" name="slReferencias[]">
							<?php foreach($Referencias as $indice => $Referencia): ?>
							<option value="<?php echo $Referencia->id; ?>" selected> <?php echo $Referencia->nombre; ?> </option>
							<?php endforeach; ?>
						</select>
					</div>
					<button type="submit" class="btn btn-primary"> Filtrar </button>
					<button id="btnLimpiar" type="button" class="btn btn-default"> Limpiar </button>
				</form>
				<div class="table-responsive">
					<table class="table table-striped table-bordered table-hover" id="tblReportes">
						<thead>
							<tr>
								<th class="text-center" style="width: 9%;"> Referencia </th>
								<th class="text-center" style="width: 9%;"> Inversión publicitaria </th>
								<th class="text-center" style="width: 9%;"> Venta </th>
								<th class="text-center" style="width: 9%;"> Ganancia </th>
								<th class="text-center" style="width: 9%;"> RDI </th>
								<th class="text-center" style="width: 9%;"> Retorno por cada <?php echo $Cliente->simbolo_moneda; ?> invertido </th>
								<th class="text-center" style="width: 9%;"> Cotizados sin venta </th>
								<th class="text-center" style="width: 9%;"> Ganancia potencial </th>
								<th class="text-center" style="width: 9%;"> RDI potencial </th>
							</tr>
						</thead>
						<tbody id="tbody">
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
	<div class="col-md-12">
		<div class="block-web">
			<div class="header">
				<h3 class="content-header"> Gráfica </h3>
			</div>
			<div class="porlets-content">
				<div id="Grafica"></div>
			</div>
		</div>
	</div>
</div><!--/row end-->
<?php $__env->stopSection(); ?>

<?php $__env->startSection('JS'); ?>
<?php echo HTML::script('DataTables/jquery.dataTables.min.js'); ?>

<?php echo HTML::script('DataTables/dataTables.bootstrap.min.js'); ?>

<?php echo HTML::script('DataTables/dataTables.responsive.min.js'); ?>

<?php echo HTML::script('bootstrap-daterangepicker/moment.min.js'); ?>

<?php echo HTML::script('bootstrap-daterangepicker/daterangepicker.js'); ?>

<?php echo HTML::script('bootstrap-select/js/bootstrap-select.min.js'); ?>

<?php echo HTML::script('bootstrap-select/js/i18n/defaults-es_CL.min.js'); ?>

<?php echo HTML::script('AccountingJS/accounting.min.js'); ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script type="text/javascript">
	var simbolo = "<?php echo $Cliente->simbolo_moneda; ?>";
	function Actualizar(){
		var table = $("#tblReportes").DataTable();
		table.ajax.reload(null, false);
		GenerarGrafica();
	}
	function GenerarTabla(){
		$.post(
			"<?php echo URL::route('SysWebRptGCRetornoInversion'); ?>",
			$("#frmFiltroFechas").serialize(),
			function(data){
				//console.log( data );
				var tbody = '';
				$.each(data, function(key, value){
					tbody = tbody+'<tr> \
						<td class="referencias"> '+value.referencia+' </td> \
						<td> <input type="text" id="txtInversion'+value.id+'" class="form-control txtInversion"> </td> \
						<td class="text-center Venta" id="tdVenta'+value.id+'"> '+accounting.formatMoney(value.ganancias, simbolo, 2, ",", ".")+' </td> \
						<td class="text-center" id="tdGanancia'+value.id+'"> </td> \
						<td class="text-center" id="tdRDI'+value.id+'"> </td> \
						<td class="text-center" id="tdRetorno'+value.id+'"> </td> \
						<td class="text-center VentaP" id="tdVentaP'+value.id+'">'+accounting.formatMoney((parseFloat(value.gananciasPotenciales)), simbolo, 2, ",", ".")+'</td> \
						<td class="text-center" id="tdGananciaP'+value.id+'"> </td> \
						<td class="text-center" id="tdRDIP'+value.id+'"> </td> \
					';
				});
				$("#tbody").html(tbody);
				$(".txtInversion").each(function(e){
					$(this).keydown(function (event) {
						if (event.shiftKey == true) {
							event.preventDefault();
						}
						if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {
						}
						else {
							if($(this).val().indexOf('.') !== -1){
								event.preventDefault();
							}
						}
						if($(this).val().indexOf('.') !== -1 && event.keyCode == 190){
							event.preventDefault();
							//if a decimal has been added, disable the "."-button
						}
					});
					$(this).blur(function(e){
						var id = parseInt( $(this).attr("id").replace("txtInversion", "") );
						if( $(this).val() != "" ){
							var venta = accounting.unformat($("#tdVenta"+id).html());
							var ventaP = accounting.unformat($("#tdVentaP"+id).html());
							//CALCULO LA GANANCIA REAL --------------------------------------------------------
							//var ganancia = parseFloat( $("#tdVenta"+id).html() ) - parseFloat( $(this).val() );
							var ganancia = parseFloat( venta ) - parseFloat( $(this).val() );
							$("#tdGanancia"+id).html( accounting.formatMoney(ganancia, simbolo, 2, ",", ".") );
							//---------------------------------------------------------------------------------
							//CALCULO LA GANANCIA POTENCIAL -----------------------------------------------------
							//var gananciaP = parseFloat( $("#tdVentaP"+id).html() ) - parseFloat( $(this).val() );
							//var gananciaP = (parseFloat( ventaP ) - parseFloat( $(this).val() )) + parseFloat( ganancia ) ;venta
							var gananciaP = (parseFloat( ventaP ) - parseFloat( $(this).val() )) + venta ;
							$("#tdGananciaP"+id).html( accounting.formatMoney(gananciaP, simbolo, 2, ",", ".") );
							//-----------------------------------------------------------------------------------
							//CALCULO EL ROI --------------------------------------
							var roi = (ganancia / parseFloat( $(this).val() ))*100;
							$("#tdRDI"+id).html( roi.toFixed(2)+"%" );
							//-----------------------------------------------------
							//CALCULO EL ROI POTENCIAL  -----------------------------
							var roiP = (gananciaP / parseFloat( $(this).val() ))*100;
							$("#tdRDIP"+id).html( roiP.toFixed(2)+"%" );
							//-------------------------------------------------------
							//CALCULO POR MONEDA -------------------------------------------------------------
							//var retorno = parseFloat( $("#tdVenta"+id).html() ) / parseFloat( $(this).val() );
							var retorno = parseFloat( venta ) / parseFloat( $(this).val() );
							$("#tdRetorno"+id).html( accounting.formatMoney(retorno, simbolo, 2, ",", ".") );
							//--------------------------------------------------------------------------------
						}
						else{
							$("#tdGanancia"+id).html("");
							$("#tdGananciaP"+id).html("");
							$("#tdRDI"+id).html("");
							$("#tdRDIP"+id).html("");
							$("#tdRetorno"+id).html("");
						}
						GenerarGrafica();
					});
				});
				GenerarGrafica();
			},
			"json"
		);
	}
	function GenerarGrafica(){
		var data = new Array();
		$(".referencias").each(function(e){
			var y = $(this).html();
			var a = ($(this).parent().find(".txtInversion").val() != "")?$(this).parent().find(".txtInversion").val():0;
			var b = accounting.unformat($(this).parent().find(".Venta").html());
			var c = accounting.unformat($(this).parent().find(".VentaP").html());
			data.push({ y: y, a: a, b: b, c: c });
		});
		if( typeof grafica  == "undefined" ){
			grafica = Morris.Bar({
				element: "Grafica",
				data: data,
				xkey: "y",
				ykeys: ["a", "b", "c"],
				barColors: ["#0197da", "#56be22", "#ffcd1b"],
				labels: ["Inversion", "Venta Real", "Venta potencial"],
				hoverCallback: function (index, options, content, row) {
					var contenido = '<div class="morris-hover-row-label"> '+row.y+' </div> \
						<div class="morris-hover-point" style="color: #0197da"> \
							Inversión: '+accounting.formatMoney(row.a, simbolo, 2, ",", ".")+' \
						</div> \
						<div class="morris-hover-point" style="color: #56be22"> \
							Venta real: '+accounting.formatMoney(row.b, simbolo, 2, ",", ".")+' \
						</div> \
						<div class="morris-hover-point" style="color: #ffcd1b"> \
							Venta potencial: '+accounting.formatMoney(row.c, simbolo, 2, ",", ".")+' \
						</div>';
					return(contenido);
				}
			});
		}
		else{
			grafica.setData(data);
		}
	}
	fx.base = "USD";
	fx.rates = {
		"USD" : 1,
	}
	// Load exchange rates data via AJAX:
	$.getJSON(
		// NB: using Open Exchange Rates here, but you can use any source!
		"https://openexchangerates.org/api/latest.json?app_id=9ea7b69a0b9b4371b4b1925d4c9254cf",
		function(data) {
			// Check money.js has finished loading:
			if ( typeof fx !== "undefined" && fx.rates ) {
				fx.rates = data.rates;
				fx.base = data.base;
			}
			else {
				// If not, apply to fxSetup global:
				var fxSetup = {
					rates : data.rates,
					base : data.base
				}
			}
		}
	);
</script>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('JSOr'); ?>
$(".sidebar-toggle-box").trigger("click");
GenerarTabla();
$("#FiltroFechas").daterangepicker({
	"ranges": {
		"Hoy": [moment(), moment()],
		"Ayer": [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
		"Últimos 7 días": [moment().subtract(6, 'days'), moment()],
		"Últimos 30 días": [moment().subtract(29, 'days'), moment()],
		"Este mes": [moment().startOf('month'), moment().endOf('month')],
		"Último mes": [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
	},
	"alwaysShowCalendars": true,
	locale: {
		format: 'DD/MM/YYYY'
	},
	autoUpdateInput: false,
	"startDate": moment(),
	"endDate": moment()
}, function(start, end, label) {
	console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')");
});
$("#FiltroFechas").on("apply.daterangepicker", function(ev, picker) { $(this).val(picker.startDate.format("DD/MM/YYYY") + " - " + picker.endDate.format("DD/MM/YYYY")); });
$("#FiltroFechas").on("cancel.daterangepicker", function(ev, picker) { $(this).val(""); });
$("#frmFiltroFechas").submit(function(e){
	e.preventDefault();
	GenerarTabla();
});
$("#btnLimpiar").click(function(e){
	e.preventDefault();
	$("#FiltroFechas").val("");
	GenerarTabla();
});
<?php if(Session::has('EliminarMensajeS')): ?>
new PNotify({ title: "Realizado", text: "<?php echo Session::get('EliminarMensajeS'); ?>", type: "success" });
<?php endif; ?>
<?php if(Session::has('EliminarMensajeE')): ?>
new PNotify({ title: "Realizado", text: "<?php echo Session::get('EliminarMensajeE'); ?>", type: "error" });
<?php endif; ?>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('BaseSistemaWeb', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>