<?php

use Slim\Http\Request;
use Slim\Http\Response;

// Routes

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

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


$app->get('/participants', 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('/committees', function (Request $request, Response $response, array $args) {
    $this->logger->info("GDDWorkshop '/committess' route");
    return $this->renderer->render($response, 'committess.html', $args);
});

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

$app->get('/invitedspeakers', function (Request $request, Response $response, array $args) {
    $this->logger->info("GDDWorkshop '/invitedspeakers' route");
    try {
      $speakers = $this->db->getSpeakers();
    } catch (Exception $e) {
      $this->logger->debug("Submit register DB error: ".$e->getMessage());
      $this->flash->addMessageNow("Get Speakers", "DB error: ".$e->getMessage());

    }
    return $this->renderer->render($response, 'invitedspeakers.html',
      ['speakers' => $speakers]);
});

$app->get('/program', 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){
    exec('sqlite3 -header -csv ../db/ggdworkshop.db "select * from registro" > "inscriptos.csv"');
    $file = 'inscriptos.csv';
    $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();
    if($this->settings['close_registration']){
        $messages->addMessageNow("submit-register-err", "Registration has benn closed");
      }
    else{
      $db = $this->db;
      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['financiacion'])||!is_numeric($data['financiacion']))
        $messages->addMessageNow("submit-register-err", "Question about financial support must have a selected answer");
      if(!isset($data['invited'])||!is_numeric($data['invited']))
        $messages->addMessageNow("submit-register-err", "Question about 'invited to participate in this conference' must have a selected answer");
      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 {
        $recaptcha = new ReCaptcha\ReCaptcha($this->settings['recaptcha']['secret-test']);
        //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>ggdworkshop@cmat.edu.uy</b>");
        else
          $db->insert($data);
      }
      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 {
        $arrayresponse = array("success" => true,
        "msg"=>"You have been successfully registered to the GGDWorkshop",
        "data"=>$data);
        $msg = "Hello ".$data["nombre"]." ".$data["apellido"].",\n\n".
        "You have been successfully registered to the Workshop on Groups, Geometry and Dynamics!\n\n".
        "For any questions please contact ggdworkshop@cmat.edu.uy\n\n".
        "Best!\n\n";
        $headers = 'From: ' . "ggdworkshop@cmat.edu.uy" . "\r\n" .
                   'Reply-To: ' . "ggdworkshop@cmat.edu.uy" . "\r\n" .
                   'Content-Type: ' . "text/plain; charset=UTF-8". "\r\n" .
                   'X-Mailer: PHP/' . phpversion();
        mail($data['email'], 'Successfully registered to the Workshop on Groups, Geometry and Dynamics', $msg, $headers);



      }
      $newres = $response->withJson($arrayresponse);
      return $newres;
	});

});
