<?php

/*
  |--------------------------------------------------------------------------
  | Application & Route Filters
  |--------------------------------------------------------------------------
  |
  | Below you will find the "before" and "after" events for the application
  | which may be used to do any work before or after a request into your
  | application. Here you may also register your custom route filters.
  |
 */

use Symfony\Component\HttpFoundation\Response;

App::before(function ($request) {
    $environment = App::environment();

    if (!empty(Config::get('api.trusted-proxies'))) {
        Request::setTrustedProxies(Config::get('api.trusted-proxies'));
    }

    if ($environment === 'production') {
        // Fix SSL
        //Request::setTrustedProxies([$request->getClientIp()]);



        //If there is a www in the url redirect to the secure address without www
        //        if (strpos(Request::url(), 'http://www.')!==false){
        //            $newPath = str_replace('http://www.','https://', Request::path());
        //            return Redirect::secure($newPath);
        //        }
        //        if (strpos(Request::url(), 'https://www.')!==false){
        //            $newPath = str_replace('https://www.','https://', Request::path());
        //            return Redirect::secure($newPath);
        //        }

        //Always use SSL in production
        if (!Request::secure()) {
            return Redirect::secure(Request::path());
        }
    }


    $currentUrl = preg_replace('/https?:\/\//', '', $request->fullUrl());

    $urlPT = [
        'local' => 'edp-live-bands.local',
        'front-end' => 'edp-live-bands.local',
        'development' => 'edp-live-bands.local',
        'staging' => 'edp-live-bands.staging.wiz.pt',
        'production' => 'edplivebandsportugal.edp.com',
    ];
    $credentials = Contest::facebookApp();
    //set the default to portuguses
    Config::set("eloquent-oauth-l4::providers.facebook.client_id", array_get($credentials, 'client_id'));
    Config::set("eloquent-oauth-l4::providers.facebook.client_secret", array_get($credentials, 'client_secret'));

    $edition = 'pt';

    Config::set('database.default', $edition);

    Contest::setEdition($edition);
    Config::set('edp_live_bands', $edition);
    Config::set('mail.username', Contest::smtpMailer());
    Config::set('mail.from', array('address' => Contest::email(), 'name' => Contest::title()));
    Config::set('app.timezone', Contest::timezone());
    date_default_timezone_set(Contest::timezone());
    Contest::email();
    App::setLocale($edition);


    Config::set("eloquent-oauth-l4::providers.facebook.client_id", array_get($credentials, 'client_id'));
    Config::set("eloquent-oauth-l4::providers.facebook.client_secret", array_get($credentials, 'client_secret'));

    View::share('edition', Contest::getEdition());
});

Route::filter('no.session.cookie', function()
{
    Config::set('session.driver', 'array');
    Config::set('cookie.driver', 'array');
});

App::after(function ($request, $response) {
    //
});

/*
  |--------------------------------------------------------------------------
  | Authentication Filters
  |--------------------------------------------------------------------------
  |
  | The following filters are used to verify that the user of the current
  | session is logged into this application. The "basic" filter easily
  | integrates HTTP Basic authentication for quick, simple checking.
  |
 */

Route::filter('auth', function () {
    if (Auth::guest())
        return Redirect::guest('login');
});


Route::filter('auth.basic', function () {
    return Auth::basic();
});

Route::filter('http_basic', function($route, $request) {
    if (getenv('FADO_ENV_HTTP_USER') && getenv('FADO_ENV_HTTP_PASSWORD')) {
        if ( ! $request->getUser()) {
            $headers = array('WWW-Authenticate' => 'Basic');
            return new Response('Invalid credentials.', 401, $headers);
        } else {
            if ($request->getUser() != getenv('FADO_ENV_HTTP_USER') || $request->getPassword() != getenv('FADO_ENV_HTTP_PASSWORD')) {
                return new Response('Invalid credentials.', 401);
            }
        };
    }
});

/*
  |--------------------------------------------------------------------------
  | Guest Filter
  |--------------------------------------------------------------------------
  |
  | The "guest" filter is the counterpart of the authentication filters as
  | it simply checks that the current user is not logged in. A redirect
  | response will be issued if they are, which you may freely change.
  |
 */

Route::filter('guest', function () {
    if (Auth::check())
        return Redirect::to('/');
});

/*
  |--------------------------------------------------------------------------
  | CSRF Protection Filter
  |--------------------------------------------------------------------------
  |
  | The CSRF filter is responsible for protecting your application against
  | cross-site request forgery attacks. If this special token in a user
  | session does not match the one given in this request, we'll bail.
  |
 */

Route::filter('csrf', function () {
    if (Session::token() != Input::get('_token')) {
        throw new Illuminate\Session\TokenMismatchException;
    }
});

Route::filter('api_auth', function ($route, $request) {

    $apiConfig   = Config::get('api');

    // $validToken  = $apiConfig['token'];
    // $headerToken = $request->header('Secret-Token');

    // if ($validToken !== $headerToken) {
    //     return APIResponse::fail(401, [
    //         'token' => trans('api.messages.invalid_token')
    //     ]);
    // }

    $ipAddresses = $apiConfig['ip-addresses'];

    if (empty($ipAddresses)) {
        return;
    }

    $clientIp = $request->server->get('REMOTE_ADDR');

    if (is_array($clientIp)) {
        $clientIp = $clientIp[0];
    }

    $validIps = array_filter($ipAddresses, function ($ipAddress) use ($clientIp) {
        $maxIp = $ipAddress['max-ip-range'];
        $minIp = $ipAddress['min-ip-range'];

        $min      = ip2long($minIp);
        $max      = ip2long($maxIp);
        $clientIp = ip2long($clientIp);

        return $clientIp >= $min && $clientIp <= $max;
    });

    if (empty($validIps)) {
        return APIResponse::fail(401, [
            'ip' => trans('api.messages.invalid_ip')
        ]);
    }
});

Route::filter('voter_auth', function () {

    try {
        $jwtAuth = JWTAuth::parseToken();
        $claims  = $jwtAuth->getPayload();
        $model   = $claims->get('model');

        if (empty($model) || $model !== Voter::class) {
            return APIResponse::fail(404, [
                'voter' => trans('api.messages.voter_not_found')
            ]);
        }

        $user = JWTAuth::parseToken()->authenticate();

        if (!$user || !$user instanceof Voter) {
            return APIResponse::fail(404, [
                'voter' => trans('api.messages.voter_not_found')
            ]);
        }
    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

        return APIResponse::fail(401, [
            'token' => trans('api.messages.token_expired')
        ]);
    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

        return APIResponse::fail(401, [
            'token' => trans('api.messages.token_invalid')
        ]);
    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
        return APIResponse::fail(401, [
            'token' => trans('api.messages.token_invalid')
        ]);
    }
});
