<?php
namespace App\Http\Middleware;

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

class Installed
{
  /**
    * Handle an incoming request.
    *
    * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
    */
  public function handle(Request $request, Closure $next): Response
  {
    if (!file_exists(base_path('storage/installed'))) {
      $this->check();
      $this->install();
    } elseif (config('app.version') > file_get_contents(base_path('storage/installed'))) {
      $this->check();
      $this->update();
    }
    return $next($request);
  }

  private function install()
  {
    $exitCode = 0;
    $exitCode += Artisan::call('migrate', ['--force' => true]);
    echo config('app.name') . ' DB Migration ... ' . (empty($exitCode) ? 'Success <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>' : 'Error <img src="' . url('/app-assets/images/app/error-20.png') . '"><br><br>');
    $exitCode += Artisan::call('db:seed', ['--force' => true]);
    echo config('app.name') . ' DB Seed ... ' . (empty($exitCode) ? 'Success <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>' : 'Error <img src="' . url('/app-assets/images/app/error-20.png') . '"><br><br>');
    if (empty($exitCode)) {
      echo '<br><h4>Install: v' . config('app.version') . ' SUCCESS <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
      echo '<br>Please click "CONTINUE".<br>';
      file_put_contents(base_path('storage/installed'), config('app.version'));
    } else {
      echo '<br>Error found >> Please re-check database credentials inside .env file!<br>';
      echo '<br><h4>Install: ERROR<br>';
    }
    echo '<br><input type="button" onclick="window.location.reload();" value="CONTINUE" />';
    die();
  }

  private function update()
  {
    $exitCode = 0;
    $exitCode += Artisan::call('migrate', ['--force' => true]);
    echo config('app.name') . ' DB Migration ... ' . (empty($exitCode) ? 'Success <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>' : 'Error <img src="' . url('/app-assets/images/app/error-20.png') . '"><br><br>');
    $exitCode += Artisan::call('db:seed', ['--force' => true]);
    echo config('app.name') . ' DB Seed ... ' . (empty($exitCode) ? 'Success <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>' : 'Error <img src="' . url('/app-assets/images/app/error-20.png') . '"><br><br>');
    if (empty($exitCode)) {
      file_put_contents(base_path('storage/installed'), config('app.version'));
      echo '<br><h4>Update: v' . config('app.version') . ' SUCCESS <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
      echo '<br>Please click "CONTINUE".<br>';
      echo '<br><button type="button" id="btn-continue" onclick="socksession();">CONTINUE</button>';
      echo '<script src="' . url('/app-assets/vendors/js/socket.io/socket.io.js') . '"></script>';
      echo '<script>';
      echo 'function socksession() {';
      echo 'const socket = io("' . rtrim(config('app.node_url'), '/') . '");';
      $devices = \App\Models\Device::where('status', 'ONLINE')->get();
      $count = ceil(count($devices)/6);
      foreach ($devices as $device) {
        echo 'socket.emit("sockSession", { sender: "' . $device->sender . '" });';
      }
      echo 'document.getElementById("btn-continue").disabled = true;';
      echo 'let count = '. $count .';';
      echo 'let counter = setInterval(timer, 1000);';
      echo 'function timer(){';
      echo 'count -= 1;';
      echo 'if (count <= 0){';
      echo 'clearInterval(counter);';
      echo 'window.location.reload();';
      echo 'return;';
      echo '}';
      echo 'document.getElementById("btn-continue").innerHTML = "' . __('DO NOT CLOSE / BACK / REFRESH !!!') . '" + " WAIT " + count + " seconds.";';
      echo '}';
      echo '}';
      echo '</script>';
      die();
    } else {
      echo '<br>Error found >> Please re-check database credentials inside .env file!<br>';
      echo '<br><h4>Update: ERROR<br>';
      echo '<br><button type="button" id="btn-continue" onclick="window.location.reload();">RELOAD</button>';
      die();
    }
  }

  private function check()
  {
    if (extension_loaded('curl')) {
      echo 'PHP Extension: curl >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: curl >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('dom')) {
      echo 'PHP Extension: dom >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: dom >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('fileinfo')) {
      echo 'PHP Extension: fileinfo >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: fileinfo >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('gd')) {
      echo 'PHP Extension: gd >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: gd >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('intl')) {
      echo 'PHP Extension: intl >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: intl >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('json')) {
      echo 'PHP Extension: json >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: json >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('mbstring')) {
      echo 'PHP Extension: mbstring >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: mbstring >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('mysqlnd')) {
      echo 'PHP Extension: mysqlnd >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: mysqlnd >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('openssl')) {
      echo 'PHP Extension: openssl >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: openssl >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('pdo')) {
      echo 'PHP Extension: pdo >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: pdo >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('tokenizer')) {
      echo 'PHP Extension: tokenizer >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: tokenizer >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (extension_loaded('zip')) {
      echo 'PHP Extension: zip >> LOADED <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('PHP Extension: zip >> NOT LOADED <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (is_writable(base_path('bootstrap/cache/'))) {
      echo 'Folder: bootstrap/cache/ >> WRITEABLE <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('Folder: bootstrap/cache/ >> NOT WRITEABLE <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (is_writable(base_path('storage/framework/'))) {
      echo 'Folder: storage/framework/ >> WRITEABLE <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('Folder: storage/framework/ >> NOT WRITEABLE <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    if (is_writable(base_path('storage/logs/'))) {
      echo 'Folder: storage/logs/ >> WRITEABLE <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
    } else {
      die('Folder: storage/logs/ >> NOT WRITEABLE <img src="' . url('/app-assets/images/app/error-20.png') . '">');
    }
    echo 'PHP VERSION: ' . PHP_VERSION . ' <img src="' . url('/app-assets/images/app/check-20.png') . '"><br><br>';
  }
}