<?php

/**
 *  Informatica Eindproject D4p
 *  6in3, Stedelijk Gymnasium Nijmegen
 *  Docent: Hans de Wolf
 *
 *  ==================
 *
 *  Daniel Boutros,
 *  Christiaan Goossens,
 *  Jelmer Hinssen
 */

namespace Inforbank\Application;

use \Slim\App;
use Inforbank\Application\Helper\Redirect;
use Inforbank\Proxy;

class Login
{
    public function __construct(App $app)
    {
        $app->get('/login', function ($request, $response, $args) {
            $query = $request->getQueryParams();
            $error = isset($query['error']);

            // Render index view
            return $this->renderer->render($response, 'login.phtml', array(
                'base' => Proxy::$route->getBaseUrl() . "/",
                'error' => $error
            ));
        });

        $app->post('/login', function ($request, $response, $args) {
            // Render index view
            $post = $request->getParsedBody();
            $query = $request->getQueryParams();
            $redirect = $query['redirect'];
            unset($query['redirect']);

            $queryString = http_build_query($query);

            try {
                $resp = $this->auth->login($post['rekeningnr'], $post['pascode']);

                if ($resp && $redirect !== "") {
                    if ($queryString !== "") {
                        return Redirect::create($request, $response, $redirect . "?" . $queryString);
                    } else {
                        return Redirect::create($request, $response, $redirect);
                    }
                } elseif ($resp) {
                    return Redirect::create($request, $response, '/rekeningen');
                } else {
                    return Redirect::create($request, $response, '/login?error&redirect='.$redirect);
                }
            } catch (\Exception $e) {
                return Redirect::create($request, $response, '/login?error&redirect='.$redirect);
            }
        });

        $app->get('/logout', function ($request, $response, $args) {
            $this->auth->logout();
            return Redirect::create($request, $response, '/login');
        });
    }
}
