<?php
session_start();
require("../conectar.php");
$id_cliente=$_POST["idcliente"];
$ema=$_POST["email"];
$mis=$_POST["mis"];
function HorasTranscurridas($FechaUltimaActualizacion){
	//Establecemos zona horaria por defecto
    date_default_timezone_set('America/Mexico_City');
    //preguntamos la zona horaria
    //echo "La hora en Chile es: " . date ("Y-m-d H:i:s",time()) . "<br />";
	$fecha=$FechaUltimaActualizacion;
	$segundos=strtotime($fecha) - strtotime('now');
	$diferencia_dias=intval($segundos/60/60/24);
	$diasderegistro=($diferencia_dias)*(-1);
	
	return $diasderegistro;
}
?>
<script>
	 function borrarCliente(id,td)
		{
		 var f=confirm( "En verdad quieres borrar el cliente?");
		 if(f==true)
			{
			 $.post("borrarcliente.php", {id:id}, function(data,status){
			 if(status=="success")
				{
				 $("#fila"+td).hide();
				 $("#msg").html("<div class='alert alert-success fade in'><a href='#' class='close' data-dismiss='alert'>&times;</a>El registro ha sido eliminado.</div>");
				} });
			}
		}
</script>

	 <?php if($nom=="" && $mis=="no" && $ema==""){echo "";}else{ ?>
	<div id="msg"></div> 
	<div class="row">
		<div class="col-xs-12">
		    <!--div class="clearfix">
				<div class="pull-right tableTools-container"></div>
			</div-->
			<div class="table-header">
				Resultado
			</div>
			<div class="table-responsive">
			 <div>
			   <table id="tpros" class="table table-striped table-bordered table-hover">
			      <thead>
						<tr>
							<th class="center">Estatus</th>
							<th>Registro</th>
							<th>Última Actualización</th>
							<th>Nombre</th>
							<th>Ejecutivo</th>
							<th>e-mail</th>
							<th>Opciones</th>
						</tr>
					</thead>
			        <tbody>
					   <?php
						  if($nom!=""){
								$no="HAVING nombres like '%$nom%'";								 
							 }
							 if($ema!=""){
								 if($nom!=""){$and="AND";}
								 $em="(c.email LIKE '$ema%' or c.email2 LIKE '$ema%' or c.email3 LIKE '$ema%') AND ";     
							 }
							 if($mis=="si"){
								 if($nom!="" || $ema!=""){$and="AND";}
								 $mi="c.id_emp = $_SESSION[usuario_id] AND ";				 
							 }
							 $cond="$em $mi";
							
							 $sql="SELECT renta.fecha,renta.id_renta,renta.id_ejecutivo,renta.fultima_act_p,(SELECT e.usuario FROM empleados e WHERE e.id_empleado=c.id_emp) as ejecutivo,c.id_emp, c.id_cliente, c.nombre, c.a_pat, c.a_mat, c.email,c.email2,c.email3,c.fecharegistro, concat(c.nombre,' ',c.a_pat,' ',c.a_mat) AS nombres FROM clientes as c inner join renta on renta.id_cliente=c.id_cliente WHERE renta.id_cliente = $id_cliente and renta.borrar='0' ORDER BY renta.fecha desc";
							 $con=mysql_query($sql);
							 $c="";
							 $i=1;
							 while($ls=mysql_fetch_array($con)){
							    $entro="si";
								$diascita= 15;
								$f3d=date("Y-m-d", strtotime("$fechaActual -$diascita day"));
								
								/*$sqls="SELECT id_cliente,id_ejecutivo FROM renta WHERE id_cliente='$ls[id_cliente]' AND ultimaact>='$f3d' ORDER BY ultimaact DESC LIMIT 1";
								$ejesema=mysql_query($sqls);
								$semaforo=mysql_num_rows($ejesema);*/
								
								$semaforo = HorasTranscurridas($ls['fultima_act_p']);
								

                                $sqlp="SELECT id_cliente,id_ejecutivo FROM renta WHERE id_renta='$ls[id_renta]' and id_renta IN (SELECT id_renta FROM pagos)";
								$ejep=mysql_query($sqlp);
								$semaforop=mysql_fetch_array($ejep);
								
								if($semaforo>=1){
									$img="<span title=' LO PUEDES MODIFICAR' class='label label-sm label-success'>Sin seguimiento</span>";
									}else{
									$img="<span title='NO PUEDES MODIFICAR' class='label label-sm label-warning'>Con seguimiento</span>";
								}
								if($semaforop){
									$p="<b>P </b>";
									}else{
									$p="";
								}
							  ?>
					    <tr id="fila<?php echo $i;?>">
						    <td class="center"><?php echo $p.$img;?></td>
							<td><?php echo $ls['fecha'];?></td>
							<td><?php echo $ls['fultima_act_p'];?></td>
							<td><?php echo htmlentities($ls["nombres"]);?></td>
							<td><?php echo htmlentities($ls['ejecutivo']);?></td>
							<td title="E-Mail Op.2 <?php echo $ls['email2']."\n";?> E-Mail Op.3 <?php echo $ls['email3']?>"><?php echo htmlentities($ls["email"]);?></td>
				            <td align="center"><a class="blue" href="javascript:detalleprospecto('<?php echo $ls['id_cliente'];?>','<?php echo $ls['id_renta'];?>')" title="Ver detalle"><i class="ace-icon fa fa-eye bigger-130"></i></a> | <a class="green" href="regmodificar2.php?idcliente=<?php echo $ls["id_cliente"];?>&idrenta=<?php echo $ls['id_renta'];?>" target="_blank" title="Modificar"><i class="fusion-li-icon fa fa-pencil bigger-130"></i></a> | <a class="pink" href="regmodificar3.php?idcliente=<?php echo $ls["id_cliente"];?>&idrenta=<?php echo $ls['id_renta'];?>" target="_blank" title="Renovar Renta"><i class="ace-icon fusion-li-icon fa fa-share bigger-130" ></i></a><?php if($_SESSION["usuario_nivel"]>4){?> | <a class="red" href="#" title="Eliminar prospecto" onclick="borrarCliente('<?php echo $ls["id_renta"];?>','<?php echo $i;?>');"><i class="ace-icon fa fa-trash-o bigger-130"></i></a><?php } ?> | <a class="orange" href="bitacorapros.php?idcliente=<?php echo $ls["id_cliente"];?>&idrenta=<?php echo $ls['id_renta'];?>" target="_blank" title="Bitacora de movimientos"><i class="fusion-li-icon fa fa-calendar bigger-130"></i></a></td>
							
						</tr>
							 <?php if($c==""){$c="1";}else{$c="";} $i++; } ?>
					</tbody>
				   </div>	
			   </table>
			</div>
		</div>
	</div>
	
<?php } ?>

	<script type="text/javascript">
			jQuery(function($) {
				//initiate dataTables plugin
				var oTable1 = 
				$('#tpros')
				//.wrap("<div class='dataTables_borderWrap' />")   //if you are applying horizontal scrolling (sScrollX)
				.dataTable( {
					
					bAutoWidth: false,
					"aoColumns": [
					  { "bSortable": false },
					  null,null, null,null, null,null   
					],
					"aaSorting": [],
					"language": {
                    "lengthMenu": "Mostrar _MENU_ registros por página",
					"zeroRecords": "No se encontraron resultados",
					"info": "Mostrando página _PAGE_ de _PAGES_ de _MAX_ registros",
					"infoEmpty": "No hay registros disponibles",
					"infoFiltered": "(Filtradodo de _MAX_ registros totales)",
					"search":"Buscar:",
					"processing":     "Procesando...",
					"emptyTable":     "Ningún dato disponible en esta tabla",
					"infoFiltered":   "(filtrado de un total de _MAX_ registros)",
					"loadingRecords": "Cargando...",
					"paginate": {
					"first":    "Primero",
					"last":     "Último",
					"next":     "Siguiente",
					"previous": "Anterior"
				},
                   }
			
			        //{ "bSortable": false }
					//,
					//"sScrollY": "200px",
					//"bPaginate": false,
			
					//"sScrollX": "100%",
					//"sScrollXInner": "120%",
					//"bScrollCollapse": true,
					//Note: if you are applying horizontal scrolling (sScrollX) on a ".table-bordered"
					//you may want to wrap the table inside a "div.dataTables_borderWrap" element
			
					//"iDisplayLength": 50
			    } );
				//oTable1.fnAdjustColumnSizing();
			   
			
				//TableTools settings
				TableTools.classes.container = "btn-group btn-overlap";
				TableTools.classes.print = {
					"body": "DTTT_Print",
					"info": "tableTools-alert gritter-item-wrapper gritter-info gritter-center white",
					"message": "tableTools-print-navbar"
				}
			
				//initiate TableTools extension
				var tableTools_obj = new $.fn.dataTable.TableTools( oTable1, {
					"sSwfPath": "../assets/swf/copy_csv_xls_pdf.swf",
					
					"sRowSelector": "td:not(:last-child)",
					"sRowSelect": "multi",
					"fnRowSelected": function(row) {
						//check checkbox when row is selected
						try { $(row).find('input[type=checkbox]').get(0).checked = true }
						catch(e) {}
					},
					"fnRowDeselected": function(row) {
						//uncheck checkbox
						try { $(row).find('input[type=checkbox]').get(0).checked = false }
						catch(e) {}
					},
			
					"sSelectedClass": "success",
			        "aButtons": [
						{
							"sExtends": "copy",
							"sToolTip": "Copy to clipboard",
							"sButtonClass": "btn btn-white btn-primary btn-bold",
							"sButtonText": "<i class='fa fa-copy bigger-110 pink'></i>",
							"fnComplete": function() {
								this.fnInfo( '<h3 class="no-margin-top smaller">Table copied</h3>\
									<p>Copied '+(oTable1.fnSettings().fnRecordsTotal())+' row(s) to the clipboard.</p>',
									1500
								);
							}
						},
						
						{
							"sExtends": "csv",
							"sToolTip": "Export to CSV",
							"sButtonClass": "btn btn-white btn-primary  btn-bold",
							"sButtonText": "<i class='fa fa-file-excel-o bigger-110 green'></i>"
						},
						
						{
							"sExtends": "pdf",
							"sToolTip": "Export to PDF",
							"sButtonClass": "btn btn-white btn-primary  btn-bold",
							"sButtonText": "<i class='fa fa-file-pdf-o bigger-110 red'></i>"
						},
						
						{
							"sExtends": "print",
							"sToolTip": "Print view",
							"sButtonClass": "btn btn-white btn-primary  btn-bold",
							"sButtonText": "<i class='fa fa-print bigger-110 grey'></i>",
							
							"sMessage": "<div class='navbar navbar-default'><div class='navbar-header pull-left'><a class='navbar-brand' href='#'><small>Optional Navbar &amp; Text</small></a></div></div>",
							
							"sInfo": "<h3 class='no-margin-top'>Print view</h3>\
									  <p>Please use your browser's print function to\
									  print this table.\
									  <br />Press <b>escape</b> when finished.</p>",
						}
			        ]
			    } );
				//we put a container before our table and append TableTools element to it
			    $(tableTools_obj.fnContainer()).appendTo($('.tableTools-container'));
				
				//also add tooltips to table tools buttons
				//addding tooltips directly to "A" buttons results in buttons disappearing (weired! don't know why!)
				//so we add tooltips to the "DIV" child after it becomes inserted
				//flash objects inside table tools buttons are inserted with some delay (100ms) (for some reason)
				setTimeout(function() {
					$(tableTools_obj.fnContainer()).find('a.DTTT_button').each(function() {
						var div = $(this).find('> div');
						if(div.length > 0) div.tooltip({container: 'body'});
						else $(this).tooltip({container: 'body'});
					});
				}, 200);
				
				
				
				//ColVis extension
				var colvis = new $.fn.dataTable.ColVis( oTable1, {
					"buttonText": "<i class='fa fa-search'></i>",
					"aiExclude": [0, 6],
					"bShowAll": true,
					//"bRestore": true,
					"sAlign": "right",
					"fnLabel": function(i, title, th) {
						return $(th).text();//remove icons, etc
					}
					
				}); 
				
				//style it
				$(colvis.button()).addClass('btn-group').find('button').addClass('btn btn-white btn-info btn-bold')
				
				//and append it to our table tools btn-group, also add tooltip
				$(colvis.button())
				.prependTo('.tableTools-container .btn-group')
				.attr('title', 'Show/hide columns').tooltip({container: 'body'});
				
				//and make the list, buttons and checkboxed Ace-like
				$(colvis.dom.collection)
				.addClass('dropdown-menu dropdown-light dropdown-caret dropdown-caret-right')
				.find('li').wrapInner('<a href="javascript:void(0)" />') //'A' tag is required for better styling
				.find('input[type=checkbox]').addClass('ace').next().addClass('lbl padding-8');
			
			
				
				/////////////////////////////////
				//table checkboxes
				$('th input[type=checkbox], td input[type=checkbox]').prop('checked', false);
				
				//select/deselect all rows according to table header checkbox
				$('#tpros > thead > tr > th input[type=checkbox]').eq(0).on('click', function(){
					var th_checked = this.checked;//checkbox inside "TH" table header
					
					$(this).closest('table').find('tbody > tr').each(function(){
						var row = this;
						if(th_checked) tableTools_obj.fnSelect(row);
						else tableTools_obj.fnDeselect(row);
					});
				});
				
				//select/deselect a row when the checkbox is checked/unchecked
				$('#tpros').on('click', 'td input[type=checkbox]' , function(){
					var row = $(this).closest('tr').get(0);
					if(!this.checked) tableTools_obj.fnSelect(row);
					else tableTools_obj.fnDeselect($(this).closest('tr').get(0));
				});
				
			
				
				
					$(document).on('click', '#tpros .dropdown-toggle', function(e) {
					e.stopImmediatePropagation();
					e.stopPropagation();
					e.preventDefault();
				});
				
				
				//And for the first simple table, which doesn't have TableTools or dataTables
				//select/deselect all rows according to table header checkbox
				var active_class = 'active';
				$('#simple-table > thead > tr > th input[type=checkbox]').eq(0).on('click', function(){
					var th_checked = this.checked;//checkbox inside "TH" table header
					
					$(this).closest('table').find('tbody > tr').each(function(){
						var row = this;
						if(th_checked) $(row).addClass(active_class).find('input[type=checkbox]').eq(0).prop('checked', true);
						else $(row).removeClass(active_class).find('input[type=checkbox]').eq(0).prop('checked', false);
					});
				});
				
				//select/deselect a row when the checkbox is checked/unchecked
				$('#simple-table').on('click', 'td input[type=checkbox]' , function(){
					var $row = $(this).closest('tr');
					if(this.checked) $row.addClass(active_class);
					else $row.removeClass(active_class);
				});
			
				
			
				/********************************/
				//add tooltip for small view action buttons in dropdown menu
				$('[data-rel="tooltip"]').tooltip({placement: tooltip_placement});
				
				//tooltip placement on right or left
				function tooltip_placement(context, source) {
					var $source = $(source);
					var $parent = $source.closest('table')
					var off1 = $parent.offset();
					var w1 = $parent.width();
			
					var off2 = $source.offset();
					//var w2 = $source.width();
			
					if( parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2) ) return 'right';
					return 'left';
				}
			
			})
		</script>
	 <script>
	     $(".loadi").fadeOut('fast');
	 </script>

