<?php

include("../bd/sql_variables.php");

$con= mysqli_connect("$sql_host", "$sql_usuario", "$sql_pass") or die(header ("No Disponible Servidor de Base de Datos"));
mysqli_select_db($con,"$sql_db");

//$idj = $_GET['idj'];
//$ids = $_GET['ids'];

//$idj=$_GET['idj'];
//$ids=$_GET['ids'];
$ugid=$_GET['ugid'];

if(isset($_GET['hini']) && isset($_GET['hfin']) && isset($_GET['fechaini'])){
//echo $hinia."<br>";
$hinia=$_GET['hini'];
$hfina=$_GET['hfin'];
$ugid = $_GET['ugid'];
$fecha = $_GET['fechaini'];

$dia=substr($fecha, 0, 2);
$mes=substr($fecha, 3, 2);
$anno=substr($fecha, 6, 4);
$fechaini =$anno.'/'.$mes.'/'.$dia;
$difhrs = $hfina - $hinia;

$hinia_mod = str_replace(".0", ":00", $hinia);
$hinia_mod = str_replace(".5", ":30", $hinia);

$hfina_mod = str_replace(".0", ":00", $hfina);
$hfina_mod = str_replace(".5", ":30", $hfina);

//$numdias=restaFechas($fechainia,$fechafina);
//$numdias=$numdias+1;
//echo $difhrs;
$idtphrp=$_GET['tphrpermiso'];
if($difhrs>0){
$sqlconsulta1="select * from tb_horapermiso where ug_id='$ugid' and year(hrp_fecha) = '$anno' and month(hrp_fecha) = '$mes' and day(hrp_fecha) = '$dia' and (hrp_horaini < '$hinia_mod' and hrp_horafin > '$hinia_mod')";
$sqlconsulta2="select * from tb_horapermiso where ug_id='$ugid' and year(hrp_fecha) = '$anno' and month(hrp_fecha) = '$mes' and day(hrp_fecha) = '$dia' and (hrp_horaini < '$hfina_mod' and hrp_horafin > '$hfina_mod')";
echo $sqlconsulta1;
$resultsql1 = mysqli_query($con,$sqlconsulta1);
$resultsql2 = mysqli_query($con,$sqlconsulta2);
	if((mysqli_num_rows($resultsql1)==0) && (mysqli_num_rows($resultsql2)==0)){
	$sqlconsulta="select hrp_id from tb_horapermiso where ug_id='$ugid' order by hrp_id desc limit 1";
	$resultsql = mysqli_query($con,$sqlconsulta);
	if(mysqli_num_rows($resultsql)==0){
	$numid = 1;
	}else{
	while ($row= mysqli_fetch_array($resultsql)){
	$numid = $row['hrp_id']+1;
	}
	}
	$sqlinsertdm="insert into tb_horapermiso values('$numid','$ugid','$fechaini','$hinia_mod','$hfina_mod','$difhrs','$idtphrp')";
	echo $sqlinsertdm;
	$resultdm = mysqli_query($con,$sqlinsertdm);
	$error=0;
	echo "<script type='text/javascript'>window.opener.location.reload(); window.close();</script>";
	
	}else{
	$error = 1;
	}
}else{
$error=1;
}}

//restando fechas
function restaFechas($dFecIni, $dFecFin)
{
    $dFecIni = str_replace("-","",$dFecIni);
    $dFecIni = str_replace("/","",$dFecIni);
    $dFecFin = str_replace("-","",$dFecFin);
    $dFecFin = str_replace("/","",$dFecFin);

    ereg( "([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})", $dFecIni, $aFecIni);
    ereg( "([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})", $dFecFin, $aFecFin);

    $date1 = mktime(0,0,0,$aFecIni[2], $aFecIni[1], $aFecIni[3]);
    $date2 = mktime(0,0,0,$aFecFin[2], $aFecFin[1], $aFecFin[3]);

    return round(($date2 - $date1) / (60 * 60 * 24));
}



//seleccionando al combo jefatura
$sqljefatura = "select j_id as cod, j_desc as descripcion from tb_jefatura";
//echo $sqltpersonal;
$resultjefatura = mysqli_query($con,$sqljefatura);
$cadenaj="<select id='jefatura' name='jefatura' onChange='actualizaservicio()'>";
while ($rowj= mysqli_fetch_array($resultjefatura)){
$cadenaj=$cadenaj."<option value='".$rowj['cod']."'";
if ($rowj['cod']==$idj){
$cadenaj=$cadenaj." selected ";
}
$cadenaj=$cadenaj.">".$rowj['descripcion']."</option>";
}
$cadenaj=$cadenaj."</select>";

//seleccionando al comnbo servicio
$sqlservicio = "select s_id as cod, s_desc as descripcion from tb_servicio where j_id='$idj'";
//echo $sqlespecialidad;
$resultservicio = mysqli_query($con,$sqlservicio);
$cadenaserv="<select id='servicio' name='servicio'>";
while ($rows= mysqli_fetch_array($resultservicio)){
$cadenaserv=$cadenaserv."<option value='".$rows['cod']."'";
if ($rows['cod']==$ids){
$cadenaserv=$cadenaserv." selected ";
}
$cadenaserv=$cadenaserv.">".$rows['descripcion']."</option>";
}
$cadenaserv=$cadenaserv."</select>";

