<style>
	.tooltip-wrap {
		position: relative;
	}

	.tooltip-wrap .tooltip-content {
		display: none;
		position: absolute;
		bottom: 10%;
		left: 10%;
		right: 10%;
		color: black;
		background-color: #A9CCE3;
		padding: .10em;
		border-radius: 5px;
		border: #5D6D7E 0.5px solid;
		width: 140px;
	}

	.tooltip-wrap:hover .tooltip-content {
		display: block;
	}

	.tooltip-wrap .tooltip-content p {
		margin-left: 2px;
	}
	#toggleFilters:hover {
            cursor: pointer;
        }
</style>

<input type="hidden" id="vurl" value="<?= site_url('sales/get_sales/') ?>">
<section class="content">
	<div class="row">
		<div class="col-xs-12">
			<div class="box" style="border-top: 2.5px solid #9fc10b;">
				<div class="box-header" >
					<h4><a id="toggleFilters">
						Filtros <i class="fa fa-chevron-down"></i> 
					</a></>
				</div>
				<div class="box-body" id="form-filtros" style="padding-top: 0px;">
					<div class="col-lg-12">
						<div class="row">
							<div class="col-md-3">
								<label for="fechaInicio">Fecha inicio</label>
								<div class='input-group date' id='divFechaInicio'>
									<input type='text' id="fechaInicio" class="input-medium form-control" placeholder="dd/mm/aaaa" readonly />
									<span class="input-group-addon">
										<span class="fa fa-calendar glyphicon glyphicon-calendar"></span>
									</span>
								</div>
							</div>
							<div class="col-md-3">
								<div class="form-group">
									<label for="fechaFin">Fecha fin</label>
									<div class="input-group date" id="divFechaFin">
										<input class="input-medium form-control" type="text" id="fechaFin" placeholder="dd/mm/aaaa" readonly>
										<span class="input-group-addon" id="calendarioEnvio">
											<span class="fa fa-calendar glyphicon glyphicon-calendar"></span>
										</span>
									</div>
								</div>
							</div>
							<div class="col-md-2">
								<div class="form-group">
									<?= lang('status_sale', 'status_sale'); ?>
									<?php
									$sw['todos'] = 'todos';
									$sw['Debe'] = 'Debe';
									$sw[lang('st_partial')] = lang('st_partial');
									$sw[lang('st_paid')] = lang('st_paid');
									?>
									<?= form_dropdown('estado', $sw, "", 'class="form-control select2 estado" id="estado"  required="required" style="width:100%;"'); ?>
								</div>
							</div>
							<div class="col-md-2">
								<div class="form-group">
									<?= lang('invoice_status', 'invoice_status'); ?>
									<?php
									$see['1'] = lang('active');
									$see['3'] = lang('canceled');
									$see['2'] = lang('all');
									?>
									<?= form_dropdown('estadof', $see, "", 'class="form-control select2 estado" id="estadof"  required="required" style="width:100%;"'); ?>
								</div>
							</div>

							<div class="col-md-2 botones">
								<div class="form-group">
									<button type="button" id="btnSearch" class="btn btn-sm btn-success"><?= lang("search2") ?></button>
								</div>
							</div>

						</div>
						<?php if ($this->session->userdata('traders')) { ?>
							<div class="row">
								<div class="col-md-2">
									<div class="form-group">
										<?= lang('traders', 'traders'); ?>
										<?php
										$trader_list = array();
										$trader_list['todos'] = "todos";
										foreach ($traders as $trader) {
											$trader_list[$trader['id']] = $trader['last_name_1'] . ' ' . $trader['last_name_2'] . ', ' . $trader['name'];
										}
										?>
										<?= form_dropdown('traders_id', $trader_list, "", 'class="form-control select2" id="traders_id"  required="required" style="width:100%;"'); ?>
									</div>
								</div>
							</div>
						<?php } ?>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div class="row">
		<div class="col-xs-12">
			<div class="box" style="border-top: 2.5px solid #004785;">
				<div class="box-header">
					<div class="btn btn-sm btn-success col-md-offset-10" onclick="exportTableToExcel()"><i class="fa fa-file-excel-o"></i> Exportar Excel</div>
					<hr>
				</div>
				<div class="box-body">
					<div class="table-responsive">
						<table id="tableSales" class="table table-striped table-bordered table-condensed table-hover" style="width:100%">
							<thead class="text-center">
								<tr>
									<th><?php echo $this->lang->line("date"); ?></th>
									<th>Tipo</th>
									<th>N° <?php echo $this->lang->line("proof"); ?></th>
									<th class="col-xs-2"><?php echo $this->lang->line("customer"); ?></th>
									<th><?php echo $this->lang->line("currency_name"); ?></th>
									<th><?php echo $this->lang->line("total_sale"); ?></th>
									<th><?php echo $this->lang->line("paid"); ?></th>
									<th><?php echo $this->lang->line("status_sale"); ?></th>
									<th><?php echo $this->lang->line("invoice_status"); ?></th>
									<th><?php echo $this->lang->line("send_status"); ?></th>
									<th><?php echo $this->lang->line("local"); ?></th>
									<th style="text-align:center; width: 100px;"><?php echo $this->lang->line("actions"); ?></th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td colspan="9" class="dataTables_empty"><?= lang('loading_data_from_server'); ?></td>
								</tr>
							</tbody>
						</table>
					</div>
					<div class="clearfix"></div>
				</div>
			</div>
		</div>
	</div>
	<!--    Datatables-->
	<script type="text/javascript" src="<?= $assets ?>plugins/datatables/datatable.min.js"></script>
	<script src="<?= $assets ?>plugins/input-mask/jquery.inputmask.js" type="text/javascript"></script>
	<script src="<?= $assets ?>plugins/input-mask/jquery.inputmask.date.extensions.js" type="text/javascript"></script>
	<script src="<?= $assets ?>plugins/bootstrap-datetimepicker/js/moment.min.js" type="text/javascript"></script>
	<script src="<?= $assets ?>plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js" type="text/javascript"></script>

	<script>
		var contador=0;
		function exportTableToExcel() {
			$(".table").table2excel({
				//exclude: "#tableID",
				name: "Excel Document Name",
				filename: "FacsiSoft - Reporte de Ventas",
			});
		}

		function sumarDias(fecha, dias) {
			fecha.setDate(fecha.getDate() + dias);
			return fecha;
		}
		$(document).ready(function() {
			$('#form-filtros').hide();

			$('#toggleFilters').click(function() {
                // Cambia el ícono basado en la dirección actual
                var icon = $(this).find('i');
                if (icon.hasClass('fa-chevron-down')) {
                    icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
					$('#form-filtros').show();

                } else {
                    icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
					$('#form-filtros').hide();

                }
            });
			//obteniendo fecha actual
			var fActual = new Date().toISOString().split('T')[0];
			//obtneieendo fecha con 30 dias antes de la fecha actual
			var fInicio = (sumarDias(new Date(), -30).toISOString().split('T')[0]);
			//pasando los valores a los filtros de fecha
			$('#fechaInicio').val(fInicio.split("-").reverse().join("/"));
			$('#fechaFin').val(fActual.split("-").reverse().join("/"));
			//Llenado el datatable

			dibujarDt("", "", 1, fInicio, fActual);

			function restriccionbotonDescarga(document_type, nro_doc) {

						if (document_type == "Nota de venta") {
							$('#id-download-' +nro_doc ).hide();
						}
						if (document_type == "Boleta") {
							$('#id-download-cdr-' + nro_doc).hide();
						}

			}

			function dibujarDt(traders_id, paid_status, status_invoice, fecha_inicio, fecha_fin) {
				$("#tableSales").DataTable({
					"aLengthMenu": [
						[10, 25, 50, 100, -1],
						[10, 25, 50, 100, '<?= lang('all'); ?>']
					], //keny ponte
					"processing": true,
					"serverSide": true,
					"bDestroy": true,
					"aaSorting": [
						[0, "desc"]
					],
					"data": {
						"status_sale": "DEBE",
						"status_invoice": "1"
					},
					"iDisplayLength": <?= $Settings->rows_per_page ?>, //keny ponte
					"sAjaxSource": $("#vurl").val(),
					"fnServerParams": function(aoData) {
						aoData.push({
							"name": "traders_id",
							"value": traders_id
						}, {
							"name": "paid_status",
							"value": paid_status
						}, {
							"name": "status_invoice",
							"value": status_invoice
						}, {
							"name": "fecha_inicio",
							"value": fecha_inicio
						}, {
							"name": "fecha_fin",
							"value": fecha_fin
						});
					},
					"aoColumns": [{
							"mRender": hrld,
							"bSearchable": false
						},
						{
							"mRender": function(data, type, row) {								
								restriccionbotonDescarga(data,row[2]);
								return data;
							}
						},
						null,
						null,
						{
							"mRender": function(data) {
								return (data == "PEN") ? '<center><span class="label label-primary">PEN</span></center>' : '<center><span class="label label-success">USD</span></center>';
							}
						},
						{
							"mRender": currencyFormat
						},
						{
							"mRender": currencyFormat
						},
						{
							"mRender": function(data) {
								if (data == "DEBE") {
									var $data = data.toLowerCase()
									return $data.replace(/^.{1}/g, $data[0].toUpperCase())
								} else {
									return data;
								}
							}
						},
						{
							"mRender": function(data, type, row) {
								if (data == 1) {
									return '<td><strong style="color:#13AD78">Activo</strong></td>';
								} else {
									var anulada = '<td><strong style="color:#9E2020;">Anulado</strong></td>';
									return anulada;
								}
							}
						},
						{
							"mRender": function(data) {
								var arr = data.split('|');
								if (arr[0] != "Rechazado") {
									return arr[0];

								} else {
									if (arr[1] != "") {
										return '<div class="tooltip-wrap"><p  style="color:red">' + arr[0] + '</p><div class="tooltip-content"><p>' + arr[1] + '</p></div></div>';

									} else {
										return '<p  style="color:red">' + arr[0] + '</p>'
									}
								}
							}
						},
						null,
						{
							"bSortable": false,
							"bSearchable": false
						}
					],
				});

			}
			$("#btnSearch").click(
				function() {
					var fI = $("#fechaInicio").val();
					var fF = $("#fechaFin").val();
					var fechaInicio = fI.split("/").reverse().join("-");
					var fechaFin = fF.split("/").reverse().join("-");
					if (fechaInicio != "" && fechaFin != "") {
						if (fechaInicio > fechaFin) {
							alert("La fecha de inicio no debe ser superior a la fecha de fin");
						} else {
							dibujarDt($("#traders_id").val(), $("#estado").val(), $("#estadof").val(), fechaInicio, fechaFin);

						}
					} else {
						dibujarDt($("#traders_id").val(), $("#estado").val(), $("#estadof").val(), fechaInicio, fechaFin);

					}
				}
			);
		});
	</script>
</section>
<script>
	$('#divFechaInicio').datetimepicker({
		format: 'DD/MM/YYYY',
		ignoreReadonly: true,

	});
	$('#divFechaFin').datetimepicker({
		format: 'DD/MM/YYYY',
		ignoreReadonly: true
	});
</script>