<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Views\Twig;
use Slim\Flash\Message;

// Routes


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

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


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


$app->get('/committees', function (Request $request, Response $response, array $args) {
  $view = Twig::fromRequest($request);

  return $view->render($response, 'committess.html', $args);
});

$app->get('/practicalinfo', function (Request $request, Response $response, array $args) {
  $view = Twig::fromRequest($request);
    return $view->render($response, 'practicalinfo.html', $args);
});

$app->get('/invitedspeakers', function (Request $request, Response $response, array $args) {
  $view = Twig::fromRequest($request);

  try {
      $speakers = $this->get('db')->getSpeakers();
    } catch (Exception $e) {
      // $this->logger->debug("Submit register DB error: ".$e->getMessage());
      $this->get('flash')->addMessageNow("Get Speakers", "DB error: ".$e->getMessage());

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

$app->get('/program', function (Request $request, Response $response, array $args) {
  $view = Twig::fromRequest($request);
  
  return $view->render($response, 'program.html', $args);
});

$app->get('/inscriptos', function(Request $request, Response $response, array $args){
  $view = Twig::fromRequest($request);
    $db = $this->get('db');
    $data = $db->getAll();    
    return $view->render($response, 'inscriptos.html', ["registros" => $data]);    
});

$app->get('/inscriptoscsv', function(Request $request, Response $response, array $args){
  $view = Twig::fromRequest($request);

  $dbfile = $this->get('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;
};

$app->get('/gallery', function (Request $request, Response $response, array $args) {
  $view = Twig::fromRequest($request);
  return $view->render($response, 'gallery.html', $args);
});

$app->get('/certificates', function(Request $request, Response $response, array $args){
  $view = Twig::fromRequest($request);
  
  $pathp = 'dilomas/participants';
  $paths = 'diplomas/speakers';
  $filesp = scandir("$pathp");
  $filess = scandir("$paths");
  unset($filesp[0]);
  unset($filesp[1]);
  unset($filess[0]);
  unset($filess[1]);  
  
  $view->render($response,"certificates.html",['archivosp'=>$filesp,'archivoss'=>$filess]);
});

// 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->get('flash');
    $data = $request->getParsedBody();
    $db = $this->get('db');
    if($this->get('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;
	});

});
