<?php
/**
 * app/controllers/admin/tokens.php
 *
 * This is the admin app/user tokens 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\Admin;

use TheTempusProject\Classes\Forms as TTPForms;
use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Houdini\Classes\Issues;
use TheTempusProject\Houdini\Classes\Navigation;
use TheTempusProject\Houdini\Classes\Components;
use TheTempusProject\Houdini\Classes\Forms;
use TheTempusProject\Classes\AdminController;
use TheTempusProject\Models\Token;
use TheTempusProject\Bedrock\Functions\Input;
use TheTempusProject\Bedrock\Functions\Check;
use TheTempusProject\Hermes\Functions\Redirect;
use TheTempusProject\Bedrock\Functions\Session;

class Tokens extends AdminController {
    public static $token;

    public function __construct() {
        parent::__construct();
        self::$title = 'Admin - Tokens';
        self::$token = new Token;
    }

    public function create() {
        if ( Input::exists( 'submit' ) ) {
            if ( !TTPForms::check( 'adminCreateToken' ) ) {
                Issues::add( 'error', [ 'There was an error with your token.' => Check::userErrors() ] );
            }
            if ( self::$token->create(
                Input::post( 'name' ),
                Input::post( 'notes' ),
                Input::post( 'token_type' )
            ) ) {
                Session::flash( 'success', 'Token Created' );
                Redirect::to( 'admin/tokens' );
            }
        }
        Views::view( 'admin.tokens.create' );
    }

    public function delete( $id = null ) {
        if ( self::$token->delete( [ $id ] ) ) {
            Session::flash( 'success', 'Token deleted.' );
        }
        Redirect::to( 'admin/tokens' );
    }

    public function edit( $id = null ) {
        $token = self::$token->findById( $id );
        if ( Input::exists( 'submit' ) ) {
            if ( !TTPForms::check( 'adminEditToken' ) ) {
                Issues::add( 'error', [ 'There was an error with your token.' => Check::userErrors() ] );
            } else {
                if ( self::$token->update(
                    $id,
                    Input::post( 'name' ),
                    Input::post( 'notes' ),
                    Input::post( 'token_type' )
                ) ) {
                    Session::flash( 'success', 'Token Updated' );
                    Redirect::to( 'admin/tokens' );
                }
            }
        }
        Forms::selectOption( $token->token_type );
        return Views::view( 'admin.tokens.edit', $token );
    }

    public function index() {
        return Views::view( 'admin.tokens.list', self::$token->listPaginated() );
    }

    public function view( $id = null ) {
        return Views::view( 'admin.tokens.view', self::$token->findById( $id ) );
    }
}
