<?php
namespace Incoviba\common;

use Incoviba\Common\Alias\OldModel as Model;
use Carbon\Carbon;

/**
 *
 * @author Aldarien
 * @property int $id
 * @property int $user_id foreign=users.id
 * @property DateTime $time
 * @property string $selector
 * @property string $token
 * @property int $status length=1 default=1
 *
 */
class Auth extends Model
{
  public static $_table = 'logins';

  public function user()
  {
  	return $this->belongsTo(User::class, 'user_id')->findOne();
  }
  public function token($token = null)
  {
  	if ($token == null) {
  		return false;
  	}
  	$this->token = \password_hash($token, \PASSWORD_DEFAULT);
  }
  public function time($time = null)
  {
  	if ($time == null) {
  		return Carbon::parse($this->time, config('app.timezone'));
  	}
  	if (!\is_a($time, \DateTime::class)) {
  		$time = Carbon::parse($time, config('app.timezone'));
  	}
  	$this->time = $time;
  }
  public function save()
  {
  	if (!\is_string($this->time)) {
  		$this->time = $this->time->format('Y-m-d H:i:s');
  	}
    parent::save();
  }
  public function isIn()
  {
  	if ($this->status == 0) {
  		return false;
  	}
  	$now = Carbon::now(config('app.timezone'));
  	$diff = $now->diffAsCarbonInterval($this->time, true);
  	if ($diff->totalHours > config('app.login_hours')) {
  		return false;
  	}
  	return true;
  }
}
?>