//seleccionando al personal
$sqlp = "select concat(ua_apepat,' ',ua_apemat,' ',ua_nom) as nombre from tb_usuasist where ug_id='$ugid'";
//echo $sqltc;
$resultp = mysqli_query($con,$sqlp);
while ($rowp= mysqli_fetch_array($resultp)){
$nombre = $rowp['nombre'];
}

//tipo de licencias

$sqltlic = "select thp_id as cod, thp_desc as descripcion from tb_tphoraper";
//echo $sqlespecialidad;
$resulttlic = mysqli_query($con,$sqltlic);
$salidatipoper="<select id='tphrpermiso' name='tphrpermiso'>";
$salidatipoper=$salidatipoper."<option value='0'>Seleccione</option>";
while ($rows= mysqli_fetch_array($resulttlic)){
$salidatipoper=$salidatipoper."<option value='".$rows['cod']."'";
if ($rows['cod']==$ids){
$salidatipoper=$salidatipoper." selected ";
}
$salidatipoper=$salidatipoper.">".$rows['descripcion']."</option>";
}
$salidatipoper=$salidatipoper."</select>";

?>
<html>
<head>
<title>HORAS PERMISO DEL PERSONAL ASISTENCIAL</title>
<link rel="stylesheet" type="text/css" href="styles/Style.css">

<script language="JavaScript" type="text/javascript" src="ajax.js"></script>
<link rel="stylesheet" type="text/css" href="styles/Style.css">
<link type="text/css" rel="stylesheet" href="src/css/jscal2.css" />
    <link type="text/css" rel="stylesheet" href="src/css/border-radius.css" />
    <!-- <link type="text/css" rel="stylesheet" href="src/css/reduce-spacing.css" /> -->

    <link id="skin-win2k" title="Win 2K" type="text/css" rel="alternate stylesheet" href="src/css/win2k/win2k.css" />
    <link id="skin-steel" title="Steel" type="text/css" rel="alternate stylesheet" href="src/css/steel/steel.css" />
    <link id="skin-gold" title="Gold" type="text/css" rel="alternate stylesheet" href="src/css/gold/gold.css" />
    <link id="skin-matrix" title="Matrix" type="text/css" rel="alternate stylesheet" href="src/css/matrix/matrix.css" />

    <link id="skinhelper-compact" type="text/css" rel="alternate stylesheet" href="src/css/reduce-spacing.css" />

    <script src="src/js/jscal2.js"></script>
	<script src="src/js/lang/en.js"></script>
    <!-- you actually only need to load one of these; we put them all here for demo purposes -->
     <script src="src/js/lang/es.js"></script>
    
    <link type="text/css" rel="stylesheet" href="demopage.css" />

<script type="text/javascript"> 

function ventanaClose(){ 
   //alert("hola mundo");
    window.close();
} 

function grabarPermiso(){
	//alert("holitas");
	var ugid = document.getElementById("ugid").value;
	var fechaini = document.getElementById("fechaini").value;
	var horaini = document.getElementById("hini").value;
	var horafin = document.getElementById("hfin").value;
	var idtpper = document.getElementById("tphrpermiso").value;
	
	var horaini = parseFloat(horaini)+1-1;
	var horafin = parseFloat(horafin)+1-1;
	
	if(fechaini == ''){
		alert("Fecha Inicial no Ingresado");
		return false;
	}
	
	if(horaini > horafin){
		alert("Hora Inicial mayor que Hora Final");
		return false;
	}
	
	if(horaini == horafin){
		alert("Hora Inicial es Igual Hora Final");
		return false;
	}
	
	if(validaFechaDDMMAAAA(fechaini) == false){
		alert("Fecha No Esta Escrita Correctamente");
		return false;
	}
	
	if(idtpper == 0){
		alert("Selecciones Tipo de Permiso");
		return false;
	}
	
	document.location= "hrpermiso.php?fechaini="+fechaini+"&hini="+horaini+"&hfin="+horafin+"&ugid="+ugid+"&tphrpermiso="+idtpper+"&tmov=1";
	
}

