<?php
session_start();
include_once("../scripts/connect.php");
include("../scripts/session.php");
//Validar Session

    $sesion=new Sesion("","","");/*Se crea un objeto nuevo con el privilegio necesario para la pag. actual*/

    if(!$sesion->isValida("1")){ /*Sesion invalida*/
	header("Location: ../login.php?err=NoSesion");
    }/*no hay sesion*/

    else{
       $dato=explode("|",$_SESSION['usuario']);
       $sesion->setDatos($dato[0],$dato[1],$dato[2]);
    }
    //fin validar session


  $conexion=conecta_default();
  
  function copiahisto()
  {
  	$sell = "SELECT id_inver, primeraG, segundaG, terceraG, cuartaG, quintaG FROM calificados JOIN inversionista ON inversionista.id_inver = calificados.inversionista_id_inver WHERE inversionista.califico='SI' ORDER BY id_inver";
    $conss = mysqli_query($conexion, $sell) or die('Err0: '. mysqli_error($conexion));
    if (mysqli_affected_rows($conexion))
    {
      $fech = date("Y-m-d");
      while($ress = mysqli_fetch_object($conss))
      {
      	$idin = $ress->id_inver;
      	$cg1 = $ress->primeraG;
  	  	$cg2 = $ress->segundaG;
      	$cg3 = $ress->terceraG;
     	$cg4 = $ress->cuartaG;
      	$cg5 = $ress->quintaG;
      	$qry = "INSERT INTO historial_calif (idhistcal, inversionista_id_inver, primeraG, segundaG, terceraG, cuartaG, quintaG, fecha) VALUES ('','$idin','$cg1','$cg2','$cg3','$cg4','$cg5','$fech')";
  	    $exqu = mysqli_query($conexion, $qry);
      }
     
    }
  }
  
  function repartiregs()
  {
    $sel = "SELECT id_inver, nombre, appat, apmat, primeraG, segundaG, terceraG, cuartaG, quintaG, (primeraG*15.20) as priG, (segundaG*15.20) as segG, (terceraG*15.20) as terG, (cuartaG*15.20) as cuaG, (quintaG*15.20) as quiG, ((primeraG+segundaG+terceraG+cuartaG+quintaG)*15.20) as total FROM inversionista JOIN calificados ON inversionista.id_inver = calificados.inversionista_id_inver WHERE inversionista.califico='SI' AND ((primeraG+segundaG+terceraG+cuartaG+quintaG)*15.20) > '0' ORDER BY id_inver";
    $cons = mysqli_query($conexion, $sel) or die('Err0: '. mysqli_error($conexion));
    if (mysqli_affected_rows($conexion))
    {  
    $totregs = 0;
    $con = 1;
    $fdeins = date('Y-m-d');
    $div = explode("-",$fdeins);
    $fecini = $div[0]."-".$div[1]."-"."01";
    $fecfin = $div[0]."-".$div[1]."-"."31";
    
    switch($div[1])
    {
     	case '01': $mes = "Enero"; break;
     	case '02': $mes = "Febrero"; break;
     	case '03': $mes = "Marzo"; break;
     	case '04': $mes = "Abril"; break;
     	case '05': $mes = "Mayo"; break;
     	case '06': $mes = "Junio"; break;
     	case '07': $mes = "Julio"; break;
     	case '08': $mes = "Agosto"; break;
     	case '09': $mes = "Septiembre"; break;
     	case '10': $mes = "Octubre"; break;
     	case '11': $mes = "Noviembre"; break;
     	case '12': $mes = "Diciembre"; break;
     }
    $anio = $div[0];
    
    echo "<center><label style='color:#5C3C12; font-size:28px; font-weight:bold'>Regal&iacute;as del mes de $mes de $anio.</label></center>";          
    echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Las regal&iacute;as se han repartido exitosamente. Se muestran a continuaci&oacute;n los detalles: <br /><br />";
    echo "<br /><table border='1' align='center' width='700'>";    
    echo "<tr align='center'> <td>No. <td>Nombre <td>G1 <td>G2 <td>G3 <td>G4 <td>G5 <td>Total <td>Regs. a Recibir</tr>";
      
    
    while($res = mysqli_fetch_object($cons))
    {
  	  $idin = $res->id_inver;
  	  $g1 = $res->priG;
      $g2 = $res->segG;
      $g3 = $res->terG;
      $g4 = $res->cuaG;
      $g5 = $res->quiG;
  	  $regals = $res->total;
      
  	  if ($res->primeraG > 0)
  	  {
  	    if($res->primeraG < 3)
  	  	 $regarec = $g1;
  	  	else{
  	  		if($res->primeraG < 6)
  	  		 $regarec = $g1 + $g2;
  	  		else{
  	  			if($res->primeraG < 9)
  	  		     $regarec = $g1 + $g2 + $g3;
  	  		    else{
  	  		      if($res->primeraG < 10)
  	  		        $regarec = $g1 + $g2 + $g3 + $g4;
  	  		      else 
  	  		        $regarec = $g1 + $g2 + $g3 + $g4 + $g5;
  	  		        }
  	  		     }
  	  	    }  		
  	   }
  	  	   
  	  $g1 = number_format($g1,2);
  	  $g2 = number_format($g2,2);
  	  $g3 = number_format($g3,2);
  	  $g4 = number_format($g4,2);
  	  $g5 = number_format($g5,2);
  	  	  
  	  $regarec = number_format($regarec,2);
  	  if ($regarec > 0) 
  	  {
  	  	$regals = number_format($regals,2);
  	  	echo "<tr align='right'> <td>$con <td align='left'>$res->nombre $res->appat $res->apmat <td>$g1 <td>$g2 <td>$g3 <td>$g4 <td>$g5 <td>$regals <td style='font-weight: bold'>$$regarec </tr>";     
  	    $con++;
  	    	    
  	    $qry = "INSERT INTO regalias (idregalias, inversionista_id_inver, total, fecha) VALUES ('','$idin','$regarec','$fdeins')";
  	    $exqu = mysqli_query($conexion, $qry);
    
  	    $selg = "SELECT * FROM tipostr WHERE descripcion = 'GANANCIAS'";
    	$consg = mysqli_query($conexion, $selg) or die('Err0: '. mysqli_error($conexion));
    	$idtr = mysqli_fetch_object($consg);
    	
    	$q3 = "INSERT INTO transacciones (idtransacciones, inversionista_id_inver, tipostr_idtipostr, fechat, observaciones) VALUES ('','$idin','$idtr->idtipostr','$fdeins','$regarec')";
    	$ins = mysqli_query($conexion, $q3) or die('Err0: '. mysqli_error($conexion));
     
    	$busqusr = "SELECT * FROM puntos WHERE inversionista_id_inver = '$idin'";
   		$consb = mysqli_query($conexion, $busqusr) or die ('Err0: '.mysqli_error($conexion));
   		$usr = mysqli_fetch_object($consb);
   		$puntos = $usr->puntosact;
   		$npagos = $usr->no_pagos;
   		
   		$puntos = $puntos + $regarec;
   		$npagos++;
   		
   		$query = "UPDATE puntos SET puntosact = '$puntos', no_pagos ='$npagos' WHERE inversionista_id_inver = '$idin'";
   		$updpun = mysqli_query($conexion, $query) or die('Err0: '. mysqli_error($conexion));
  	  
   		$totregs = $totregs + $regarec;
  	  }
      
     } 
     echo "</table>";
     $totregs = number_format($totregs,2);
     echo "<br /> <br /> <center>Total de Regalias a repartir: <label style='font-weight:bold; font-size:16px'> $$totregs</label> ";
     $con--;
     echo "<br /> <br /> Total de personas que recibir&aacute;n regalias: <label style='font-weight:bold; font-size:16px'> $con </label> </center>";
     $cnt = 1;
     $primlugs = "SELECT id_inver, nombre, appat, apmat, total FROM inversionista JOIN regalias ON inversionista.id_inver = regalias.inversionista_id_inver WHERE regalias.fecha BETWEEN '$fecini' AND '$fecfin' ORDER BY total DESC";
     $xprim = mysqli_query($conexion, $primlugs);
     if(mysqli_affected_rows($conexion))
     {	
     	echo "<br /> <br />";
     	echo "<center><label style='color:#5C3C12; font-size:28px; font-weight:bold'>Primeros lugares del Mes.</label></center>";
     	echo "<br /><br />";
     	echo "<table border='1' align='center' width='500'>";
     	while(($r = mysqli_fetch_object($xprim)) && ($cnt <= 3))
     	{
     	 	$total = number_format($r->total,2);
     		echo "<tr align='right'> <td>$cnt <td align='left'>$r->nombre $r->appat $r->apmat <td style='font-weight: bold'>$$total </tr>";
     		$cnt++;	
     	}
     	echo "</table>";
     }
    }
    else 
    {
    	echo "<html>";
   		echo "<head><meta http-equiv='Refresh' content='7;URL=entrada.php'></head>";
    	echo "<center>";
   		echo "<div style='width:500px; height:400; background: url(logotransp2.gif)'";
   		echo "<form name='form1' action='index.php' method='post' style='padding-top:120px'>";
   		echo "<label style='color:#FF0000; font-weight:bold; font-size:26px; padding-left:30px;'>MENSAJE:</label> <br /> <label style='color:#5C3C12; font-weight:bold; font-size:22px; padding-left:30px;'>NO SE ENCONTRARON REGISTROS DE PERSONAS QUE HAYAN GANADO REGALIAS.</label>";
    	echo "<br /><br />Pulsa <a href='entrada.php'>aqu&iacute;</a> si tu navegador no te redirecciona automaticamente";
   	
   		echo "</form>";
   		echo "</div>";
    	echo "</center>";
    	echo "</html>"; 
    }
    	 
   }  
   
   $hoy = date('Y-m-d');
   $div = explode("-",$hoy);
   $fecini = $div[0]."-".$div[1]."-"."01";
   $fecfin = $div[0]."-".$div[1]."-"."31";

   $chec = "SELECT * FROM regalias WHERE fecha BETWEEN '$fecini' AND '$fecfin'";
   $doit = mysqli_query($conexion, $chec);
   
   if(!mysqli_affected_rows($conexion))
   {
   	copiahisto();
   	repartiregs();
   }
   
   else 
   {
   	    echo "<html>";
   		echo "<head><meta http-equiv='Refresh' content='7;URL=entrada.php'></head>";
    	echo "<center>";
   		echo "<div style='width:500px; height:400; background: url(logotransp2.gif)'";
   		echo "<form name='form1' action='index.php' method='post' style='padding-top:120px'>";
   		echo "<label style='color:#FF0000; font-weight:bold; font-size:26px; padding-left:30px;'>ERROR:</label> <br /> <label style='color:#5C3C12; font-weight:bold; font-size:22px; padding-left:30px;'>YA SE REPARTIERON LAS REGALIAS DE ESTE MES.</label>";
    	echo "<br /><br />Pulsa <a href='entrada.php'>aqu&iacute;</a> si tu navegador no te redirecciona automaticamente";
   	
   		echo "</form>";
   		echo "</div>";
    	echo "</center>";
    	echo "</html>";
    	
   }
   
?>