<?php
/**
 * app/controllers/usercp.php
 *
 * This is the user control panel 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;

use TheTempusProject\Houdini\Classes\Template;
use TheTempusProject\Classes\Email;
use TheTempusProject\Bedrock\Functions\Code;
use TheTempusProject\Bedrock\Functions\Check;
use TheTempusProject\Bedrock\Functions\Input;
use TheTempusProject\Bedrock\Functions\Hash;
use TheTempusProject\Houdini\Classes\Components;
use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Houdini\Classes\Issues;
use TheTempusProject\Houdini\Classes\Navigation;
use TheTempusProject\TheTempusProject as App;
use TheTempusProject\Classes\Controller;
use TheTempusProject\Classes\Preferences;
use TheTempusProject\Classes\Forms;
use TheTempusProject\Hermes\Functions\Redirect;
use TheTempusProject\Bedrock\Functions\Session;

class Usercp extends Controller {
    public function __construct() {
        parent::__construct();
        if ( !App::$isLoggedIn ) {
            Session::flash( 'notice', 'You must be logged in to view this page!' );
            Redirect::home();
        }
        Template::noIndex();
    }

    public function email() {
        self::$title = 'Email Settings';
        $menu = Views::simpleView( 'nav.usercp', App::$userCPlinks );
        Navigation::activePageSelect( $menu, null, true, true );
        if ( App::$activeUser->confirmed != '1' ) {
            return Issues::add( 'notice', 'You need to confirm your email address before you can make modifications. If you would like to resend that confirmation link, please <a href="/register/resend">click here</a>', true );
        }
        if ( !Input::exists() ) {
            return Views::view( 'user_cp.email_change' );
        }
        if ( !Forms::check( 'changeEmail' ) ) {
            Issues::add( 'error', [ 'There was an error with your request.' => Check::userErrors() ] );
            return Views::view( 'user_cp.email_change' );
        }
        $code = Code::genConfirmation();
        self::$user->update(
            App::$activeUser->ID,
            [
                'confirmed' => 0,
                'email' => Input::post( 'email' ),
                'confirmationCode' => $code,
            ],
        );
        Email::send( App::$activeUser->email, 'emailChangeNotice', $code, [ 'template' => true ] );
        Email::send( Input::post( 'email' ), 'emailChange', $code, [ 'template' => true ] );
        Issues::add( 'notice', 'Email has been changed, please check your email to confirm it.' );
    }

    public function index() {
        self::$title = 'User Control Panel';
        $menu = Views::simpleView( 'nav.usercp', App::$userCPlinks );
        Navigation::activePageSelect( $menu, null, true, true );
        Views::view( 'profile', App::$activeUser );
    }

    public function password() {
        self::$title = 'Password Settings';
        $menu = Views::simpleView( 'nav.usercp', App::$userCPlinks );
        Navigation::activePageSelect( $menu, null, true, true );
        if ( !Input::exists() ) {
            return Views::view( 'user_cp.password_change' );
        }
        if ( !Hash::check( Input::post( 'curpass' ), App::$activeUser->password ) ) {
            Issues::add( 'error', 'Current password was incorrect.' );
            return Views::view( 'user_cp.password_change' );
        }
        if ( !Forms::check( 'changePassword' ) ) {
            Issues::add( 'error', [ 'There was an error with your request.' => Check::userErrors() ] );
            return Views::view( 'user_cp.password_change' );
        }
        self::$user->update(
            App::$activeUser->ID,
            [ 'password' => Hash::make( Input::post( 'password' ) ) ],
        );
        Email::send( App::$activeUser->email, 'passwordChange', null, [ 'template' => true ] );
        Issues::add( 'notice', 'Your Password has been changed!' );
    }

    public function settings() {
        self::$title = 'Preferences';
        $menu = Views::simpleView( 'nav.usercp', App::$userCPlinks );
        Navigation::activePageSelect( $menu, null, true, true );
        $prefs = new Preferences;
        $userPrefs = App::$activePrefs;
        if ( Input::exists( 'submit' ) ) {
            $fields = $prefs->convertFormToArray( true, false );
            self::$user->updatePrefs( $fields, App::$activeUser->ID );
            Issues::add( 'success', 'Your preferences have been updated.' );
            // if the image upload fails, need to fall back on original
            if ( empty( $fields['avatar'] ) ) {
                $fields['avatar'] = $userPrefs['avatar'];
            }
        } else {
            $fields = $userPrefs;
        }
        Components::set( 'AVATAR_SETTINGS', $fields['avatar'] );
        Components::set( 'PREFERENCES_FORM', $prefs->getFormHtml( $fields ) );
        Views::view( 'user_cp.settings', App::$activeUser );
    }

    public function updatePref() {
        Template::setTemplate( 'api' );
        if ( ! App::$isLoggedIn ) {
            return Views::view( 'api.response', ['response' => json_encode( [ 'error' => 'Not Logged In' ], true )]);
        }
        if ( ! Forms::check( 'updatePreference' ) ) {
            return Views::view( 'api.response', ['response' => json_encode( [ 'error' => Check::userErrors() ], true )]);
        }
        $name = Input::post( 'prefName' );
        $value = Input::post('prefValue' );

        if ( 'false' === $value ) {
            $value = false;
        } elseif ( 'true' === $value ) {
            $value = true;
        }

        if ( empty( Preferences::get( $name ) ) ) {
            return Views::view( 'api.response', ['response' => json_encode( [ 'error' => 'Unknown Preference' ], true )]);
        }

        $prefs = new Preferences;
        $fields1 = $prefs->convertFormToArray( true, false );
        $fields3 = $fields1;

        if ( isset( $fields1[ $name ] ) ) {
            $fields3[ $name ] = $value;
        }
        $result = self::$user->updatePrefs( $fields3, App::$activeUser->ID );

        return Views::view( 'api.response', ['response' => json_encode( $result, true )]);
    }
}
