<?php
class Logger {
    private static $conn = null;
    private static $userId;

    public static function init($userId) {
      self::$userId = $userId;
    }

    private static function dbconn() {
      $servername = "localhost";
      $username = "szatunaweb";
      $password = "5vZb.0GfLEB2E!";
      $serverdb = "log";

      if (self::$conn === null) {
        self::$conn = new mysqli($servername, $username, $password, $serverdb);
      }

      /* Joga van: SELECT, INSERT */

      return self::$conn;
    }

    public static function writeLogWarehouse($params) {
      $conn = self::dbconn();
      $date_create = time();

      $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
      $full_url = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

      $referrer_url = $_SERVER['HTTP_REFERER'] ?? $full_url;

      $reason = $params['reason'] ?? '';
      $reason_code = $params['reason_code'] ?? 0;
      $item_id = $params['item_id'] ?? '';
      $from_place = $params['from_place'] ?? '';
      $to_place = $params['to_place'] ?? '';
      $amount_left = $params['amount_left'] ?? 0;
      $amount_right = $params['amount_right'] ?? 0;

      if (empty(trim($reason))) {
        die('LOG ERROR - Nem lett specifikálva indoklás!');
      }

      $stmt = $conn->prepare("INSERT INTO warehouse(date_create, user_id, url, reason, reason_code, item_id, from_place, to_place, amount_left, amount_right) VALUES (?,?,?,?,?,?,?,?,?,?)");
      $stmt->bind_param("iississsii",
                        $date_create, self::$userId,
                        $referrer_url, $reason, $reason_code,
                        $item_id, $from_place, $to_place,
                        $amount_left, $amount_right);
      $stmt->execute();

      if (!empty(trim($item_id))) {
        $_GET['type'] = 'daily';
        $_GET['item_id'] = $item_id;
        $_GET['silent'] = true;
        include 'statistics.php';
      }

      return;
    }
}
?>
