<?php

use Slim\Http\Request;
use Slim\Http\Response;
use Symfony\Component\Yaml\Yaml;
function getSesiones($id=NULL){
  $sesiones = Yaml::parseFile(__DIR__."/../data/sesiones.yml"); 
  
  function removeAccents($string) {
    return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8'))), ' '));
  }  

  usort($sesiones,function($s1,$s2){
    $a = removeAccents($s1['sesion']);
    $b = removeAccents($s2['sesion']);   
   return strcasecmp($a,$b)<0?-1:1;
  });
  
  if($id==null)
    return $sesiones;
  else{
    return $sesiones[(int)--$id];  
  }
}
function getEventos($tipo){
  $conferencias = Yaml::parseFile(__DIR__."/../data/conferencias.yml");
  $sesiones = Yaml::parseFile(__DIR__."/../data/sesiones.yml");
  if($tipo !== 'sesiones'){    
    foreach ($conferencias as $val){            
      if ($val['categoria'] === $tipo){       
        $charlas = $val['charlas'];     
        $mockHour=8;  
        return array_map(function($event) use($val,&$mockHour){  
          
          $evento = array(
            'title'=>$event['titulo'],
            'start'=>$event['start']?$event['start']:'2021-09-15T'.++$mockHour.':00',
            'end'=>$event['end']?$event['end']:'2021-09-15T'.++$mockHour.':30',
            'description'=>$event['abstract'],
            'speaker'=>$event['speaker'],
            'resourceId'=>$val['categoria']
          );         
          return $evento;    
        },$charlas);
        //echo json_encode($ret);
      }
        
      
    }
  }
  else{
    return $sesiones;
  }
}
// Routes
$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
  "path" => ["/inscriptos", "inscriptoscsv"], /* or ["/admin", "/api"] */
  "realm" => "Protected",
  "secure" => false,
  "users" => [
      "admin" => "puntofijo"      
  ]
]));

$app->get('/', function (Request $request, Response $response, array $args) {
    $this->logger->info("GDDWorkshop '/' route");
    return $this->renderer->render($response, 'index.html', $args);
});
$app->get('/descripcion', function (Request $request, Response $response, array $args) {
    $this->logger->info("GDDWorkshop '/descripcion' route");
    return $this->renderer->render($response, 'descripcion.html', $args);
});

$app->get('/registrarse', function (Request $request, Response $response, array $args) {
    $this->logger->info("GDDWorkshop '/registrtion' route");
    $recapsitekey = $this->settings["recaptcha"]["sitekey"];
    if($this->settings["testing"]){
      $recapsitekey = $this->settings["recaptcha"]["sitekeytest"];
    }
    return $this->renderer->render($response, 'registration.html',
      [
        'closed' => $this->settings['close_registration'],
        'sitekey' => $recapsitekey
      ]);
});


$app->get('/participantes', function (Request $request, Response $response, array $args) {
  $this->logger->info("GDDWorkshop '/participants' route");
 	$db = $this->db;
 	$data = $db->getAll();
  $result = array('Estudiante de grado'=>array(),'Estudiante de posgrado'=>array(),'Profesor'=>array(),'Posdoctorando'=>array(),'Otro'=>array());
  foreach ($data as $element) {
    switch ($element['titulo']){
      case 'Profesor':
        $result['Profesor'][] = $element;
        break;
      case 'Posdoctorando':
        $result['Posdoctorando'][] = $element;
        break;
      case 'Estudiante de posgrado':
        $result['Estudiante de posgrado'][] = $element;
        break;
      case 'Estudiante de grado':
        $result['Estudiante de grado'][] = $element;
        break;
      default:
        $result['Otro'][] = $element;
        break;
    }
  }
  //echo '<pre>' . json_encode($result,JSON_PRETTY_PRINT). '</pre>';
  
  return $this->renderer->render($response, 'participants.html', ['registros' => $result]);
});


