<?php session_start();
//RESTRICCIÓN DE ACCESO A TRABAJADOR (ACCESO INDIVIDUAL) 
if (isset($_SESSION['tipousuario'])) {
	if ($_SESSION['tipousuario'] == '1')
		header('location:menu_personal.php');
}
if (trim($_SESSION['nombre_validar']) == '') header('location:index.php');
include("fphp.php");
$enlace = cargar_conexion();
$accion = $_REQUEST["accion"];
$codigo = $_REQUEST["codigo"];

$diario = "zd_" . trim($_SESSION['usuario_validar']);
$consulta = mysqli_query($enlace, "create table if not exists `" . $diario . "` (
			  `cedula` varchar(8) NOT NULL,
			  `nombres` varchar(50) NOT NULL,
			  `turno` varchar(60) NOT NULL,
			  `fecha` date NOT NULL,
			  `h1` int(11) NOT NULL,
			  `m1` int(11) NOT NULL,
			  `h2` int(11) NOT NULL,
			  `m2` int(11) NOT NULL,
			  `h3` int(11) NOT NULL,
			  `m3` int(11) NOT NULL,
			  `h4` int(11) NOT NULL,
			  `m4` int(11) NOT NULL,
			  `h5` int(11) NOT NULL,
			  `m5` int(11) NOT NULL,
			  `h6` int(11) NOT NULL,
			  `m6` int(11) NOT NULL,
			  `mensaje` varchar(100) NOT NULL,
			  `departamento` varchar(100) NOT NULL
			) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
$consulta = mysqli_query($enlace, "delete from `" . $diario . "`");

$consulta = mysqli_query($enlace, "select * from empresa where id='" . $_SESSION['id_validar'] . "' ");
if (mysqli_num_rows($consulta) != 0) {
	$row = mysqli_fetch_array($consulta);
	$_POST['pie'] = $row['pie'];
	$_POST['encabeza'] = $row['encabeza'];
	$_POST['empresas'] = $row['nombre'];
	$_POST['ciudad'] = $row['ciudad'];
	$_POST['representante'] = $row['representante'];
	$_POST['cedular'] = $row['cedula'];
}
$_POST['usuario'] = $_SESSION['nombre_validar'];

////////////////////////////////////////////////////////////////////// CALCULOS GENERALES	
$fecdes = substr($_POST['fec1'], 0, 2) . "-" . substr($_POST['fec1'], 2, 2) . "-" . substr($_POST['fec1'], 4, 4);
$fechas = substr($_POST['fec2'], 0, 2) . "-" . substr($_POST['fec2'], 2, 2) . "-" . substr($_POST['fec2'], 4, 4);

$fx = sumar_dias($fechas, 1);
$fhasta = substr($fx, 6, 4) . "-" . substr($fx, 3, 2) . "-" . substr($fx, 0, 2);
$fdesde = substr($_POST['fec1'], 4, 4) . "-" . substr($_POST['fec1'], 2, 2) . "-" . substr($_POST['fec1'], 0, 2);

$_POST['subtitulo'] = "(" . $fecdes . " / " . $fechas . ")";

$query = " and personal.nomina='" . substr($_POST['nomina'], 0, 3) . "' " . ($_POST['statusx'] == '' ? " and (personal.status='A' or personal.status='C') " : " and personal.status='" . $_POST['statusx'] . "' ");
if ($_POST['gerencia'] != "") $query .= "and personal.gerencia='" . substr($_POST['gerencia'], 0, 4) . "' ";
if ($_POST['division'] != "") $query .= "and personal.division='" . substr($_POST['division'], 0, 4) . "' ";
if ($_POST['departamento'] != "") $query .= "and personal.departamento='" . substr($_POST['departamento'], 0, 4) . "' ";

