<?php
namespace GlpiPlugin\Wbstore;

if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access this file directly");
}

class Notifications {

   public static function table(): string {
      global $DB;
      if (method_exists($DB, 'getTable')) {
         return $DB->getTable('plugin_wbstore_notifications');
      }
      // fallback
      return 'glpi_plugin_wbstore_notifications';
   }

   public static function create(array $row): bool {
      global $DB;
      $table = self::table();
      $defaults = [
         'instance_id' => (string)Config::get('instance_id', ''),
         'license_key' => (string)Config::get('license_key', ''),
         'title'       => '',
         'message'     => '',
         'level'       => 'info',
         'url'         => '',
         'is_read'     => 0,
         'created_at'  => date('Y-m-d H:i:s'),
      ];
      $row = array_merge($defaults, $row);

      try {
         if (method_exists($DB, 'insert')) {
            return (bool)$DB->insert($table, $row);
         }
      } catch (\Throwable $e) {}
      try {
         // Legacy GLPI DB wrapper
         $DB->doQuery("INSERT INTO `$table` (`instance_id`,`license_key`,`title`,`message`,`level`,`url`,`is_read`,`created_at`)
            VALUES ('".$DB->escape($row['instance_id'])."','".$DB->escape($row['license_key'])."','".$DB->escape($row['title'])."','".$DB->escape($row['message'])."','".$DB->escape($row['level'])."','".$DB->escape($row['url'])."',".(int)$row['is_read'].",'".$DB->escape($row['created_at'])."')");
         return true;
      } catch (\Throwable $e) {
         error_log('[wbstore] notification insert error: ' . $e->getMessage());
         return false;
      }
   }

   public static function listRecent(int $limit = 5, bool $onlyUnread = false): array {
      global $DB;
      $table = self::table();
      $iid = (string)Config::get('instance_id','');
      $lk  = (string)Config::get('license_key','');

      $where = "WHERE `instance_id`='".$DB->escape($iid)."' AND `license_key`='".$DB->escape($lk)."'";
      if ($onlyUnread) {
         $where .= " AND `is_read`=0";
      }
      $sql = "SELECT * FROM `$table` $where ORDER BY `id` DESC LIMIT ".(int)$limit;
      $out = [];
      try {
         $res = $DB->query($sql);
         if ($res) {
            while ($row = $DB->fetchAssoc($res)) {
               $out[] = $row;
            }
         }
      } catch (\Throwable $e) {
         error_log('[wbstore] notification list error: ' . $e->getMessage());
      }
      return $out;
   }

   public static function countUnread(): int {
      global $DB;
      $table = self::table();
      $iid = (string)Config::get('instance_id','');
      $lk  = (string)Config::get('license_key','');
      $sql = "SELECT COUNT(*) AS c FROM `$table` WHERE `instance_id`='".$DB->escape($iid)."' AND `license_key`='".$DB->escape($lk)."' AND `is_read`=0";
      try {
         $res = $DB->query($sql);
         if ($res && ($row = $DB->fetchAssoc($res))) {
            return (int)$row['c'];
         }
      } catch (\Throwable $e) {}
      return 0;
   }

   public static function markRead(int $id): void {
      global $DB;
      $table = self::table();
      try { $DB->doQuery("UPDATE `$table` SET `is_read`=1 WHERE `id`=".(int)$id); } catch (\Throwable $e) {}
   }

   public static function clearRead(): void {
      global $DB;
      $table = self::table();
      $iid = (string)Config::get('instance_id','');
      $lk  = (string)Config::get('license_key','');
      try { $DB->doQuery("DELETE FROM `$table` WHERE `instance_id`='".$DB->escape($iid)."' AND `license_key`='".$DB->escape($lk)."' AND `is_read`=1"); } catch (\Throwable $e) {}
   }
}
