<?php

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

class Login {
  public function index (Request $r) {
    if (isset($_COOKIE['kero_token'])) return redirect('');
    $res = array();
    $err = '';

    if (isset($r->username) && isset($r->password)) {
      $res = $this->login($r);
      if (isset($res['kero_token'])) return redirect('');
      $err = $res['err'];
    }

    return view('pages.site.login', ['res' => $res, 'err' => $err]);
  }

  public function login (Request $r) {
    if (!empty($r)) {
      $checkName = DB::table('users')->where('username', $r->username)->first();

      if ($checkName) {
        // $checkName = json_decode(json_encode($checkName), true);
        $checkPass = hash('sha256', $r->password . $checkName->salt);
        for ($round = 0; $round < 65536; $round++) $checkPass = hash('sha256', $checkPass . $checkName->salt);

        if (hash_equals($checkPass, $checkName->password)) {
          if (!$checkName->kero_token) {
            $checkName->kero_token = makeToken();
            DB::table('users')->where('id', $checkName->id)->update(['kero_token' => $checkName->kero_token]);
          }

          setcookie('kero_token', $checkName->kero_token, time()+157788000, '/', $_SERVER['HTTP_HOST'], 0, 1);
          return array('uid' => $checkName->id, 'kero_token' => $checkName->kero_token);
        }
      }
      return array('err' => 'ユーザ名又はパスワードを間違いました。');
    }

    return array('err' => 'フォームは空です。');
  }
}