<?php

use Slim\Http\Request;
use Slim\Http\Response;
use Symfony\Component\Yaml\Yaml;

// 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();
  return $this->renderer->render($response, 'participants.html', ['registros' => $data]);
});


$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->get('/sesiones', function (Request $request, Response $response, array $args) {
  $this->logger->info("GDDWorkshop '/sesiones' route");
  $sesiones = Yaml::parseFile(__DIR__."/../data/sesiones.yml");
  //$strsesiones = file_get_contents(__DIR__."/../data/sesiones.json");
  //$sesiones = json_decode($strsesiones,true);
  
  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['titulo']);
    $b = removeAccents($s2['titulo']);   
   return strcasecmp($a,$b)<0?-1:1;
  });
  
  //echo "<pre>".var_export($sesiones,true)."</pre>";
  return $this->renderer->render($response, 'sesiones.html', ["sesiones"=>array_chunk($sesiones,8,true)]);
});

$app->get('/programa', 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("/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", "First name could not be empty");
      if(!isset($data['apellido'])||empty($data['apellido']))
        $messages->addMessageNow("submit-register-err", "Last name could not be empty");
      if(!isset($data['email'])||empty($data['email']))
        $messages->addMessageNow("submit-register-err", "E-mail could not be empty");      
      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", "Please validate captcha!");
      }
      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", "ReCaptcha validation error " . implode($resp->getErrorCodes()));
        }
        else {
          unset($data['g-recaptcha-response']);
        }
      }

      try{
        if($db->findByMail($data['email']))
          $messages->addMessageNow("submit-register-err", $data['email']." is already registered<br/>"
          ."Please contact: <b>surfacedynamics2018@cmat.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"=>"You registration could not be completed:\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"=>"You have been successfully registered to Workshop on Surface Dynamics 2018",
                      "data"=>$data);
      $mailbody = "Hello ".$data["nombre"]." ".$data["apellido"].",\n\n".
      "You have been successfully registered to the Workshop on Surface Dynamics 2018!\n\n".
      "If you need to change the information you have provided and for any ".
      "questions please contact surfacedynamics2018@cmat.edu.uy\n\n".
      "Best!\n\n";
      $headers = 'From: ' . "surfacedynamics2018@cmat.edu.uy" . "\r\n" .
                  'Reply-To: ' . "surfacedynamics2018@edu.uy" . "\r\n" .
                  'Content-Type: ' . "text/plain; charset=UTF-8". "\r\n" .
                  'X-Mailer: PHP/' . phpversion();
      mail($data['email'], 'Successfully registered to the Surface Dynamics 2018 Workshop', $mailbody, $headers);
    }
    $newres = $response->withJson($arrayresponse);
    return $newres;
	});

});
