<?php

namespace App\Http\Controllers\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
// use Illuminate\Support\Facades\Log;

class Notification {
  private $check;

  public function __construct () {
    $this->check = checkLegit((isset($_COOKIE['kero_token']) ? $_COOKIE['kero_token'] : ''));
  }

  public function get () {
    $res = null;

    if ($this->check != 0) {
      if (Cache::has('getNotification')) $get = Cache::get('getNotification');
      else {
        $get = DB::table('usr_notification')->select('id', 'app_id', 'text', 'section', 'goto')->where('user_id', $this->check)->get();
        $res = array();

        foreach ($get as $g) {
          $prot = DB::table('sys_settings')->select('protocol')->first()->protocol;
          $goto = DB::table('sys_apps')->select('url')->where('id', $g->app_id)->first()->url;

          $res[] = array('id' => $g->id, 'text' => $g->text, 'url' => 'http'.($prot == 1 ? 's' : '').'://'.$goto.'/#/'.$g->section);
          Cache::put('getNotification', $get);
        }
      }

      return $res;
    }
    else return array();
  }

  public function add ($uid, $aid, $txt, $sec, $goto) {
    if ($this->check != 0) {
      $add = DB::table('usr_notification')->insert(['user_id' => $uid, 'app_id' => $aid, 'text' => $txt, 'section' => $sec, 'goto' => $goto]);
      if (Cache::has('getNotification')) Cache::forget('getNotification');
      return 1;
    }
  }

  public function delete ($id) {
    if ($this->check != 0) {
      $del = DB::table('usr_notification')->where('id', $id)->where('user_id', $this->check)->delete();
      if (Cache::has('getNotification')) Cache::forget('getNotification');
      return $del;
    }
  }
}
