<?php
/**
 * app/controllers/admin/users.php
 *
 * This is the users admin 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\Bedrock\Functions\Check;
use TheTempusProject\Bedrock\Functions\Input;
use TheTempusProject\Bedrock\Functions\Code;
use TheTempusProject\Bedrock\Functions\Hash;
use TheTempusProject\Houdini\Classes\Navigation;
use TheTempusProject\Houdini\Classes\Components;
use TheTempusProject\Houdini\Classes\Forms;
use TheTempusProject\Houdini\Classes\Issues;
use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Bedrock\Classes\Config;
use TheTempusProject\Classes\Forms as FormChecker;
use TheTempusProject\Classes\AdminController;
use TheTempusProject\Models\User;
use TheTempusProject\Models\Group;
use TheTempusProject\TheTempusProject as App;
use TheTempusProject\Houdini\Classes\Template;

class Users extends AdminController {
    public static $user;
    public static $group;

    public function __construct() {
        parent::__construct();
        self::$title = 'Admin - Users';
        self::$user = new User;
        self::$group = new Group;
    }

    public function create() {
        if ( Input::exists( 'submit' ) ) {
            if ( !FormChecker::check( 'createUser' ) ) {
                Issues::add( 'error', [ 'There was an error with your request.' => Check::userErrors() ] );
            } else {
                $fields = [
                    'username' => Input::post( 'username' ),
                    'password' => Hash::make( Input::post( 'password' ) ),
                    'email' => Input::post( 'email' ),
                    'userGroup' => Input::post( 'groupSelect' ),
                    'terms' => 0,
                ];
                if ( !Input::exists( 'confirmation' ) ) {
                    $fields['confirmed'] = 1;
                }
                if ( self::$user->create( $fields ) ) {
                    Issues::add( 'success', 'User Created' );
                    return $this->index();
                } else {
                    Issues::add( 'error', 'There was an error creating the user' );
                }
            }
        }
        $select = Forms::getSelectHtml(
            'groupSelect',
            self::$group->listGroupsSimple(),
            Config::getValue( 'group/defaultGroup' ),
        );
        Components::set( 'groupSelect', $select );
        Views::view( 'admin.users.create' );
    }

    public function delete( $id = null ) {
        if ( Input::exists( 'submit' ) ) {
            $id = Input::post( 'U_' );
        }
        if ( self::$user->delete( $id ) ) {
            Issues::add( 'success', 'User deleted' );
        } else {
            Issues::add( 'error', 'There was an error deleting user(s)' );
        }
        $this->index();
    }

    public function edit( $id = null ) {
        if ( !Check::id( $id ) ) {
            return Issues::add( 'error', 'Invalid user' );
        }
        $userData = self::$user->findById( $id );
        if ( in_array( $userData->groupName, self::$group::$protectedGroups ) ) {
            switch ( $userData->groupName ) {
                case 'Super':
                    if ( 'Super' !== App::$activeGroup->name ) {
                        Issues::add( 'error', 'You do not have permission to do that.' );
                        return $this->index();
                    }
                case 'Admin':
                    if ( 'Super' !== App::$activeGroup->name ) {
                        Issues::add( 'error', 'You do not have permission to do that.' );
                        return $this->index();
                    }
            }
        }

        if ( Input::exists( 'submit' ) ) {
            if ( !FormChecker::check( 'editUser' ) ) {
                Issues::add( 'error', [ 'There was an error with your request.' => Check::userErrors() ] );
            } else {
                $fields = [
                    'username' => Input::post( 'username' ),
                    'email' => Input::post( 'email' ),
                    'userGroup' => Input::post( 'groupSelect' ),
                ];
                if ( Input::exists( 'confirmed' ) ) {
                    $fields['confirmed'] = 1;
                } else {
                    if ( Input::exists( 'confirmation' ) ) {
                        $fields['confirmationCode'] = Code::genConfirmation();
                    }
                }
                if ( self::$user->update( $userData->ID, $fields ) ) {
                    Issues::add( 'success', 'User Updated.' );
                    return $this->index();
                } else {
                    Issues::add( 'notice', 'There was an error with your request, please try again.' );
                }
            }
        }
        if ( empty( $avatarLocation ) ) {
            $avatarLocation = $userData->prefs['avatar'];
        }
        if ( empty( $userGroup ) ) {
            $userGroup = $userData->userGroup;
        }
        Forms::selectRadio( 'confirmed', $userData->confirmed );

        $avatar = $this->getAvatar( 'avatar', $avatarLocation );
        Components::set( 'AvatarSettings', $avatar );
        
        $select = Forms::getSelectHtml(
            'groupSelect',
            self::$group->listGroupsSimple(),
            $userGroup,
        );
        Components::set( 'groupSelect', $select );
        Views::view( 'admin.users.edit', $userData );
    }

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

    public function view( $id = null ) {
        if ( !empty( $id ) ) {
            $userData = self::$user->findById( $id );
            if ( $userData !== false ) {
                return Views::view( 'admin.users.view', $userData );
            }
            Issues::add( 'error', 'User not found.' );
        }
        $this->index();
    }
    
    private function getAvatar( $name, $value ) {
        $fieldname = str_ireplace( '/', '-', $name );

        $html = '';
        $fieldHtml = '';
        $fieldHtml = Forms::getFileHtml( $fieldname );

        $html .= '<div class="mb-3 row">';
        $html .= '    <label for="' . $fieldname . '" class="col-lg-6 col-form-label text-end">' . ucfirst( $fieldname ) . '</label>';
        $html .= '    <div class="col-lg-2">';
        $html .= '        ' . $fieldHtml;
        $html .= '    </div>';
        $html .= '</div>';

        $html .= '<div class="mb-3 row">';
        $html .= '    <h4 class="col-lg-6 col-form-label text-end">Current Image</h4>';
        $html .= '    <div class="col-lg-2">';
        $html .= '        <img alt="User Avatar" src="{ROOT_URL}' . $value . '" class="img-circle img-fluid p-2 avatar-125">';
        $html .= '    </div>';
        $html .= '</div>';

        return Template::parse( $html );
    }
}