function validaFechaDDMMAAAA(fecha){    
var dtCh= "/";    
var minYear=1900;
var maxYear=2100;
        function isInteger(s){
        var i;     
		for (i = 0; i < s.length; i++){ 
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
        }
        return true;
		}
		function stripCharsInBag(s, bag){
        var i;
        var returnString = ""; 
		for (i = 0; i < s.length; i++){ 
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;        }
        return returnString;    }
		function daysInFebruary (year){
        return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );    }
		function DaysArray(n) {
        for (var i = 1; i <= n; i++) { 
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}        
		} 
		return this
		}    
		function isDate(dtStr){
        var daysInMonth = DaysArray(12) 
		var pos1=dtStr.indexOf(dtCh) 
		var pos2=dtStr.indexOf(dtCh,pos1+1) 
		var strDay=dtStr.substring(0,pos1)
        var strMonth=dtStr.substring(pos1+1,pos2)
        var strYear=dtStr.substring(pos2+1)
        strYr=strYear
        if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)        
		if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)        
		for (var i = 1; i <= 3; i++) {            
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
        }        
		month=parseInt(strMonth)        
		day=parseInt(strDay)        
		year=parseInt(strYr)        
		if (pos1==-1 || pos2==-1){            
		return false        }        
		if (strMonth.length<1 || month<1 || month>12){            
		return false        }       
		if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
		{            return false        }        
		if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){ 
		return false        }        
		if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false)
		{            return false        }        
		return true    }    
		if(isDate(fecha))
		{        return true;    }
		else{        return false;    }
}

</script> 
</head>
<body>
<table align='center'>
<tr><td>
<div id='transfpersonal'>
<?php
echo "<input type='hidden' id='ugid' name='ugid' value='".$ugid."'>";
?>
<fieldset>
	<legend align='left'><font color='blue' size='15'>Escriba la Hora de Permiso </font></legend>
	<br>
		<table align='center' class='FacetFormTABLE' width='400'>
		<tr><td class='FacetFieldCaptionTDT' colspan='4'><center>HORA PERMISO DEL PERSONAL ASISTENCIAL</center></td></tr>
		<tr><td colspan='4'><center><?php if(isset($error)){ if($error=='1'){ echo "REVISE LOS DATOS, PERSONAL NO REGISTRADO";}elseif($error=='0'){ echo "PERSONAL REGISTRADO";}}?></center></td></tr>
		<tr><td align='right' class='FacetFieldCaptionTD' style='width:150px'>PERSONAL </td><td colspan='3'><?php echo $nombre; ?></td></tr>
		<tr><td align='right' class='FacetFieldCaptionTD' style='width:150px'>DIA </td>
		<td colspan='3' align='left'>
		<input type='text' id='fechaini' name='fechaini' size='15' value='<?php //if(isset($_GET['ugid'])){ echo $fechaing;}?>'>
		<button id="f_rangeStart_trigger1"><img src="../img/b_calendar.png" ></button>
                <button id="f_clearRangeStart1" onclick="clearRangeStart1()">clear</button>
                <script type="text/javascript">
				  var LEFT_CAL = Calendar.setup({
                    //cont: "cont",
                    //weekNumbers: true,
                    //selectionType: Calendar.SEL_MULTIPLE,
                    //showTime: 12
                    // titleFormat: "%B %Y"
					})
                  new Calendar({
                          inputField: "fechaini",
                          dateFormat: "%d/%m/%Y",
                          trigger: "f_rangeStart_trigger1",
                          bottomBar: false,
                          onSelect: function() {
                                  var date = Calendar.intToDate(this.selection.get());
								  LEFT_CAL.setLanguage('es');
                                  LEFT_CAL.args.min = date;
                                  LEFT_CAL.redraw();
                                  this.hide();
                          }
                  });
                  function clearRangeStart1() {
                          document.getElementById("fechaini").value = "";
                          LEFT_CAL.args.min = null;
                          LEFT_CAL.redraw();
                  };
                </script>
		</td>
		</tr>
		<tr><td align='right' class='FacetFieldCaptionTD'>HORA INICIAL</td>
		<td>
		<select id='hini' name='hini' style='width:12em;'>
		<?php for($ai=0;$ai<=24;$ai++){ ?>
		<option value='<?php echo $ai.".0";?>'><?php echo $ai.":00";?></option>
		<?php if($ai<24){ ?>
		<option value='<?php echo $ai.".5";?>'><?php echo $ai.":30";?></option>
		<?php } } ?>
		</select>
		</td>
		<td align='right' class='FacetFieldCaptionTD'>HORA FINAL</td>
		<td>
		<select id='hfin' name='hfin' style='width:12em;'>
		<?php for($ai=0;$ai<=24;$ai++){ ?>
		<option value='<?php echo $ai.".0";?>'><?php echo $ai.":00";?></option>
		<?php if($ai<24){ ?>
		<option value='<?php echo $ai.".5";?>'><?php echo $ai.":30";?></option>
		<?php } } ?>
		</select>
		</td>
		</tr>
		<tr><td align='right' class='FacetFieldCaptionTD' style='width:300px'>TIPO DE PERMISO </td><td colspan='3'><?php echo $salidatipoper; ?></td></tr>
		<tr><td align='center' colspan='4'><input type='button' id='pprog' style='width:150px' class='SalidaButton'  value='Grabar' onClick='grabarPermiso();'>
		<button type='button' id='pprog' style='width:150px' class='SalidaButton' onClick='ventanaClose();' >Cancelar</button>
		</td></tr></table>
	  <br>
	</fieldset>
</div>
</td><tr>
</table>
</body>
</html>