<?php

namespace App\Http\Controllers\Home;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Engine;
// use Illuminate\Support\Facades\Log;

class CommentList extends Engine {
  private $engine;

  public function __construct () {
    $this->engine = new Engine();
  }

  public function index () {
    if (getPerms()['usr_ban'] != 1) return view('pages.site.notallowed', ['user' => $this->engine->user]);
    $get = DB::table('blg_comments')->orderBy('created', 'desc')->paginate(10);
    setlocale(LC_ALL, 'ja_JP.utf8');

    foreach ($get as $g) {
      if (!is_null($g->user_id)) {
        $g->username = DB::table('users')->select('username')->where('id', $g->user_id)->first()->username;
        $g->showName = '';
        $g->showCol = '';
        $g->perm_id = DB::table('usr_perm_id')->select('perm_id')->where('user_id', $g->user_id)->first()->perm_id;

        $p = DB::table('usr_profile')->select('gender', 'avatar', 'name_style', 'display_name')->where('user_id', $g->user_id)->first();
        $g->gender = $p->gender;
        $g->avatar = $p->avatar;
        $g->name_style = $p->name_style;
        $g->display_name = $p->display_name;

        if (!empty(userDetail($g->user_id))) {
          $det = userDetail($g->user_id);
          $g->user_id = $det['user_id'];
          $g->showname = $det['showname'];
          $g->showcol = $det['showcol'];
          $g->avatar = $det['avatar'];
        }

        
        unset($g->email);

        if (!empty($g->display_name)) $g->showname = $g->display_name;
        else $g->showname = $g->username;

        if (!empty($g->name_style)) $g->showcol = $g->name_style;
        else {
          foreach (getGroupColours() as $j) {
            if ($j->id == $g->perm_id) {
              if ($g->gender == 1) $g->showcol = $j->colour_m;
              else if ($g->gender == 2) $g->showcol = $j->colour_f;
              else $g->showcol = $j->colour_u;
            }
          }
        }

        $g->user = userDetail(null, DB::table('users')->select('kero_token')->where('id', $g->user_id)->first()->kero_token);
      }
      else {
        if (is_null($g->name)) $g->name = '名無しのテクニシャン';
      }

      if (!is_null($g->post_id) && $g->post_id != 0) {
        $g->url = '/blog/'.DB::table('blg_content')->where('id', $g->post_id)->first()->slug.'#comment-'.$g->id;
        $g->title = DB::table('blg_content')->where('id', $g->post_id)->first()->title;
      }
      else if (!is_null($g->video_id) && $g->video_id != '') {
        $g->url = '/video/play/'.$g->video_id.'#comment-'.$g->id;
        $g->title = DB::table('vid_video')->where('vid', $g->video_id)->first()->title;
      }

      $g->created = date('Y年m月d日 H:i:s', $g->created);
    }

    return view('pages.site.commentlist', ['res' => $get, 'user' => $this->engine->user]);
  }
}
