<?php
/**
 * app/controllers/api/auth.php
 *
 * This is the api authentication controller.
 *
 * @version 3.0
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */
namespace TheTempusProject\Controllers\Api;

use TheTempusProject\Classes\ApiController;
use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Models\Token;
use TheTempusProject\Models\User;
use TheTempusProject\Houdini\Classes\Template;
use TheTempusProject\Classes\Forms;
use TheTempusProject\Bedrock\Functions\Input;

class Login extends ApiController {
    public static $tokens;
    public static $user;

    public function __construct() {
        parent::__construct( false );
        self::$tokens = new Token;
        self::$user = new User;
        Template::addHeader( 'Access-Control-Allow-Origin: *' );
        Template::addHeader( 'Content-Type: application/json; charset=utf-8' );
    }

    public function index() {
        if ( ! Forms::check( 'apiLogin' ) ) {
            $responseType = 'error';
            $response = 'malformed input';
            return Views::view( 'api.response', ['response' => json_encode( [ $responseType => $response ], true )]);
        }
        $user = self::$user->authorize( Input::post( 'username' ), Input::post( 'password' ) );
        if ( ! $user ) {
            $responseType = 'error';
            $response = 'bad credentials';
            return Views::view( 'api.response', ['response' => json_encode( [ $responseType => $response ], true )]);
        }
        $responseType = 'token';
        $token = self::$tokens->findOrCreateUserToken( $user->ID, true );
        return Views::view( 'api.response', ['response' => json_encode( [ $responseType => $token ], true )]);
    }
}