<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

class InstallMiddleware
{
    /**
     * Allow access if app is installed. If config license.require_lic_file_for_access is true,
     * the license file must also exist.
     */
    public function handle(Request $request, Closure $next)
    {


        $licPath = config('license.license_file_path');
        $licExists = $licPath && file_exists($licPath);
        $requireLic = config('license.require_lic_file_for_access', false);
        $dbConfigured = false;
        $envPath = base_path('.env');
        if (file_exists($envPath)) {
            $content = file_get_contents($envPath);
            if (preg_match('/^DB_DATABASE=["\']?([^"\'\s#]+)/m', $content, $matches)) {
                $dbConfigured = !empty($matches[1]);
            }
        }
        $allowed = ($requireLic === false || $licExists) && $dbConfigured;

        if ($allowed) {
            return $next($request);
        }
        return redirect('install/initialize');
    }
}
