<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Support\Facades\Log;

use App\Http\Controllers\AuthController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\PermissionController;

class SiteController extends Controller {
  private $objAuth;
  private $objUser;
  private $objPermission;
  private $valid;

  public function __construct () {
    $this->objAuth = new AuthController();
    $this->objUser = new UserController();
    $this->objPermission = new PermissionController();
    $this->valid = $this->objAuth->getPermissions((isset($_COOKIE['kero_token']) ? $_COOKIE['kero_token'] : ''));
  }

  public function getPosts ($ispost=1) {
    $ucol = $this->objUser->getGroupColours();

    $get = DB::table('blg_content')->where('isPost', $ispost)->orderBy('publish_date', 'desc')->get();
    setlocale(LC_ALL, 'ja_JP.utf8');

    foreach ($get as $g) {
      if ($this->valid['blg_addpost'] == 0 && $this->valid['blg_editpost'] == 0 && $g->public_status != 0) unset($g);
    }

    return $get;
  }

  public function getPost ($slug, $kero) {
    $ucol = $this->objUser->getGroupColours();

    if ($this->valid['blg_editpost']) {
      $get = DB::table('blg_content')
        ->join('users', 'blg_content.user_id', '=', 'users.id')
        ->join('usr_details', 'usr_details.user_id', '=', 'blg_content.user_id')
        ->join('usr_profile', 'usr_profile.user_id', '=', 'blg_content.user_id')
        ->join('usr_perm_id', 'usr_perm_id.user_id', '=', 'blg_content.user_id')
        ->where('isPost', 1)
        ->where('slug', $slug)
        ->get(array(
          'blg_content.id',
          'blg_content.user_id',
          'title',
          'slug',
          'post_date',
          'publish_date',
          'public_status',
          'message',
          'username',
          'perm_id',
          'gender',
          'avatar',
          'name_style',
          'display_name'
        ));
    }
    else {
      $get = DB::table('blg_content')
        ->join('users', 'blg_content.user_id', '=', 'users.id')
        ->join('usr_details', 'usr_details.user_id', '=', 'blg_content.user_id')
        ->join('usr_profile', 'usr_profile.user_id', '=', 'blg_content.user_id')
        ->join('usr_perm_id', 'usr_perm_id.user_id', '=', 'blg_content.user_id')
        ->where('public_status', 0)
        ->where('isPost', 1)
        ->where('slug', $slug)
        ->get(array(
          'blg_content.id',
          'blg_content.user_id',
          'title',
          'slug',
          'post_date',
          'publish_date',
          'public_status',
          'message',
          'username',
          'perm_id',
          'gender',
          'avatar',
          'name_style',
          'display_name'
        ));
    }

    $res = array();
    setlocale(LC_ALL, 'ja_JP.utf8');

    foreach ($get as $i) {
      $showName = '';
      $showCol = '';
      $showGroupName = '';
      $comments = DB::table('blg_comments')->where('post_id', $i->id)->orderBy('id', 'asc')->get();

      foreach ($comments as $k => $c) {
        if ($c->isShadow == 0) {
          if ($this->getIp() != $c->ipaddress) unset($comments[$k]);
        }
        else {
          unset($c->email);
          unset($c->ipaddress);
          unset($c->isShadow);
          $c->created = date('Y年m月d日 H:i:s', $c->created);
        }
      }

      if (!empty($i->display_name)) $showName = $i->display_name;
      else $showName = $i->username;

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

      $gname = $this->objUser->getGroupName($i->user_id);
      $showGroupName = $gname[0]->name;

      array_push($res, [
        'id' => $i->id,
        'user_id' => $i->user_id,
        'title' => $i->title,
        'slug' => $i->slug,
        'post_date' => strftime('%Y/%m/%d(%a) %H:%M:%S %Z', $i->post_date),
        'publish_date' => strftime('%Y/%m/%d(%a) %H:%M:%S %Z', $i->publish_date),
        'public_status' => $i->public_status,
        'comments' => $comments,
        'message' => $i->message,
        'gender' => $i->gender,
        'avatar' => $i->avatar,
        'showcol' => $showCol,
        'showname' => $showName
      ]);
    }

    return $res;
  }

  public function newComment (Request $r) {
    $com = $r->comment;
    $id = DB::table('blg_content')->select('id')->where('slug', $r->slug)->first()->id;
    $shadow = DB::table('blg_blacklist')->where('ipaddress', $this->getIp())->first();

    if ($shadow && !$shadow->isShadow) return array('status' => '0101FF', 'message' => '失礼しますが、あなたはBANされていましたので、コメントを保存できません。');
    $shadow = ($shadow ? 0 : 1);

    $add = DB::table('blg_comments')
      ->insertGetId([
        'post_id' => $id,
        'name' => $com['name'],
        'email' => $com['mail'],
        'message' => $com['text'],
        'created' => time(),
        'ipaddress' => $this->getIp(),
        'isShadow' => $shadow
      ]);

    // 返事だったら、メールを送って

    $res = DB::table('blg_comments')->select('id', 'name', 'created', 'message')->where('id', $add)->first();
    $res->created = date('Y年m月d日 H:i:s', $res->created);
    return array('status' => '010100', 'message' => 'OK', 'result' => $res);
  }

  public function getIp () {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP'];
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;
  }

  public function getPagesInMenu () {
    $get = DB::table('blg_content')
      ->select('title', 'slug')
      ->where('public_status', 0)
      ->where('isPost', 0)
      ->where('isMenu', 1)
      ->orderBy('sortorder', 'asc')
      ->get();

    $res = array();
    $key = 0;

    foreach ($get as $i) {
      array_push($res, ['key' => $key, 'title' => $i->title, 'slug' => $i->slug]);
      $key++;
    }

    return $res;
  }

  public function getPage ($slug, $kero) {
    if ($this->valid['blg_editpage'] == 1) {
      return DB::table('blg_content')
        ->select('id', 'title', 'slug', 'isMenu', 'public_status', 'message')
        ->where('isPost', 0)
        ->where('slug', $slug)
        ->orderBy('sortorder', 'asc')
        ->first();
    }
    else {
      return DB::table('blg_content')
        ->select('id', 'title', 'slug', 'isMenu', 'public_status', 'message')
        ->where('public_status', 0)
        ->where('isPost', 0)
        ->where('slug', $slug)
        ->orderBy('sortorder', 'asc')
        ->first();
    }
  }

  public function addContent ($bdl) {
    if (($this->valid['blg_addpost'] && $bdl['isPost'] == 1) || ($this->valid['blg_addpage'] && $bdl['isPost'] == 0)) {
      return DB::table('blg_content')->insert($bdl);
    }
    return 0;
  }

  public function editContent ($bdl) {
    if (($this->valid['blg_editpost'] && $bdl['isPost'] == 1) || ($this->valid['blg_editpage'] && $bdl['isPost'] == 0)) {
      return DB::table('blg_content')->where('slug', $bdl['slug'])->update($bdl);
    }
    return 0;
  }

  public function delContent ($bdl) {
    if (($this->valid['blg_delpost'] && $bdl['isPost'] == 1) || ($this->valid['blg_delpage'] && $bdl['isPost'] == 0)) {
      return DB::table('blg_content')->where('slug', $bdl['slug'])->delete();
    }
    return 0;
  }
}
