<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;
use Symfony\Component\HttpFoundation\Response;

class IsInstalled
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {

        if (
            $this->checkConnectionFileExists()
            && ($this->checkProgressIsCompletedInDB()
                || $this->checkProgressIsCompletedInConfig())
        ) {
            return $next($request);
        }

        return redirect()->route('install');

        // if (isDocker(true) || isHostedVersion(true)) {

        // }

        // return response(view('partials.error', [

        //     'error' => 'Smart Report Maker is not installed successfully yet!'
        // ]));
    }

    private function connectionFile()
    {
        return 'srm_db_config';
    }

    private function installConfigFile()
    {
        return 'srm_install_config';
    }

    private function checkInstallConfigFileExists()
    {
        return config($this->installConfigFile()) ? true : false;
    }

    private function checkProgressIsCompletedInConfig()
    {

        if ($this->checkInstallConfigFileExists()) {
            return config($this->installConfigFile() . '.status') === 'complete' ? true : false;
        }

        return false;
    }

    private function checkConnectionFileExists()
    {

        if (!config($this->connectionFile())) {
            $this->clearConfigCache();
        }

        return config($this->connectionFile()) ? true : false;
    }

    private function clearConfigCache()
    {
        Artisan::call("config:clear");
    }

    private function checkProgressIsCompletedInDB()
    {
        $installed = DB::table($this->InstalledVersionsTable())
        // ->where('version', $this->currentVersion())
            ->where('is_current', 1)
            ->where('is_install_complete', 1)
            ->first();

        return $installed ? true : false;
    }

    private function InstalledVersionsTable()
    {
        return 'srm_installed_versions';
    }

    private function currentVersion()
    {
        return 'v9.1.8';
    }

}