$app->get('/comites', function (Request $request, Response $response, array $args) {
    $this->logger->info("GDDWorkshop '/committess' route");
    $comites = Yaml::parseFile(__DIR__."/../data/comites.yml");
    //$strcomites = file_get_contents(__DIR__."/../data/comites.json");
    //$comites = json_decode($strcomites,true);
    //echo "<pre>".var_export($comites,true)."</pre>";
    return $this->renderer->render($response, 'committess.html',['comites' => $comites]);
});

$app->get('/informacion-practica', function (Request $request, Response $response, array $args) {
    $this->logger->info("GDDWorkshop '/practicalinfo' route");
    return $this->renderer->render($response, 'practicalinfo.html', $args);
});

$app->get('/conferencias', function (Request $request, Response $response, array $args) {
    $this->logger->info("GDDWorkshop '/charlas' route");
    //$strcharlas = file_get_contents(__DIR__."/../data/conferencias.json");
    
    $charlas = Yaml::parseFile(__DIR__."/../data/conferencias.yml");
    //echo "<pre>".var_export($charlasyml,true)."</pre>";
    //$charlas = json_decode($strcharlas,true);
    /*function cmp($a, $b){
      $aArray = explode(" ", $a.no);
      $bArray = explode(" ", $b);
      $aApellido = $a
      if($a == $b){
        return 0;
      }
      return ($a<$b)?-1:1;
    }  */
    return $this->renderer->render($response, 'conferencias.html',
      ['charlas' => $charlas]);
});
$app->group('/sesiones',function($app){
  $app->get('', function (Request $request, Response $response, array $args) {
    $this->logger->info("GDDWorkshop '/sesiones' route");
    /*$sesiones = Yaml::parseFile(__DIR__."/../data/sesiones.yml"); 
    
    function removeAccents($string) {
      return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8'))), ' '));
    }  

    usort($sesiones,function($s1,$s2){
      $a = removeAccents($s1['sesion']);
      $b = removeAccents($s2['sesion']);   
    return strcasecmp($a,$b)<0?-1:1;
    });*/
    $sesiones = getSesiones();
    
    //echo "<pre>".var_export($sesiones,true)."</pre>";
    return $this->renderer->render($response, 'sesiones.html', ["sesiones"=>array_chunk($sesiones,5,true)]);
  });
  $app->get('/{sesionId}', function (Request $request, Response $response, array $args) {
    $sesion = getSesiones($args['sesionId']);
    usort($sesion['charlas'],function($a,$b){
      return strtotime($a["start"]) - strtotime($b["start"]);
    });
    setlocale(LC_TIME, 'es_UY.utf8');
    $charlas = array_reduce($sesion['charlas'], function($acc,$charla){
      $index = isset($charla['start']) ? ucfirst(strftime("%A %d",strtotime($charla['start']))) : 'TBA';
      if(isset($acc[$index]))
       $acc[$index][] = $charla;
      else
        $acc[$index] = array($charla);
      return $acc;
    },[]);
    
    return $this->renderer->render($response, 'sesion.html', ["sesion"=>$sesion,"charlas"=>$charlas]);

  });
  $app->get('/group/{sesionId}', function (Request $request, Response $response, array $args) {    
    $sesion = getSesiones($args['sesionId']);
    usort($sesion['charlas'],function($a,$b){
      return strtotime($a["start"]) - strtotime($b["start"]);
    });
     setlocale(LC_TIME, 'es_UY.utf8');  
     $charlas = array_reduce($sesion['charlas'], function($acc,$charla){
      //$index = isset($charla['start']) ? date("l d",strtotime($charla['start'])) : 'TBA';      
      $index = isset($charla['start']) ? ucfirst(strftime("%A %d",strtotime($charla['start']))) : 'TBA';
      if(isset($acc[$index]))
       $acc[$index][] = $charla;
      else
        $acc[$index] = array($charla);
      return $acc;
    },[]);
  //echo '<pre>' . json_encode($result,JSON_PRETTY_PRINT). '</pre>';
    return $response->withJson($charlas);
    //return $this->renderer->render($response, 'sesion.html', ["sesion"=>$sesion]);

  });


});


$app->get('/calendario', function (Request $request, Response $response, array $args) {
    $this->logger->info("GDDWorkshop '/program' route");
    return $this->renderer->render($response, 'program.html', $args);
});

