<?php

namespace App\Http\Controllers;

use App\Models\ForUser;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

use App\Http\Controllers\AuthController;

class UserController extends Controller {
  private $objAuth;

  public function __construct() {
    $this->objAuth = new AuthController();
  }

  public function getLoggedUser ($id, $kero) {
    $check = $this->objAuth->checkLegit($kero);
    if ($check == 0) return 0;

    $valid = $this->objAuth->getPermissions($kero);
    $cols = $this->getGroupColours()->toArray();

    $get = DB::table('users')->where('id', $id)->first();
    $get->profile = DB::table('usr_profile')->where('user_id', $id)->first();
    $get->profile->showname = (!empty($get->profile->display_name) && !is_null($get->profile->display_name) ? $get->profile->display_name : $get->username);
    $get->perm = $valid;
    if (empty($get->avatar) || $get->avatar == '') $get->avatar = '/img/noicon.webp';

    return $get;
  }

  public function getGroupName($id) {
    return DB::table('usr_perm_module')->join('usr_perm_id', 'usr_perm_id.perm_id', '=', 'usr_perm_module.id')->where('user_id', $id)->get(array('name'));
  }

  public function getGroupColours() {
    return DB::table('usr_perm_module')->select('id', 'colour_m', 'colour_f', 'colour_u')->get();
  }

  public function getUser ($id, $kero) {
    $check = $this->objAuth->checkLegit($kero);

    $valid = $this->objAuth->getPermissions($kero);
    $cols = $this->getGroupColours()->toArray();

    $get = DB::table('users')->where('id', $id)->first();
    $get->details = DB::table('usr_details')->where('user_id', $id)->first();
    $get->profile = DB::table('usr_profile')->where('user_id', $id)->first();
    $get->contacts = DB::table('usr_contacts')->where('user_id', $id)->first();
    $get->perm_id = DB::table('usr_perm_id')->where('user_id', $id)->first();
    $get->perm_module = DB::table('usr_perm_module')->where('usr_perm_id', $get->perm_id->usr_per_id)->first();
    if (is_null($get->profile->avatar) || empty($get->profile->avatar) || $get->profile->avatar == '') {
      $get->profile->avatar = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['HTTP_HOST'].'/img/noicon.webp';
    }
    else $get->profile->avatar = '/'.$get->profile->avatar;

    $get->profile->gender_name = '不明';
    if ($get->profile->gender == 1) $get->profile->gender_name = '男性';
    else if ($get->profile->gender == 2) $get->profile->gender_name = '女性';

    $get->details->reg_date = strftime('%Y年%m月%d日（%a）', $get->details->reg_date);
    $get->profile->showname = (!empty($get->profile->display_name) && !is_null($get->profile->display_name) ? $get->profile->display_name : $get->username);

    if ($id != $check) {
      unset($get->password);
      unset($get->kero_token);
      unset($get->salt);
    }

    if ($valid['usr_emailshow'] == 0 || $id != $check) unset($get->email);
    if ($valid['usr_ipshow'] == 0 || $id != $check) unset($get->profile->ip_address);
    if ($valid['usr_canwarn'] == 0 || $id != $check) unset($get->details->strikes);

    return $get;
  }

  public function getCountries () {
    $flags = DB::table('nhn_country')->orderBy('id', 'asc')->get();
    $res = array();

    foreach ($flags as $flag) {
      $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';

      $res[] = array(
        'value' => $flag->nameEng,
        'label' => $flag->name
      );
    }

    return $res;
  }

  public function avatarUpload(Request $r) {
    $check = $this->objAuth->checkLegit($r->kero_token);

    if ($check == 0) return 'Err!';
    else {
      $valid = $this->objAuth->getPermissions($r->kero_token);
      $user = 0;

      if ($valid['usr_editother'] == 1) $user = $r->id;
      else $user = $check;

      if ($valid['usr_editprofile'] == 1) {
        if (isset($r->filename)) {
          if (!is_dir('/usericon/'.$check)) {
            if (!mkdir('/usericon/'.$check, 0755, true)) return 'Could not make folder '.$check.'<br />';
          }

          $img_dir = '/usericon/'.$check.'/';
          $image = $img_dir . $r->filename;
          $imageFileType = array('image/png', 'image/jpeg', 'image/gif');

          if (!in_array($r->filetype, $imageFileType)) return "Only JPG, PNG, JPEG, and GIF are allowed.";

          $fname = '/usericon/'.$user.'/'.$r->filename;
          $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $r->thefile));
          Storage::disk('public')->put($fname, $data);

          return $r->filename;
        }
      }
      else return 'Permission denied.';
    }
  }

  public function getNotification (Request $r) { // /api/rpc/user/notification/get
    $check = $this->objAuth->checkLegit($r->kero_token);
    $res = null;

    if ($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', $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 addNotification(Request $r, $uid, $aid, $txt, $sec, $goto) {
    $check = $this->objAuth->checkLegit($r->kero_token);

    if ($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 delNotification(Request $r) {
    $check = $this->objAuth->checkLegit($r->kero_token);

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