<?php
  
  namespace Api\Controllers\Auth;
  
  use Api\Core\Controller;
  use Api\Services\UserService;
  use PDO;
  
  class SessionController extends Controller
  {
    public function show($token)
    {
			$sessions = db()->prepare("SELECT * FROM AccountSessions WHERE loginToken = ? AND expiryDate > ?");
			$sessions->execute([$token, date('Y-m-d H:i:s')]);
			$sessions = $sessions->fetch(PDO::FETCH_ASSOC);
			
			if (!$sessions) {
				api()->error('SESSION_NOT_FOUND', 'Session not found!');
			}
			
      api()->success();
    }
    
    public function store()
    {
			validate([
				'userID' => 'required',
				'ip' => 'required',
				'expires' => 'nullable',
			]);
			
	    $user = UserService::getByID(input('userID'));
	    if (!$user) api()->notFound('USER_NOT_FOUND', 'User not found!');
	    
	    $loginToken = md5(uniqid(mt_rand(), true));
			
			if (input('expires') && strtotime(input('expires')) > time()) {
				$expiryDate = input('expires');
			} else {
				$expiryDate = date('Y-m-d H:i:s', strtotime('+30 days'));
			}
			
			$session = db()->prepare("INSERT INTO AccountSessions (accountID, loginToken, creationIP, expiryDate, creationDate) VALUES (?, ?, ?, ?, ?)");
			$session->execute([$user['id'], $loginToken, input('ip'), $expiryDate, date('Y-m-d H:i:s')]);
			
      api()->success([
				'token' => $loginToken,
      ]);
    }
  }