$query1 = "select concat(personal.nombres,' ',personal.nombres1,' ', personal.apellidos,' ', personal.apellidos1) as det, personal.departamento as dep,personal.codigo as cod from ";
$query1 .= "personal where id='" . $_SESSION['id_validar'] . "' $query order by personal.codigo";
$resul1 = mysqli_query($enlace, $query1) or die($query1 . ' > ' . mysqli_error($enlace));
while ($row1 = mysqli_fetch_array($resul1)) {
	$ced = trim($row1['cod']);
	$nom = trim($row1['det']);
	$dpto = trim($row1['dep']);
	$query2 = "select * from chequeo where id='" . $_SESSION['id_validar'] . "' and codigo='" . $ced . "' and chequeo.fecha >= '" . $fdesde . "' and chequeo.fecha <= '" . $fhasta . "' order by fecha";
	$resul2 = mysqli_query($enlace, $query2) or die($query2 . ' > ' . mysqli_error($enlace));
	while ($row2 = mysqli_fetch_array($resul2)) {
		$fec = substr($row2['fecha'], 0, 10);
		$h = substr($row2['fecha'], 11, 2);
		$m = substr($row2['fecha'], 14, 2);
		$men = $row2['mensaje'];
		$resul3 = mysqli_query($enlace, "select * from $diario where cedula = '$ced' and fecha = '$fec'") or die(' select diario $query2> ' . mysqli_error($enlace));
		$num = mysqli_num_rows($resul3);
		if ($num == 0) {
			$columna = 1;
			$resul3 = mysqli_query($enlace, "insert into $diario (mensaje, cedula,nombres,fecha,h1,m1,departamento) values ('$men','$ced','$nom','$fec',$h,$m,'$dpto')") or die("insert into diario > " . mysqli_error($enlace));
		} else {
			$columna++;
			$query4 = "";
			switch ($columna) {
				case 2:
					$query4 = "update $diario set h2 = '$h', m2='$m' where  cedula = '$ced' and fecha = '$fec'";
					break;
				case 3:
					$query4 = "update $diario set h3 = '$h', m3='$m' where  cedula = '$ced' and fecha = '$fec'";
					break;
				case 4:
					$query4 = "update $diario set h4 = '$h', m4='$m' where  cedula = '$ced' and fecha = '$fec'";
					break;
				case 5:
					$query4 = "update $diario set h5 = '$h', m5='$m' where  cedula = '$ced' and fecha = '$fec'";
					break;
				case 6:
					$query4 = "update $diario set h6 = '$h', m6='$m' where  cedula = '$ced' and fecha = '$fec'";
					break;
			}
			if ($query4 != "") $resul4 = mysqli_query($enlace, $query4) or die($query4 . ' > ' . mysqli_error($enlace));
		} // fin $num==0
	} // fin de while $row2
} // fin de while $row1


////////////////////////////////////////////////////////////////////// Cargar FECHA NO CHEQUEADAS
$query1 = "select concat(personal.nombres,' ',personal.nombres1,' ', personal.apellidos,' ', personal.apellidos1) as det, personal.departamento as dep,personal.codigo as cod from personal where id='" . $_SESSION['id_validar'] . "' $query ";
$resul1 = mysqli_query($enlace, $query1) or die($query1 . ' > ' . mysqli_error($enlace));
while ($row1 = mysqli_fetch_array($resul1)) {
	$nom = trim($row1['det']);
	$h = 0;
	$m = 0;
	$ced = $row1['cod'];
	$dpto = $row1['dep'];
	$desde = $fdesde;
	$final = $fhasta;
	$finalizar = 1;
	while ($desde < $final) {
		$query2 = "select cedula from $diario where substring(fecha,1,10) = '" . $desde . "' and cedula='" . $ced . "'";
		$resul2 = mysqli_query($enlace, $query2) or die($query2 . ' > ' . mysqli_error($enlace));
		if (mysqli_num_rows($resul2) == 0) {
			$resul3 = mysqli_query($enlace, "insert into $diario (cedula,nombres,fecha,h1,m1) values ('$ced','$nom','" . $desde . "',$h,$m)") or die("insert into diario > " . mysqli_error($enlace));
		}
		$dia = substr($desde, 8, 2);
		$mes = substr($desde, 5, 2);
		$ano = substr($desde, 0, 4);
		$desde = date('Y-m-d', mktime(0, 0, 0, $mes, $dia + 1, $ano));
	}
}

////////////////////////////////////////////////////////////////////// REPORTE GENERAL	
require('fpdf.php');
class PDF extends FPDF
{

