<?php

require_once("../class/class.conectar.php");


$Objcon = new Conectar();
$conex = $Objcon->con();

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

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

if(isset($_GET['tmov'])){
$fechainia=$_GET['fechaini'];
$fechafina=$_GET['fechafin'];
$idtplic=$_GET['tplicencia'];
$ugid = $_GET['ugid'];
$diaini=substr($fechainia, 0, 2);
$diafin=substr($fechafina, 0, 2);
$mesini=substr($fechainia, 3, 2);
$mesfin=substr($fechafina, 3, 2);
$annoini=substr($fechainia, 6, 4);
$annofin=substr($fechafina, 6, 4);
$fechaini =$annoini.'/'.$mesini.'/'.$diaini;
$fechafin =$annofin.'/'.$mesfin.'/'.$diafin;
$numdias=restaFechas($fechainia,$fechafina);
$numdias=$numdias+1;

if(($diaini<=$diafin && $mesini==$mesfin && $annoini==$annofin) || ($mesini<$mesfin && $annoini==$annofin) || ($annoini<$annofin)){
$sqlconsulta1="select * from tb_licencias where ug_id='$ugid' and '$fechaini' between lc_fechaini and lc_fechafin";
$sqlconsulta2="select * from tb_licencias where ug_id='$ugid' and '$fechafin' between lc_fechaini and lc_fechafin";
//echo $sqlconsulta1;
$resultsql1 = mysqli_query($conex,$sqlconsulta1);
$resultsql2 = mysqli_query($conex,$sqlconsulta2);
	if((mysqli_num_rows($resultsql1)==0) && (mysqli_num_rows($resultsql2)==0)){
	$sqlconsulta="select lc_id from tb_licencias where ug_id='$ugid' order by lc_id desc limit 1";
	$resultsql = mysqli_query($conex,$sqlconsulta);
	if(mysqli_num_rows($resultsql)==0){
	$numid = 1;
	}else{
	while ($row= mysqli_fetch_array($resultsql)){
	$numid = $row['lc_id']+1;
	}
	}
	$sqlinsertdm="insert into tb_licencias values('$numid','$idtplic','$ugid','$fechaini','$fechafin','$numdias')";
	//echo $sqlinsertdm;
	$resultdm = mysqli_query($conex,$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);

    preg_match( "([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})", $dFecIni, $aFecIni);
    preg_match( "([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($conex,$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>";

$cadenaserv="";
/*
//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($conex,$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($conex,$sqlp);
while ($rowp= mysqli_fetch_array($resultp)){
$nombre = $rowp['nombre'];
}

//tipo de licencias

$sqltlic = "select tlc_id as cod, tlc_desc as descripcion from tb_tplicencia";
//echo $sqlespecialidad;
$resulttlic = mysqli_query($conex,$sqltlic);
$salidatipolic="<select id='tplicencia' name='tplicencia'>";
$salidatipolic=$salidatipolic."<option value='0'>Seleccione</option>";
while ($rows= mysqli_fetch_array($resulttlic)){
$salidatipolic=$salidatipolic."<option value='".$rows['cod']."'";
/*
if ($rows['cod']==$ids){
$salidatipolic=$salidatipolic." selected ";
}
*/
$salidatipolic=$salidatipolic.">".$rows['descripcion']."</option>";
}
$salidatipolic=$salidatipolic."</select>";

?>
<html>
<head>
<title>LICENCIA 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 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;    }
}

function grabarLicencia(){
	var ugid = document.getElementById("ugid").value;
	var fechaini = document.getElementById("fechaini").value;
	var fechafin = document.getElementById("fechafin").value;
	var idtplic = document.getElementById("tplicencia").value;
	
	if(fechaini == ''){
		alert("Fecha Inicial no Ingresado");
		return false;
	}
	
	if(fechafin == ''){
		alert("Fecha Final no Ingresado");
		return false;
	}
	
	if(validaFechaDDMMAAAA(fechaini) == false){
		alert("Fecha No Esta Escrita Correctamente");
		return false;
	}
	
	if(validaFechaDDMMAAAA(fechafin) == false){
		alert("Fecha No Esta Escrita Correctamente");
		return false;
	}
	
	if(idtplic == 0){
		alert("Selecciones Tipo de Licencia");
		return false;
	}
	
	document.location= "licenciaper.php?fechaini="+fechaini+"&fechafin="+fechafin+"&ugid="+ugid+"&tplicencia="+idtplic+"&tmov=1";
	
}
</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 Fecha de la Licencia </font></legend>
	<br>
		<table align='center' class='FacetFormTABLE' width='450'>
		<tr><td class='FacetFieldCaptionTDT' colspan='4'><center>LICENCIA 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:300px'>PERSONAL </td><td colspan='3'><?php echo $nombre; ?></td></tr>
		<tr><td align='right' class='FacetFieldCaptionTD'>FECHA INICIAL</td>
		<td>
		<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>
		<td align='right' class='FacetFieldCaptionTD'>FECHA FINAL</td>
		<td>
		<input type='text' id='fechafin' name='fechafin' size='15' value='<?php //if(isset($_GET['ugid'])){ echo $fechaing;}?>'>
		<button id="f_rangeStart_trigger2"><img src="../img/b_calendar.png" ></button>
                <button id="f_clearRangeStart2" onclick="clearRangeStart2()">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: "fechafin",
                          dateFormat: "%d/%m/%Y",
                          trigger: "f_rangeStart_trigger2",
                          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 clearRangeStart2() {
                          document.getElementById("fechafin").value = "";
                          LEFT_CAL.args.min = null;
                          LEFT_CAL.redraw();
                  };
                </script>
		</td>
		</tr>
		<tr><td align='right' class='FacetFieldCaptionTD' style='width:300px'>TIPO DE LICENCIA </td><td colspan='3'><?php echo $salidatipolic; ?></td></tr>
		<tr><td align='center' colspan='4'><input type='button' id='pprog' style='width:150px' class='SalidaButton'  value='Grabar' onClick='grabarLicencia()'>
		<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>