$app->get('/inscriptos', function(Request $request, Response $response, array $args){
    $this->logger->info("GDDWorkshop '/practicalinfo' route");
    $db = $this->db;
    $data = $db->getAll();    
    return $this->renderer->render($response, 'inscriptos.html', ["registros" => $data]);    
});

$app->get('/inscriptoscsv', function(Request $request, Response $response, array $args){
  $this->logger->info("GDDWorkshop '/practicalinfo' route");
  $dbfile = $this->settings['db']['path'];
    $file = 'inscriptos-surface2018.csv';    
    exec('sqlite3 -header -csv '.$dbfile.' "select * from registro" > "'.$file.'"');    
    
    $fh = fopen($file,"rb");
    $stream = new \Slim\Http\Stream($fh);
    return $response->withHeader('Content-Type', 'application/force-download')
                    ->withHeader('Content-Type', 'application/octet-stream')
                    ->withHeader('Content-Type', 'application/download')
                    ->withHeader('Content-Description', 'File Transfer')
                    ->withHeader('Content-Transfer-Encoding', 'binary')
                    ->withHeader('Content-Disposition', 'attachment; filename="' . basename($file) . '"')
                    ->withHeader('Expires', '0')
                    ->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
                    ->withHeader('Pragma', 'public')
                    ->withBody($stream);
});

$mw = function ($request, $response, $next) {
    $response->getBody()->write('BEFORE');
    $response = $next($request, $response);
    $response->getBody()->write('AFTER');

    return $response;
};