	protected $logo_validar;
	protected $nempresa;
	protected $usuario;
	protected $subtitulo;
	protected $gerencia;
	protected $division;
	protected $departamento;
	protected $pie;


	function set_logo_validar($logo_validar)
	{
		$this->logo_validar = $logo_validar;
	}

	function set_nempresa($nempresa)
	{
		$this->nempresa = $nempresa;
	}

	function set_usuario($usuario)
	{
		$this->usuario = $usuario;
	}

	function set_subtitulo($subtitulo)
	{
		$this->subtitulo = $subtitulo;
	}

	function set_gerencia($gerencia)
	{
		$this->gerencia = $gerencia;
	}

	function set_division($division)
	{
		$this->division = $division;
	}

	function set_departamento($departamento)
	{
		$this->departamento = $departamento;
	}

	function set_pie($pie)
	{
		$this->pie = $pie;
	}

	function Header()
	{
		$this->Image($this->logo_validar, 10, 10, 30, 25);
		$this->SetFont('arial', '', 12);
		$this->Ln(4);
		$this->Cell(0, 0, trim($this->nempresa), 0, 1, 'C');
		$this->Ln(5);
		$this->SetFont('arial', '', 10);
		$this->Cell(0, 0, 'Fecha: ' . hoy(), 0, 1, 'R');
		$this->Ln(5);
		$this->Cell(0, 0, 'Usuario: ' . $this->usuario, 0, 1, 'R');
		$this->Ln(5);
		$this->SetFont('arial', 'B', 12);
		$this->Cell(0, 0, 'Chequeo del Personal', 0, 1, 'C');
		$this->Ln(5);
		$this->Cell(0, 0, $this->subtitulo, 0, 1, 'C');
		$this->Ln(5);
		if ($this->gerencia != "") {
			$this->Cell(0, 0, 'Gerencia: ' . $this->gerencia, 0, 1, 'L');
			$this->Ln(5);
		}
		if ($this->division != "") {
			$this->Cell(0, 0, 'División: ' . $this->division, 0, 1, 'L');
			$this->Ln(5);
		}
		if ($this->departamento != "") {
			$this->Cell(0, 0, 'Departamento: ' . $this->departamento, 0, 1, 'L');
			$this->Ln(5);
		}
		$header = array('Item', 'Cedula', 'Nombres y Apellidos', 'Fecha', 'Chequeo', 'Hor/Trab', 'Tarde?', 'Observaciones');
		$this->SetFillColor(255, 0, 0);
		$this->SetTextColor(255);
		$this->SetDrawColor(128, 0, 0);
		$this->SetLineWidth(.3);
		$this->SetFont('', '');
		//Cabecera
		$this->SetFont('arial', 'B', 8);
		$w = array(10, 15, 80, 20, 50, 20, 10, 55);
		for ($i = 0; $i < count($header); $i++)
			$this->Cell($w[$i], 4, $header[$i], 1, 0, 'C', 1);
		$this->Ln();
		//Restauraci�n de colores y fuentes
		$this->SetFillColor(224, 235, 255);
		$this->SetTextColor(0);
		$this->SetFont('');
	}
	//Pie de Página ////////////////////////
	function Footer()
	{
		$this->SetY(-20);
		$this->Cell(0, 0, '', 1, 1, 'C');
		$this->SetFont('Times', 'I', 8);
		$this->ln(2);
		$this->Cell(0, 0, $this->pie, 0, 1, 'C');
		$this->Cell(0, 10, 'Página ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
	}
}
//Cuerpo ///////////////////////////////
$pdf = new PDF($orientacion = 'L', $unit = 'mm', $format = 'letter');
$pdf->set_logo_validar($_SESSION['logo_validar']);
$pdf->set_nempresa($_POST['nempresa']);
$pdf->set_usuario($_POST['usuario']);
$pdf->set_subtitulo($_POST['subtitulo']);
$pdf->set_gerencia($_POST['gerencia']);
$pdf->set_division($_POST['division']);
$pdf->set_departamento($_POST['departamento']);
$pdf->set_pie($_POST['pie']);
$pdf->AddPage();
$pdf->AliasNbPages();
$pdf->SetFont('Arial', '', 8);
$pdf->SetFillColor(224, 235, 255);
$pdf->SetTextColor(0);
$consulta = mysqli_query($enlace, "select * from $diario order by cedula, fecha");
$linea = 0;
$color = 0;
$bandera = 0;
$w = array(10, 15, 80, 30, 50, 75);

while ($row = mysqli_fetch_array($consulta)) {
	$linea++;
	$llegotarde = 0;
	$ht = 0;
	$mt = 0;
	$hd = 0;
	$md = 0;
	if ($row['h1'] * 60 + $row['m1'] > 550) $llegotarde = 1;

	//============================================= buscar departamento 
	$consulta3 = "select tablas.detalle from tablas,personal where tablas.tabla=ucase('CARGO') and tablas.codigo=personal.cargo and personal.codigo='" . $row['cedula'] . "' and tablas.id='" . $_SESSION['id_validar'] . "' ";
	$resultado3 = mysqli_query($enlace, $consulta3) or die($consulta3 . mysqli_error($enlace));
	$row3 = mysqli_fetch_array($resultado3);
	$dep = $row3['detalle'];
	mysqli_free_result($resultado3);

	//============================================= buscar semana 
	$dia1 = substr($row['fecha'], 8, 2);
	$mes1 = substr($row['fecha'], 5, 2);
	$ano1 = substr($row['fecha'], 0, 4);
	$semana = dia_semana($dia1, $mes1, $ano1);
	if ($semana == 1) $sem = 'Dom';
	if ($semana == 2) $sem = 'Lun';
	if ($semana == 3) $sem = 'Mar';
	if ($semana == 4) $sem = 'Mie';
	if ($semana == 5) $sem = 'Jue';
	if ($semana == 6) $sem = 'Vie';
	if ($semana == 7) $sem = 'Sab';

	if ($row['h3'] + $row['m3'] == 0) {
		if ($row['h2'] + $row['m2'] != 0) {
			if ($row['m2'] - $row['m1'] >= 0) {
				$ht = $row['h2'] - $row['h1'];
				$mt = $row['m2'] - $row['m1'];
			} else {
				$ht = $row['h2'] - $row['h1'] - 1;
				$mt = $row['m2'] - $row['m1'] + 60;
			}
		}
	} else {
		if ($row['h4'] + $row['m4'] == 0) {
			if ($row['m2'] - $row['m1'] >= 0) {
				$ht = $row['h2'] - $row['h1'];
				$mt = $row['m2'] - $row['m1'];
			} else {
				$ht = $row['h2'] - $row['h1'] - 1;
				$mt = $row['m2'] - $row['m1'] + 60;
			}
			if ($row['m3'] - $row['m2'] >= 0) {
				$hd = $row['h3'] - $row['h2'];
				$md = $row['m3'] - $row['m2'];
			} else {
				$hd = $row['h3'] - $row['h2'] - 1;
				$md = $row['m3'] - $row['m2'] + 60;
			}
		} else {
			if ($row['m3'] - $row['m2'] >= 0) {
				$hd = $row['h3'] - $row['h2'];
				$md = $row['m3'] - $row['m2'];
			} else {
				$hd = $row['h3'] - $row['h2'] - 1;
				$md = $row['m3'] - $row['m2'] + 60;
			}
			if ($row['m2'] - $row['m1'] >= 0) {
				$ht = $row['h2'] - $row['h1'];
				$mt = $row['m2'] - $row['m1'];
			} else {
				$ht = $row['h2'] - $row['h1'] - 1;
				$mt = $row['m2'] - $row['m1'] + 60;
			}
			if ($row['m4'] - $row['m3'] >= 0) {
				$ht1 = $row['h4'] - $row['h3'];
				$mt1 = $row['m4'] - $row['m3'];
			} else {
				$ht1 = $row['h4'] - $row['h3'] - 1;
				$mt1 = $row['m4'] - $row['m3'] + 60;
			}
			if ($mt + $mt1 < 60) {
				$ht = $ht + $ht1;
				$mt = $mt + $mt1;
			} else {
				$ht = $ht + $ht1 + 1;
				$mt = 60 - ($mt + $mt1);
			}
		}
	}

	$mostrar  = str_repeat("0", 2 - strlen(($row['h1'] > 12 ? $row['h1'] - 12 : $row['h1']))) . ($row['h1'] > 12 ? ($row['h1'] - 12) : $row['h1']) . ':';
	$mostrar .= str_repeat("0", 2 - strlen($row['m1'])) . $row['m1'] . ($row['h1'] > 12 ? "p" : "a") . ' - ';
	$mostrar .= str_repeat("0", 2 - strlen(($row['h2'] > 12 ? $row['h2'] - 12 : $row['h2']))) . ($row['h2'] > 12 ? ($row['h2'] - 12) : $row['h2']) . ':';
	$mostrar .= str_repeat("0", 2 - strlen($row['m2'])) . $row['m2'] . ($row['h2'] > 12 ? "p" : "a") . ' / ';
	$mostrar .= str_repeat("0", 2 - strlen(($row['h3'] > 12 ? $row['h3'] - 12 : $row['h3']))) . ($row['h3'] > 12 ? ($row['h3'] - 12) : $row['h3']) . ':';
	$mostrar .= str_repeat("0", 2 - strlen($row['m3'])) . $row['m3'] . ($row['h3'] > 12 ? "p" : "a") . ' - ';
	$mostrar .= str_repeat("0", 2 - strlen(($row['h4'] > 12 ? $row['h4'] - 12 : $row['h4']))) . ($row['h4'] > 12 ? ($row['h4'] - 12) : $row['h4']) . ':';
	$mostrar .= str_repeat("0", 2 - strlen($row['m4'])) . $row['m4'] . ($row['h4'] > 12 ? "p" : "a");

	if (trim($mostrar) == '00:04a - 00:00a / 00:00a - 00:00a' || trim($mostrar) == '00:00a - 00:00a / 00:00a - 00:00a') $mostrar = 'S/Chequeo';

	if ($bandera == 0) {
		$bandera = 1;
		$salto = $row['cedula'];
	}
	if ($salto != $row['cedula'] || $linea == 1) {
		$salto = $row['cedula'];
		$pdf->Cell(260, 0, '', 1, 1, 'C', 0);
		$pdf->cell(10, 5, $linea, 0, 0, 'C', $color);
		$pdf->cell(15, 5, $row['cedula'], 0, 0, '', $color);
		$pdf->SetFont('Arial', '', 6);
		$pdf->cell(80, 5, trim($row['nombres']) . " - " . $dep, 0, 0, '', $color);
		$pdf->SetFont('Arial', '', 8);
		$pdf->cell(20, 5, ($sem . " " . $row['fecha']), 0, 0, 'R', $color);
		$pdf->cell(50, 5, $mostrar, 0, 0, '', $color);
		$pdf->cell(20, 5, ($ht == '00' ? '' : $ht . ":" . $mt), 0, 0, 'C', $color);
		//$pdf->cell(10,5,$hd.":".$md,0,0,'C',$color);
		$pdf->cell(10, 5, ($llegotarde ? "X" : ""), 0, 0, 'C', $color);
		$pdf->cell(55, 5, $row['mensaje'], 0, 1, '', $color);
		$pdf->ln(1);
		$color = !$color;
	} else {
		$linea--;
		$salto = $row['cedula'];
		$pdf->cell(125, 5, ($sem . " " . $row['fecha']), 0, 0, 'R', $color);
		$pdf->cell(50, 5, $mostrar, 0, 0, '', $color);
		$pdf->cell(20, 5, ($ht == '00' ? '--' : $ht . ":" . $mt), 0, 0, 'C', $color);
		//$pdf->cell(10,5,$hd.":".$md,0,0,'C',$color);
		$pdf->cell(10, 5, ($llegotarde ? "X" : ""), 0, 0, 'C', $color);
		$pdf->cell(55, 5, $row['mensaje'], 0, 1, '', $color);
		$pdf->ln(1);
		$color = !$color;
	}
}
$pdf->Cell(260, 0, '', 1, 1, 'C');
$pdf->ln(1);
$pdf->Cell(260, 0, '', 1, 1, 'C');
$pdf->Output();
