<?php
namespace ProVM\KI\Common\Middleware;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as Handler;
use Psr\Http\Message\ResponseInterface as Response;
use Carbon\Carbon;

class Visits {
  protected $filename;
  protected $time;
  public function __construct(string $filename, int $visit_time) {
    $this->filename = $filename;
    $this->time = $visit_time;
  }
  public function __invoke(Request $request, Handler $handler): Response {
    $params = $request->getServerParams();
    $ip = $params['REMOTE_ADDR'];
    $fwd = 0;
    $login = Carbon::now();
    if (isset($params['HTTP_X_FORWARDED_FOR'])) {
      $fwd = $params['HTTP_X_FORWARDED_FOR'];
    }
    if (!file_exists($this->filename)) {
      $file = (object) [
        'visits' => 0,
        'ips' => []
      ];
    } else {
      $file = json_decode(trim(file_get_contents($this->filename)));
    }
    $found = false;
    foreach ($file->ips as $i => $ipd) {
      if ($ipd->ip == $ip and $ipd->fwd == $fwd) {
        $t = Carbon::parse($ipd->time);
        if ($t->diffInSeconds($login) > $this->time) {
          $file->ips[$i]->time = $login->format('Y-m-d H:i:s');
          $file->visits ++;
        }
        $found = true;
        break;
      }
    }
    if (!$found) {
      $file->ips []= (object) [
        'ip' => $ip,
        'fwd' => $fwd,
        'time' => $login->format('Y-m-d H:i:s')
      ];
      $file->visits ++;
    }
    file_put_contents($this->filename, json_encode($file, \JSON_PRETTY_PRINT));
    $response = $handler->handle($request);
    return $response;
  }
}