// API ROUTES
$app->group('/api', function($app){
  $app->get("/eventos/{tipo:cursos|plenarias|semiplenarias|publicas|premiados}",function(Request $request, Response $response, array $args) {    
      $tipo=$args['tipo']=="publicas"?"Públicas":ucfirst($args['tipo']);
      if($tipo==="Cursos"){
        $cursos = [];
        foreach(getEventos($tipo) as $event){          
          for($i=0;$i<3;$i++){
            $eventStart = new DateTime($event['start']);
            $eventEnd = new DateTime($event['end']);            
            $eventStart->add(new DateInterval("P{$i}D"));
            $eventEnd->add(new DateInterval("P{$i}D"));            
            $cursos[] = array(
              'title'=>$event['title'],
              'start'=>$eventStart->format("c"),
              'end'=>$eventEnd->format("c"),
              'description'=>$event['description'],
              'speaker'=>$event['speaker'],         
            );           
          }
        }
        $newres = $response->withJson($cursos);
      }      
      else
        $newres = $response->withJson(getEventos($tipo));
      return $newres;
  });
  $app->group("/eventos/sesiones/", function($app){
    $app->get("",function(Request $request, Response $response, array $args){
      $sesiones = getSesiones();
      $sesionesEventos = [];
      for($i=0;$i<5;$i++){
        $dia=13+$i;
        $evento = array(
            'title'=>"Sesiones",
            'start'=>'2021-09-'.$dia.'T15:00-0300',
            'end'=>'2021-09-'.$dia.'T18:15-0300',
            'description'=>"",
            'speaker'=>"",            
          );
        $sesionesEventos[]=$evento;         
      }
      foreach ($sesiones as $ses){

      }
      return $response->withJson($sesionesEventos);
    });
    $app->get("/{sesionId}",function(Request $request, Response $response, array $args) {
    
    $newres = $response->withJson(getSesiones($args['sesionId']));    
    return $newres;
  });

  });
  
	$app->get("/test", function(Request $request, Response $response, array $args) {
		$this->logger->info("GDDWorkshop '/api/test' route");
		return var_dump($request);

	});

	$app->post('/register', function (Request $request, Response $response, array $args) {
    $messages = $this->flash;
    $data = $request->getParsedBody();
    $db = $this->db;
    if($this->settings['close_registration']){
        $messages->addMessageNow("submit-register-err", "Registration has benn closed");
      }
    else{
    
      if(!isset($data['nombre'])||empty($data['nombre']))
        $messages->addMessageNow("submit-register-err", "Debe ingresar nombre");
      if(!isset($data['apellido'])||empty($data['apellido']))
        $messages->addMessageNow("submit-register-err", "Debe ingresar apellido");
      if(!isset($data['email'])||empty($data['email']))
        $messages->addMessageNow("submit-register-err", "Debe ingresar e-mail");      
      if(!isset($data['ciudad'])||empty($data['ciudad']))
        $messages->addMessageNow("submit-register-err", "Debe ingresar ciudad");      
      if(!isset($data['pais'])||empty($data['pais']))
        $messages->addMessageNow("submit-register-err", "Debe seleccionar pais");      
      if(!isset($data['titulo'])||empty($data['titulo']))
        $messages->addMessageNow("submit-register-err", "Debe seleccionar profesión o actividad");      
      if(!isset($data['afiliacion'])||empty($data['afiliacion']))
        $messages->addMessageNow("submit-register-err", "Debe ingresar afiliación");      
      if(!isset($data['emailzoom'])||empty($data['emailzoom']))
        $messages->addMessageNow("submit-register-err", "Debe ingresar e-mail asociado a cuenta Zoom");      
      /*if(!isset($data['letterinvited'])||!is_numeric($data['letterinvited']))
        $messages->addMessageNow("submit-register-err", "Question about needing a letter of invitation must have a selected answer");*/
        
      //ReCaptcha Validation
      if(!isset($data['g-recaptcha-response'])||empty($data['g-recaptcha-response'])){
        $messages->addMessageNow("submit-register-err", "Debe validar el ReCaptcha!");
      }
      else {        
        $recapsecret = $this->settings['recaptcha']['secret'];
        if($this->settings['testing']){
          $recapsecret = $this->settings['recaptcha']['secrettest'];
        }
        
        $recaptcha = new ReCaptcha\ReCaptcha($recapsecret);
        //get remote ip from request header TODO
        $resp = $recaptcha->verify($data['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
        if(!$resp->isSuccess()){
          $messages->addMessageNow("submit-register-err", "Error de validación de ReCaptcha " . implode($resp->getErrorCodes()));
        }
        else {
          unset($data['g-recaptcha-response']);
        }
      }

      try{
        if($db->findByMail($data['email']))
          $messages->addMessageNow("submit-register-err", $data['email']." ya está registrado<br/>"
          ."Contacte a: <b>clam2021@fing.edu.uy</b>");
      }catch (Exception $e){
        $this->logger->debug("Submit register DB error: ".$e->getMessage());
        $messages->addMessageNow("submit-register-err", "DB error: ".$e->getMessage());
      }
    }
    
    if($messages->hasMessage("submit-register-err")){
        $arrayresponse = array("success" => false,
        "msg"=>"Su registro NO pudo ser completado:\n",
        "errors"=>$messages->getMessage("submit-register-err"), "data"=>$data);
    }

    else {
      try{
      $db->insert($data);
      }catch (Exception $e){
        $this->logger->debug("Submit register DB error: ".$e->getMessage());
        $messages->addMessageNow("submit-register-err", "DB error: ".$e->getMessage());
      }
      $arrayresponse = array("success" => true,
                      "msg"=>"Su registro al CLAM2021 ha sido satisfactorio.",
                      "data"=>$data);
      $mailbody = "Hola ".$data["nombre"]." ".$data["apellido"].",\n\n".
      "Se ha inscripto satisfactoriamente al CLAM2021!\n\n".
      "Por cualquier consulta no dude en contactar al comité organizador en: ".
      "clam2021@fing.edu.uy\n\n".
      "Saludos Cordiales!\n\n";
      $headers = 'From: ' . "clam2021@fing.edu.uy" . "\r\n" .
                  'Reply-To: ' . "clam2021@fing.edu.uy" . "\r\n" .
                  'Content-Type: ' . "text/plain; charset=UTF-8". "\r\n" .
                  'X-Mailer: PHP/' . phpversion();
      mail($data['email'], 'Registro exitoso CLAM2021', $mailbody, $headers);
    }
    $newres = $response->withJson($arrayresponse);
    return $newres;
	});

});
