<?php

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

class Profile extends Engine {
  private $engine;
  private $get;

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

  public function index ($id) {
    $this->get = $this->engine->getUser($id);
    if (!$this->get) return view('pages.site.notfound');
    return view('pages.site.profile', ['res' => $this->get]);
  }

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

    if ($check == 0) return 'Err!';
    else {
      $valid = getPerms();
      $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 edit ($id, Request $r) {
    $user = $this->engine->user;
    if ((getPerms()['usr_editother'] == 0 && $user != $id)) return view('pages.site.notallowed');
    $this->get = $this->engine->getUser($id);

    if (isset($r->submit)) {
      if (!is_null($r->password)) {
        if ($r->password != $r->password_check) $this->engine->err = '「パスワード」と「パスワード確認」が異なります。';
        else {
          $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
          $passwd = hash('sha256', $r->password . $salt);
          for ($round = 0; $round < 65536; $round++) { $passwd = hash('sha256', $passwd . $salt); }
          $eduserp = DB::table('users')->where('id', $id)->update(['password' => $passwd, 'salt' => $salt]);
          if (!$eduserp) $this->engine->err = 'パスワードの編集失敗。';
        }
      }

      $cheml = DB::table('users')->select('email')->where('id', $id)->first();

      if ($this->engine->err == '') {
        if ($cheml->email != $r->email) {
          $exeml = DB::table('users')->select('email')->where('email', $r->email)->count();
          if ($exeml > 0) $this->engine->err = '入力したメールアドレスはもう存在しています。';
          else {
            $edusere = DB::table('users')->where('id', $id)->update(['email' => $r->email]);
            if (!$edusere) $this->engine->err = 'メールアドレスの編集失敗。';
          }
        }
      }

      if ($this->engine->err == '') {
        $p = DB::table('usr_profile')->select('display_name', 'country', 'gender')->where('user_id', $id)->first();
        $edprofile = 1;
        if ($p->display_name != $r->display_name || $p->country != $r->country || $p->gender != $r->gender) {
          $edprofile = DB::table('usr_profile')->where('user_id', $id)->update([
            'display_name' => $r->display_name,
            'country' => $r->country,
            'gender' => $r->gender
          ]);
        }

        if (!$edprofile) $this->engine->err = '表示名、お国、又は性別の編集失敗。';
        else return redirect('/');
      }
    }

    if (!$this->get) return view('pages.site.notfound');
    if ($this->engine->user) return view('pages.site.profileedit', ['res' => $this->get, 'suc' => $this->engine->suc, 'err' => $this->engine->err]);
    return view('pages.site.notfound');
  }
}
