<?php

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

class Login extends Common {
  private $common;

  public function __construct () {
    $this->common = new Common;
  }

  public function index ($err=null) {
    if (isset($this->common->user['me']) && !is_null($this->common->user['me'])) {
      return redirect('/peertube/home');
    }

    $res = [
      'page' => 'login',
      'style' => 'login',
      'userinfo' => $this->common->user,
      'err' => $err
    ];

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

  public function login (Request $r) {
    if (isset($this->common->user['me']) && !is_null($this->common->user['me'])) {
      return redirect('/peertube/videos/local');
    }

    $param = [
      'client_id' => $this->common->user['local']->client_id,
      'client_secret' => $this->common->user['local']->client_secret,
      'grant_type' => 'password',
    ];

    if (isset($r->username) && isset($r->password)) {
      $param['username'] = $r->username;
      $param['password'] = $r->password;
    }
    else if (isset($r->refresh_token)) {
      $param['refresh_token'] = $r->refresh_token;
    }

    $res = $this->ptapi('/api/v1/users/token', http_build_query($param), 'post', 'x-www-form-urlencoded');
    $err = null;

    if (isset($res->access_token) && isset($res->refresh_token)) {
      setcookie('access_token', $res->access_token, time()+(int)$res->expires_in, '/', $_SERVER['HTTP_HOST'], 0, 1); // 24時間
      setcookie('refresh_token', $res->refresh_token, time()+(int)$res->refresh_token_expires_in, '/', $_SERVER['HTTP_HOST'], 0, 1); // 14日間

      return redirect('/peertube/videos/local');
    }

    return $this->index(isset($res->error) ? $res->error : '不正なエラー');
  }
}
