<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;

/**
 * Class DatabaseConnect
 *
 * @package App\Http\Middleware
 */
class DatabaseConnect
{

    protected $except = [
        'api/user/profile/view-image/*',
        'api/chat/message/view-image/*'
    ];

    /**
     * Handle an incoming request
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        foreach ($this->except as $except) {
            if ($request->is($except)) {
                return $next($request);
            }
        }

        $customerId = $request->header('CustomerID');
        $config = config('databases.' . $customerId . '.config.inc');

        if ( ! count($config)) {
            abort(404);
        }

        Config::set('database.default', $customerId);
        Config::set('database.connections.' . $customerId, $config);

        return $next($request);
    }
}