<?php
// require login
$Auth->requireUser(WEB_ROOT . '/login.' . SITE_CONFIG_PAGE_EXTENSION);

// load user
$user = UserPeer::loadUserById($Auth->id);
if(!$user)
{
    coreFunctions::redirect(WEB_ROOT);
}
if(isset($_REQUEST['s']))
{
    notification::setSuccess(t("account_lock_activation_success_message", "Account successfully secured."));
}
if(isset($_REQUEST['ss']))
{
    notification::setSuccess(t("account_updated_success_message", "Account details successfully updated"));
}
if(isset($_REQUEST['f']))
{
    notification::setSuccess(t("account_lock_activation_failure_message", "Account could not be secured at this time, please try again later."));
}
if(isset($_REQUEST['us']))
{
    notification::setSuccess(t("account_lock_deactivation_success_message", "Account successfully unlocked."));
}
if(isset($_REQUEST['uf']))
{
    notification::setSuccess(t("account_lock_deactivation_failure_message", "Account could not be unlocked at this time, please try again later."));
}
if(isset($_REQUEST['uc']))
{
    notification::setError(t("account_lock_deactivation_code_mismatch", "Account could not be unlocked as the code is incorrect."));
}
if(isset($_REQUEST['e']))
{
    notification::setSuccess(t("account_lock_resend_email_confirm_message", "The email containing the unlock code has been emailed to the registered email account."));
}
// setup page
define("PAGE_NAME", t("account_edit_page_name", "Account Details"));
define("PAGE_DESCRIPTION", t("account_edit_meta_description", "Account details"));
define("PAGE_KEYWORDS", t("account_edit_meta_keywords", "details, account, short, url, user"));
define("SELECTED_NAVIGATION_LINK", "settings");

// get account stats
$totalFreeSpace = UserPeer::getAvailableFileStorage($Auth->id);
$totalActiveFiles = file::getTotalActiveFilesByUser($Auth->id);
$totalDownloads = file::getTotalDownloadsByUserOwnedFiles($Auth->id);
$lockStatus = coreFunctions::getUsersAccountLockStatus($Auth->id);

// setup keys
$key1 = '';
$key2 = '';
$accountAPIKeys = $db->getRow('SELECT key_public, key_secret FROM apiv2_api_key WHERE user_id = :user_id LIMIT 1', array('user_id' => $Auth->id));
if($accountAPIKeys)
{
    $key1 = $accountAPIKeys['key_public'];
    $key2 = $accountAPIKeys['key_secret'];
}

// activate security lock
if(isset($_REQUEST['secureAccount']) && (int) $_REQUEST['secureAccount'])
{
    // Generate the locking Hash
    $lockHash = coreFunctions::generateSecurityLockHash();

    // Update the database
    $db = Database::getDatabase();
    $rs = $db->query("UPDATE users SET accountLockStatus = 1, accountLockHash = " . $db->quote($lockHash) . " WHERE id = " . (int) $Auth->id);
    if($rs && (!notification::isErrors()))
    {
        // Send email to the registered account
        $subject = t('lock_account_email_subject', 'Security lock details for [[[SITE_NAME]]]', array('SITE_NAME' => SITE_CONFIG_SITE_NAME));
        $replacements = array(
            'FIRST_NAME' => $user->firstname,
            'SITE_NAME' => SITE_CONFIG_SITE_NAME,
            'UNLOCK_CODE' => $lockHash
        );
        $defaultContent = "Dear [[[FIRST_NAME]]],<br/><br/>";
        $defaultContent .= "Your account on [[[SITE_NAME]]] has been locked as per your request. Use the code below to unlock your account:<br/><br/>";
        $defaultContent .= "<strong>Unlock code:</strong> [[[UNLOCK_CODE]]]<br/><br/>";
        $defaultContent .= "Feel free to contact us if you need any support with your account.<br/><br/>";
        $defaultContent .= "Regards,<br/>";
        $defaultContent .= "[[[SITE_NAME]]] Admin";
        $htmlMsg = t('lock_account_email_content', $defaultContent, $replacements);

        coreFunctions::sendHtmlEmail($user->email, $subject, $htmlMsg, SITE_CONFIG_DEFAULT_EMAIL_ADDRESS_FROM, strip_tags(str_replace("<br/>", "\n", $htmlMsg)));
        coreFunctions::redirect(WEB_ROOT . '/account_edit.html?s=1');
    }
    else
    {
        coreFunctions::redirect(WEB_ROOT . '/account_edit.html?f=1');
    }
}

if(isset($_REQUEST['unlockAccount']) && (int) $_REQUEST['unlockAccount'])
{
    $accountCode = trim($_REQUEST['accountCode']);
    if(!$accountCode)
    {
        notification::setError(t("account_lock_deactivation_no_code_message", "Please enter the unlock code and try again."));
    }

    if(!notification::isErrors())
    {
        // get the unlock code from the DB
        $unlockCode = $db->getRow("SELECT accountLockHash FROM users WHERE id = " . (int) $Auth->id . " AND accountLockStatus = '1' LIMIT 1");
        if($unlockCode)
        {
            // Codes match, continue to unlock account
            if($accountCode === $unlockCode['accountLockHash'])
            {
                $rs = $db->query("UPDATE users SET accountLockStatus = 0, accountLockHash = '' WHERE id = " . (int) $Auth->id . ' LIMIT 1');
                if($rs)
                {
                    coreFunctions::redirect(WEB_ROOT . '/account_edit.html?us=1');
                }
            }
            else
            {
                coreFunctions::redirect(WEB_ROOT . '/account_edit.html?uc=1');
            }
        }
        else
        {
            coreFunctions::redirect(WEB_ROOT . '/account_edit.html?uf=1');
        }
    }
}

if(isset($_REQUEST['resendCode']) && (int) $_REQUEST['resendCode'])
{
    // Send email to the registered account
    $details = $db->getRow("SELECT accountLockHash FROM users WHERE id = " . (int) $Auth->id . " LIMIT 1");

    $subject = t('lock_account_email_subject', 'Security lock details for [[[SITE_NAME]]]', array('SITE_NAME' => SITE_CONFIG_SITE_NAME));
    $replacements = array(
        'FIRST_NAME' => $user->firstname,
        'SITE_NAME' => SITE_CONFIG_SITE_NAME,
        'UNLOCK_CODE' => $details['accountLockHash']
    );
    $defaultContent = "Dear [[[FIRST_NAME]]],<br/><br/>";
    $defaultContent .= "Your account on [[[SITE_NAME]]] has been locked as per your request. Use the code below to unlock your account:<br/><br/>";
    $defaultContent .= "<strong>Unlock code:</strong> [[[UNLOCK_CODE]]]<br/><br/>";
    $defaultContent .= "Feel free to contact us if you need any support with your account.<br/><br/>";
    $defaultContent .= "Regards,<br/>";
    $defaultContent .= "[[[SITE_NAME]]] Admin";
    $htmlMsg = t('lock_account_email_content', $defaultContent, $replacements);

    coreFunctions::sendHtmlEmail($user->email, $subject, $htmlMsg, SITE_CONFIG_DEFAULT_EMAIL_ADDRESS_FROM, strip_tags(str_replace("<br/>", "\n", $htmlMsg)));
    coreFunctions::redirect(WEB_ROOT . '/account_edit.html?e=1');
}

// update avatar
if(isset($_REQUEST['submitav']) && (int) $_REQUEST['submitav'])
{
    $uploadedAvatar = null;
    if((isset($_FILES['avatar']['tmp_name'])) && (strlen($_FILES['avatar']['tmp_name'])))
    {
        $uploadedAvatar = $_FILES['avatar'];
    }
    $removeAvatar = false;
    if((isset($_REQUEST['removeAvatar'])) && ((int) $_REQUEST['removeAvatar'] == 1))
    {
        $removeAvatar = true;
    }


    if(!notification::isErrors())
    {
        if($uploadedAvatar)
        {
            // check filesize
            $maxAvatarSize = 1024 * 1024 * 5;
            if($uploadedAvatar['size'] > ($maxAvatarSize))
            {
                notification::setError(t("account_edit_avatar_is_too_large", "The uploaded image can not be more than [[[MAX_SIZE_FORMATTED]]]", array('MAX_SIZE_FORMATTED' => coreFunctions::formatSize($maxAvatarSize))));
            }
            else
            {
                // make sure it's an image
                $imagesizedata = @getimagesize($uploadedAvatar['tmp_name']);
                if($imagesizedata === FALSE)
                {
                    //not image
                    notification::setError(t("account_edit_avatar_is_not_an_image", "Your avatar must be a jpg, png or gif image."));
                }
            }
        }
    }



    // update the account
    if(!notification::isErrors())
    {


        $db = Database::getDatabase(true);
        $rs = $db->query('UPDATE users SET title = :title, firstname = :firstname, lastname = :lastname, email = :email, languageId = :languageId, privateFileStatistics = :privateFileStatistics, isPublic = :isPublic WHERE id = :id', array('title' => $title, 'firstname' => $firstname, 'lastname' => $lastname, 'email' => $emailAddress, 'id' => $Auth->id, 'languageId' => $languageId, 'privateFileStatistics' => $privateFileStatistics, 'isPublic' => $filePrivacy));
        if($rs)
        {
            // save avatar
            $src = null;
            if($uploadedAvatar)
            {
                // convert all images to jpg
                $imgInfo = getimagesize($uploadedAvatar['tmp_name']);
                switch($imgInfo[2])
                {
                    case IMAGETYPE_GIF: $src = imagecreatefromgif($uploadedAvatar['tmp_name']);
                        break;
                    case IMAGETYPE_JPEG: $src = imagecreatefromjpeg($uploadedAvatar['tmp_name']);
                        break;
                    case IMAGETYPE_PNG: $src = imagecreatefrompng($uploadedAvatar['tmp_name']);
                        break;
                    default: $src = null;
                }
            }

            // if we've loaded the image store it as jpg
            if(($src) || ($removeAvatar == true))
            {
                ob_start();
                imagejpeg($src, null, 100);
                $imageData = ob_get_contents();
                ob_end_clean();
                $avatarCachePath = 'user/' . (int) $Auth->id . '/profile';

                // delete any existing avatar files including generate cache
                if(file_exists(CACHE_DIRECTORY_ROOT . '/' . $avatarCachePath))
                {
                    $files = coreFunctions::getDirectoryListing(CACHE_DIRECTORY_ROOT . '/' . $avatarCachePath);
                    if(COUNT($files))
                    {
                        foreach($files AS $file)
                        {
                            @unlink($file);
                        }
                    }
                }

                if($src)
                {
                    // save new file
                    cache::saveCacheToFile($avatarCachePath . '/avatar_original.jpg', $imageData);
                }
            }

            coreFunctions::redirect(WEB_ROOT . '/account_edit.html?ss=1');
            //notification::setSuccess(t("account_updated_success_message", "Account details successfully updated"));
        }
        else
        {
            notification::setError(t("problem_updating_your_account_try_again_later", "There was a problem updating your account, please try again later"));
        }
    }
}

// update user
if(isset($_REQUEST['submitme']) && (int) $_REQUEST['submitme'])
{
    // validation
    $title = trim($_REQUEST['title']);
    $firstname = trim($_REQUEST['firstname']);
    $lastname = trim($_REQUEST['lastname']);
    $emailAddress = trim(strtolower($_REQUEST['emailAddress']));
    $password = trim($_REQUEST['password']);
    $passwordConfirm = trim($_REQUEST['passwordConfirm']);
    $languageId = null;
    $filePrivacy = (int) $_REQUEST['isPublic'];
    if(isset($_REQUEST['languageId']))
    {
        $languageId = (int) $_REQUEST['languageId'];
    }
    $privateFileStatistics = (int) $_REQUEST['privateFileStatistics'];

    // pickup api keys
    $key1 = trim($_REQUEST['key1']);
    $key2 = trim($_REQUEST['key2']);

    if(pluginHelper::pluginEnabled('newsletters')) {
        $marketingEmails = (int)isset($_REQUEST['marketingEmails'])?(int)$_REQUEST['marketingEmails']:0;
    }

    if(!strlen($title))
    {
        notification::setError(t("please_enter_your_title", "Please enter your title"));
    }
    elseif(!strlen($firstname))
    {
        notification::setError(t("please_enter_your_firstname", "Please enter your firstname"));
    }
    elseif(!strlen($lastname))
    {
        notification::setError(t("please_enter_your_lastname", "Please enter your lastname"));
    }
    elseif(!strlen($emailAddress))
    {
        notification::setError(t("please_enter_your_email_address", "Please enter your email address"));
    }
    elseif(!validation::validEmail($emailAddress))
    {
        notification::setError(t("your_email_address_is_invalid", "Your email address is invalid"));
    }
    elseif(_CONFIG_DEMO_MODE == true)
    {
        notification::setError(t("no_changes_in_demo_mode"));
    }
    else
    {
        $checkEmail = UserPeer::loadUserByEmailAddress($emailAddress);
        if(($checkEmail) && ($checkEmail->id != $Auth->id))
        {
            // username exists
            notification::setError(t("email_address_already_exists", "Email address already exists on another account"));
        }
        else
        {
            // check password if one set
            if(strlen($password))
            {
                if($password != $passwordConfirm)
                {
                    notification::setError(t("your_password_confirmation_does_not_match", "Your password confirmation does not match"));
                }
                else
                {
                    $passValid = passwordPolicy::validatePassword($password);
                    if(is_array($passValid))
                    {
                        notification::setError(implode('<br/>', $passValid));
                    }
                }
            }
        }
    }



    if(!notification::isErrors())
    {
        if(strlen($key1) || strlen($key2))
        {
            // make sure keys are 64 characters in length
            if((strlen($key1) != 64) || (strlen($key2) != 64))
            {
                notification::setError(t("account_api_keys_not_correct_length", "API keys should be 64 characters in length."));
            }
        }
    }

    // update the account
    if(!notification::isErrors())
    {
        // if password changed send confirmation notice to user
        if(SITE_CONFIG_SECURITY_SEND_USER_EMAIL_ON_PASSWORD_CHANGE == 'yes')
        {
            if(strlen($password))
            {
                $subject = t('password_change_email_subject', 'Password changed for account on [[[SITE_NAME]]]', array('SITE_NAME' => SITE_CONFIG_SITE_NAME));

                $replacements = array(
                    'FIRST_NAME' => $user->firstname,
                    'SITE_NAME' => SITE_CONFIG_SITE_NAME,
                    'WEB_ROOT' => WEB_ROOT,
                    'USERNAME' => $user->username,
                );
                $defaultContent = "Dear [[[FIRST_NAME]]],<br/><br/>";
                $defaultContent .= "This is a courtesy email notifying you that your account password on [[[SITE_NAME]]] has been changed.<br/><br/>";
                $defaultContent .= "If you didn't change your password, please contact us immediately. Otherwise just ignore this email.<br/><br/>";
                $defaultContent .= "<strong>Url:</strong> <a href='[[[WEB_ROOT]]]'>[[[WEB_ROOT]]]</a><br/>";
                $defaultContent .= "<strong>Username:</strong> [[[USERNAME]]]<br/><br/>";
                $defaultContent .= "Feel free to contact us if you need any support with your account.<br/><br/>";
                $defaultContent .= "Regards,<br/>";
                $defaultContent .= "[[[SITE_NAME]]] Admin";
                $htmlMsg = t('password_change_email_content', $defaultContent, $replacements);

                coreFunctions::sendHtmlEmail($user->email, $subject, $htmlMsg, SITE_CONFIG_DEFAULT_EMAIL_ADDRESS_FROM, strip_tags(str_replace("<br/>", "\n", $htmlMsg)));
            }
        }

        // if email changed send confirmation notice to user
        if(SITE_CONFIG_SECURITY_SEND_USER_EMAIL_ON_EMAIL_CHANGE == 'yes')
        {
            if($emailAddress != $user->email)
            {
                $subject = t('email_change_email_subject', 'Email changed for account on [[[SITE_NAME]]]', array('SITE_NAME' => SITE_CONFIG_SITE_NAME));

                $replacements = array(
                    'FIRST_NAME' => $user->firstname,
                    'SITE_NAME' => SITE_CONFIG_SITE_NAME,
                    'WEB_ROOT' => WEB_ROOT,
                    'USERNAME' => $user->username,
                    'NEW_EMAIL' => $emailAddress,
                );
                $defaultContent = "Dear [[[FIRST_NAME]]],<br/><br/>";
                $defaultContent .= "This is a courtesy email notifying you that your account email address on [[[SITE_NAME]]] has been changed to [[[NEW_EMAIL]]].<br/><br/>";
                $defaultContent .= "If you didn't change your email address, please contact us immediately. Otherwise just ignore this email.<br/><br/>";
                $defaultContent .= "<strong>Url:</strong> <a href='[[[WEB_ROOT]]]'>[[[WEB_ROOT]]]</a><br/>";
                $defaultContent .= "<strong>Username:</strong> [[[USERNAME]]]<br/>";
                $defaultContent .= "<strong>New Email:</strong> [[[NEW_EMAIL]]]<br/><br/>";
                $defaultContent .= "Feel free to contact us if you need any support with your account.<br/><br/>";
                $defaultContent .= "Regards,<br/>";
                $defaultContent .= "[[[SITE_NAME]]] Admin";
                $htmlMsg = t('email_change_email_content', $defaultContent, $replacements);

                coreFunctions::sendHtmlEmail($user->email, $subject, $htmlMsg, SITE_CONFIG_DEFAULT_EMAIL_ADDRESS_FROM, strip_tags(str_replace("<br/>", "\n", $htmlMsg)));
            }
        }

        $db = Database::getDatabase(true);
        $rs = $db->query('UPDATE users SET title = :title, firstname = :firstname, lastname = :lastname, email = :email, languageId = :languageId, privateFileStatistics = :privateFileStatistics, isPublic = :isPublic WHERE id = :id', array('title' => $title, 'firstname' => $firstname, 'lastname' => $lastname, 'email' => $emailAddress, 'id' => $Auth->id, 'languageId' => $languageId, 'privateFileStatistics' => $privateFileStatistics, 'isPublic' => $filePrivacy));
        if($rs)
        {
            // do password
            if(strlen($password))
            {
                $rs = $db->query('UPDATE users SET password = :password WHERE id = :id', array('password' => Password::createHash($password), 'id' => $Auth->id));
            }

            // reset site language if updated
            if($languageId != null)
            {
                $languageName = $db->getValue("SELECT languageName FROM language WHERE isActive = 1 AND id = " . (int) $languageId . " LIMIT 1");
                if($languageName)
                {
                    $_SESSION['_t'] = $languageName;
                }
            }

            // update api keys
            $keepSame = $db->getValue('SELECT COUNT(id) AS total FROM apiv2_api_key WHERE key_public = :key_public AND key_secret = :key_secret AND user_id = :user_id LIMIT 1', array(
                'user_id' => (int)$Auth->id,
                'key_public' => $key1,
                'key_secret' => $key2,
            ));
            if(!$keepSame)
            {
                // delete any existing keys for the user
                $db->query('DELETE FROM apiv2_api_key WHERE user_id = :user_id LIMIT 1', array(
                    'user_id' => (int)$Auth->id,
                ));

                // add the new keys
                if(strlen($key1) && strlen($key2))
                {
                    $db->query('INSERT INTO apiv2_api_key (key_public, key_secret, user_id, date_created) VALUES (:key_public, :key_secret, :user_id, NOW())', array(
                        'user_id' => (int)$Auth->id,
                        'key_public' => $key1,
                        'key_secret' => $key2,
                    ));
                }
            }

            // update newsletter state
            if(pluginHelper::pluginEnabled('newsletters')) {
                // clear existing setting
                $db->query('DELETE FROM plugin_newsletter_unsubscribe WHERE user_id = :user_id LIMIT 1', array(
                    'user_id' => (int)$Auth->id,
                ));

                // unsubscribe
                if($marketingEmails === 0) {
                    $db->query('INSERT INTO plugin_newsletter_unsubscribe (user_id, date_unsubscribed) VALUES (:user_id, NOW())', array(
                        'user_id' => (int)$Auth->id,
                    ));
                }
            }

            coreFunctions::redirect(WEB_ROOT . '/account_edit.html?ss=1');
            //notification::setSuccess(t("account_updated_success_message", "Account details successfully updated"));
        }
        else
        {
            notification::setError(t("problem_updating_your_account_try_again_later", "There was a problem updating your account, please try again later"));
        }
    }
}
else
{
    $title = $user->title;
    $firstname = $user->firstname;
    $lastname = $user->lastname;
    $emailAddress = $user->email;
    $languageId = $user->languageId;
    $isPublic = $user->isPublic;
    if($languageId == null)
    {
        $languageId = $db->getValue("SELECT id FROM language WHERE isActive = 1 AND languageName = '" . $db->escape(trim($_REQUEST['_t'])) . "' LIMIT 1");
    }
    $privateFileStatistics = $user->privateFileStatistics;

    // get newsletter state
    if(pluginHelper::pluginEnabled('newsletters')) {
        $marketingEmails = (int)!$db->getValue("SELECT COUNT(*) AS total FROM plugin_newsletter_unsubscribe WHERE user_id = ".$user->id." LIMIT 1");
    }
}

// check for existing avatar
$hasAvatar = false;
$avatarCachePath = 'user/' . (int) $Auth->id . '/profile/avatar_original.jpg';
if(cache::checkCacheFileExists($avatarCachePath))
{
    $hasAvatar = true;
}

// include header
require_once(SITE_TEMPLATES_PATH . '/partial/_header_file_manager.inc.php');

// file manager javascript
require_once(SITE_TEMPLATES_PATH . '/partial/_account_home_javascript.inc.php');

if(notification::isSuccess())
{
    echo templateFunctions::outputSuccess();
}
elseif(notification::isErrors())
{
    echo templateFunctions::outputErrors();
}
?>
<script>
    $(document).ready(function () {
        $(".showLostPass").click(function () {
            $(".lostPass").toggle(0,
                    function () {
                        $(".fa-plus-square-o").hide();
                    },
                    function () {
                        $("fa-minus-square-o").show();
                    });
        });
    });
    $('#settings').addClass('active');
    $('.dash .navbar-form').remove();
</script>
<div class="row section">
  <div class="col-md-12 entry">
    <h2><?php echo t("hg_profile", "Profile")?></h2>
  </div>
  <div class="clearfix"></div>
  <div class="accProfile">
    <div class="profile">
	    <div class="avatar">
		  <img src="<?php echo CORE_PAGE_WEB_ROOT; ?>/account_view_avatar.php?width=200&amp;height=200" class="img-circle" height="200">
		</div>
		<div class="info">
		  <h5><?php echo validation::safeOutputToScreen($Auth->getAccountScreenName()); ?></h5>
		  <p><?php echo isset($emailAddress) ? validation::safeOutputToScreen($emailAddress) : ''; ?></p>
		</div>
		<div class="static">
		  <div class="col-md-4 tile-stats">
		    <i class="la la-archive"></i>
			<div data-delay="0" data-duration="1500" data-decimals="2" data-postfix="&nbsp;<?php echo validation::safeOutputToScreen(coreFunctions::formatSize($totalActiveFileSize, 'ext')); ?>" data-end="<?php echo validation::safeOutputToScreen(coreFunctions::formatSize($totalActiveFileSize, 'size')); ?>" data-start="0" class="num">-</div>
			<p<?php echo t("hg_used_storage", ">used storage")?></p>
		  </div>
		  <div class="col-md-4 tile-stats">
		    <i class="la la-files-o"></i>
			<div data-delay="0" data-duration="1500" data-end="<?php echo validation::safeOutputToScreen($totalActiveFiles); ?>" data-start="0" class="num">-</div>
			<p><?php echo t("hg_total_files", "total files")?></p>
		  </div>
		  <div class="col-md-4 tile-stats">
		    <i class="la la-download"></i>
			<div data-delay="0" data-duration="1500" data-end="<?php echo validation::safeOutputToScreen($totalDownloads); ?>" data-start="0" class="num">-</div>
			<p><?php echo t("hg_downloads", "downloads")?></p>
		  </div>
		</div>
		<div class="clearfix"></div>
		<div class="col-md-8">
		<form role="form" id="fava" action="<?php echo WEB_ROOT; ?>/account_edit.<?php echo SITE_CONFIG_PAGE_EXTENSION; ?>" method="POST" enctype="multipart/form-data">
		  <?php
                            // do plugin includes, i.e. override avatar with social login one
                            $params = pluginHelper::includeAppends('account_avatar.php', array('photoURL' => null));
                            if(strlen($params['photoURL']) == 0)
                            {
                                ?>

                                        <input type="file" class="hidden" id="avatar" name="avatar">
          <label for="avatar" <?php if($lockStatus == 0): ?><?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> class="btn btn-primary btn-block btn-upload"><i class="la la-upload"></i> <?php echo t("hg_change_avat", "Change Avatar")?></label>
		<?php if($hasAvatar == true): ?>

                                <?php endif; ?>

                                <?php
                            }
                            ?>
		  <input type="hidden" value="1" name="submitav"/>
		</form>
		</div>

	</div>
	<form role="form" action="<?php echo WEB_ROOT; ?>/account_edit.<?php echo SITE_CONFIG_PAGE_EXTENSION; ?>" method="POST" enctype="multipart/form-data">
	<div class="settings">
      <!-- Nav tabs -->
      <ul class="nav nav-tabs" role="tablist">
          <li role="presentation" class="active"><a href="#det" aria-controls="det" role="tab" data-toggle="tab"><i class="la la-user"></i> <span class="hidden-xs"><?php echo t("hg_details", "Details")?></span></a></li>
          <li role="presentation"><a href="#priv" aria-controls="priv" role="tab" data-toggle="tab"><i class="la la-shield"></i> <span class="hidden-xs"><?php echo t("hg_pp", "Privacy")?></span></a></li>
          <li role="presentation"><a href="#pass" aria-controls="pass" role="tab" data-toggle="tab"><i class="la la-unlock"></i> <span class="hidden-xs"><?php echo t("hgpassword_", "Password")?></span></a></li>
          <li role="presentation"><a href="#api" aria-controls="api" role="tab" data-toggle="tab"><i class="la la-code"></i> <span class="hidden-xs"><?php echo t("hg_api", "API")?></span></a></li>
      </ul>
      <div class="tab-content">
        <div role="tabpanel" class="tab-pane fade in active" id="det">
		    <div class="col-md-6">
			  <div class="form-group">
			    <label class="control-label" for="title"><?php echo t("title", "Title"); ?></label>
			    <select <?php if($lockStatus == 0): ?>id="title" name="title"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> class="form-control" tabindex="1">
                  <option value="Mr" <?php echo ($title == 'Mr') ? 'SELECTED' : ''; ?>><?php echo t('title_mr', 'Mr'); ?></option>
                  <option value="Ms" <?php echo ($title == 'Ms') ? 'SELECTED' : ''; ?>><?php echo t('title_ms', 'Ms'); ?></option>
                  <option value="Mrs" <?php echo ($title == 'Mrs') ? 'SELECTED' : ''; ?>><?php echo t('title_mrs', 'Mrs'); ?></option>
                  <option value="Miss" <?php echo ($title == 'Miss') ? 'SELECTED' : ''; ?>><?php echo t('title_miss', 'Miss'); ?></option>
                  <option value="Dr" <?php echo ($title == 'Dr') ? 'SELECTED' : ''; ?>><?php echo t('title_dr', 'Dr'); ?></option>
                  <option value="Pro" <?php echo ($title == 'Pro') ? 'SELECTED' : ''; ?>><?php echo t('title_pro', 'Pro'); ?></option>
                </select>
			  </div>
			</div>
			<div class="clearfix"></div>
			<div class="col-md-6">
			  <div class="form-group">
			    <label class="control-label" for="firstname"><?php echo t("firstname", "Firstname"); ?></label>
				<input <?php if($lockStatus == 0): ?>id="firstname" name="firstname"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> type="text" tabindex="2" value="<?php echo isset($firstname) ? validation::safeOutputToScreen($firstname) : ''; ?>" class="form-control">
			  </div>
			</div>
			<div class="col-md-6">
			  <div class="form-group">
			    <label class="control-label" for="lastname"><?php echo t("lastname", "Lastname"); ?></label>
				<input <?php if($lockStatus == 0): ?>id="lastname" name="lastname"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> type="text" tabindex="3" value="<?php echo isset($lastname) ? validation::safeOutputToScreen($lastname) : ''; ?>" class="form-control">
			  </div>
			</div>
			<div class="clearfix"></div>
			<div class="col-md-6">
			  <div class="form-group">
			    <label class="control-label" for="emailAddress"><?php echo t("email_address", "Email Address"); ?></label>
				<input <?php if($lockStatus == 0): ?>id="emailAddress" name="emailAddress"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> type="text" tabindex="4" value="<?php echo isset($emailAddress) ? validation::safeOutputToScreen($emailAddress) : ''; ?>" class="form-control">
			  </div>
			</div>
			<?php
            // language selector
            if(SITE_CONFIG_LANGUAGE_USER_SELECT_LANGUAGE == 'yes')
            {
                $activeLanguages = $db->getRows("SELECT id, languageName FROM language WHERE isActive = 1 ORDER BY languageName ASC");
                if(COUNT($activeLanguages))
                {
                    ?>
                    <div class="col-md-6">
					  <div class="form-group">
                        <label class="control-label" for="languageId"><?php echo t("language", "Language"); ?></label>
                        <select <?php if($lockStatus == 0): ?>id="languageId" name="languageId"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> class="form-control" tabindex="7">
                          <?php
                          foreach($activeLanguages AS $activeLanguage)
                          {
                            echo '<option value="' . $activeLanguage['id'] . '"';
                            if($languageId == $activeLanguage['id'])
                            {
                                echo ' SELECTED';
                            }
                                echo '>' . validation::safeOutputToScreen($activeLanguage['languageName']) . '</option>';
                            }
                          ?>
                        </select>
                      </div>
					</div>
                    <?php
                }
            }
            ?>
			<div class="col-md-6">
			  <div class="form-group">
			    <label class="control-label" for="privateFileStatistics"><?php echo t("file_statistics", "File Statistics"); ?></label>
                <select <?php if($lockStatus == 0): ?>id="privateFileStatistics" name="privateFileStatistics"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> class="form-control" tabindex="8">
                    <?php
                    $optionsArr = array('0' => t('settings_statistics_public', 'Publicly Accessible (using ~s on url)'), '1' => t('settings_statistics_private', 'Private (only via your account)'));
                    foreach($optionsArr AS $k => $option)
                    {
                        echo '<option value="' . $k . '"';
                        if($privateFileStatistics == $k)
                        {
                            echo ' SELECTED';
                        }
                        echo '>' . validation::safeOutputToScreen($option) . '</option>';
                    }
                    ?>
                </select>
			  </div>
			</div>
			<div class="clearfix"></div>
			<div class="col-md-4 col-md-offset-8 pt30">
			  <div class="form-group">
                <button class="btn btn-go btn-block" <?php if($lockStatus == 0): ?>type="submit"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?>><?php echo UCWords(t("update_account", "update account")); ?> <i class="la la-arrow-right"></i></button>
			  </div>
			</div>
		</div>
        <div role="tabpanel" class="tab-pane fade" id="priv">
		  <?php if(SITE_CONFIG_SECURITY_ACCOUNT_LOCK == 'yes'): ?>
		  <!-- Security Lock -->
		  <div class="col-md-4">
		    <div class="secBox">
			  <?php if($lockStatus == 1): ?>
			  <i class="la la-unlock"></i>
			  <p><?php echo t("hg_lock_sta", "Lock Status")?></p>
			  <h3><?php echo t("hg_locked", "Locked")?></h3>
			  <?php endif; ?>
			  <?php if($lockStatus == 0): ?>
			  <i class="la la-unlock-alt"></i>
			  <p><?php echo t("hg_lock_sta", "Lock Status")?></p>
			  <h3><?php echo t("hg_unlocked", "Unlocked")?></h3>
			  <?php endif; ?>
			</div>
		  </div>
		  <div class="col-md-8">
		    <div class="secnfo">
			  <p> <?php echo t('account_lock_long_description', 'The account security lock, when enabled, prevents your account details (name, email, password) from being edited, it also prevents files from being edited, moved and deleted.<br/><br/>To unlock your account, you will need the password which is emailed to your registered email address when the lock is enabled.'); ?></p>
			</div>
			<?php if($lockStatus == 0): ?>
              <button class="btn btn-primary btn-activate" <?php if($lockStatus == 0): ?>type="submit"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?>><i class="la la-key"></i> <?php echo UCWords(t("activate_security_lock", "Activate security lock")); ?></button>
			<?php endif; ?>
            <?php if($lockStatus == 1): ?>
			<form role="form" action="<?php echo WEB_ROOT; ?>/account_edit.<?php echo SITE_CONFIG_PAGE_EXTENSION; ?>" method="POST" enctype="multipart/form-data">
              <div class="form-group">
                <input type="hidden" value="1" name="resendCode"/>
                <button class="btn btn-primary btn-activate" type="submit"><i class="la la-key"></i> <?php echo UCWords(t("deactivate_security_lock_resend_code", "Resend security code")); ?> </button>
              </div>
            </form>
			<?php endif; ?>
		  </div>
		  <div class="clearfix"></div>
		  <?php if($lockStatus == 1): ?>
		  <form role="form" action="<?php echo WEB_ROOT; ?>/account_edit.<?php echo SITE_CONFIG_PAGE_EXTENSION; ?>" method="POST" enctype="multipart/form-data">
		    <div class="col-md-8">
			  <div class="form-group">
                <label class="control-label"><?php echo ucwords(t("account_edit_security_lock_code", "Account lock code")); ?></label>
                <input id="accountCode" name="accountCode" type="text" tabindex="99" value="" class="form-control"/>
              </div>
			</div>
			<div class="col-md-4 pt10">
			  <div class="form-group">
                <input type="hidden" value="1" name="unlockAccount"/>
                <button class="btn btn-block btn-deactivate" type="submit"><i class="la la-minus-circle"></i> <?php echo UCWords(t("deactivate_security_lock", "De-activate security lock")); ?></button>
              </div>
            </div>
		  </form>
		  <?php endif; ?>
          <!-- Security Lock -->
		  <div class="clearfix"></div>
		  <hr>
          <?php endif; ?>
		    <?php if(SITE_CONFIG_FORCE_FILES_PRIVATE == 'no'): ?>
              <div class="col-md-6">
				<div class="form-group">
                  <label class="control-label" for="isPublic"><?php echo ucwords(t("file_privacy", "File Privacy")); ?></label>
                  <select <?php if($lockStatus == 0): ?>id="isPublic" name="isPublic"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> class="form-control" tabindex="8" >
                    <?php if($user->isPublic == 1): ?>
                      <option value="1" selected="selected"><?php echo t('settings_public_files', 'All Files Publicly Accessible'); ?></option>
                      <option value="0"><?php echo t('settings_private_files', 'All Files Private (only via your account)'); ?></option>
                    <?php elseif($user->isPublic == 0): ?>
                      <option value="1"><?php echo t('settings_public_files', 'All Files Publicly Accessible'); ?></option>
                      <option value="0" selected="selected"><?php echo t('settings_private_files', 'All Files Private (only via your account)'); ?></option>
                    <?php endif; ?>
                  </select>
                </div>
			  </div>
              <div class="col-md-12">
                  <div class="form-group">
                      <label class="control-label"><?php echo t('receive_occasional_email', 'Receive Occational Emails'); ?></label>
                      <div class="checkbox checkbox-primary">
                          <input type="checkbox" id="marketingEmails" name="marketingEmails" value="1" <?php echo ($marketingEmails === 1)?'CHECKED':''; ?> />
                          <label for="marketingEmails">
                              <?php echo t('receive_occasional_email_text', 'Receive occasional marketing emails from us. We\ll never share your details with anyone else.'); ?>
                          </label>
                      </div>
                  </div>
              </div>

			<div class="clearfix"></div>
			<div class="col-md-4 col-md-offset-8 pt30">
			  <div class="form-group">
                <button class="btn btn-go btn-block" <?php if($lockStatus == 0): ?>type="submit"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?>><?php echo UCWords(t("update_account-p", "update privacy")); ?> <i class="la la-arrow-right"></i></button>
			  </div>
			</div>
			<?php endif; ?>
		</div>
        <div role="tabpanel" class="tab-pane fade" id="pass">
			<div class="col-md-6">
			  <div class="form-group">
                <label class="control-label" for="password"><?php echo t("change_password", "Change Password"); ?></label>
                <input <?php if($lockStatus == 0): ?> id="password" name="password"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> type="password" tabindex="5" value="" class="form-control" />
              </div>
			</div>
			<div class="col-md-6">
			  <div class="form-group">
                <label class="control-label" for="passwordConfirm"><?php echo t("confirm_password_edit", "Confirm Password"); ?></label>
                <input <?php if($lockStatus == 0): ?> id="passwordConfirm" name="passwordConfirm"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> type="password" tabindex="6" value="" class="form-control" />
              </div>
			</div>
			<div class="clearfix"></div>
			<div class="col-md-4 col-md-offset-8 pt30">
			  <div class="form-group">
                <button class="btn btn-go btn-block" <?php if($lockStatus == 0): ?> type="submit" <?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?>><?php echo UCWords(t("update_account-pass", "update password")); ?> <i class="la la-arrow-right"></i></button>
			  </div>
			</div>
		</div>
        <div role="tabpanel" class="tab-pane fade" id="api">
		  <div class="col-md-8">
			<div class="form-group">
              <label class="control-label" for="key1"><?php echo t("key1", "Key 1"); ?></label>
              <input <?php if($lockStatus == 0): ?> id="key1" name="key1"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?> type="text" tabindex="6" value="<?php echo validation::safeOutputToScreen($key1); ?>" class="form-control">
            </div>
		  </div>
		  <div class="col-md-4 pt10">
            <div class="form-group">
              <button class="btn btn-block btn-gen" type="button" <?php if($lockStatus == 0): ?> onClick="createRandomAPIKey('key1'); return false;"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?>><i class="la la-rotate-right"></i> <?php echo t("hg_generate", "Generate")?></button>
            </div>
          </div>
		  <br>
		  <div class="col-md-8">
			<div class="form-group">
              <label class="control-label" for="key2"><?php echo t("key2", "Key 2"); ?></label>
              <input <?php if($lockStatus == 0): ?> id="key2" name="key2" <?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?>type="text" tabindex="6" value="<?php echo validation::safeOutputToScreen($key2); ?>" class="form-control">
            </div>
		  </div>
		  <div class="col-md-4 pt10">
            <div class="form-group">
              <button class="btn btn-block btn-gen" type="button" <?php if($lockStatus == 0): ?> onClick="createRandomAPIKey('key2'); return false;"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?>><i class="la la-rotate-right"></i> <?php echo t("hg_generate", "Generate")?></button>
            </div>
          </div>
		  <div class="clearfix"></div>
			<div class="col-md-4 col-md-offset-8 pt30">
			  <div class="form-group">
                <button class="btn btn-go btn-block" <?php if($lockStatus == 0): ?>type="submit"<?php endif; ?><?php if($lockStatus == 1): ?> disabled="disabled" <?php endif; ?>><?php echo UCWords(t("update_account", "update account")); ?> <i class="la la-arrow-right"></i></button>
			  </div>
			</div>
		</div>
      </div>
	</div>
	<?php if($lockStatus == 0): ?><input type="hidden" value="1" name="submitme"/><?php endif; ?>
	</form>
  </div>
</div>
<script>
$('#avatar').change(function() {
  $('#fava').submit();
});
</script>

<?php
// include footer
require_once(SITE_TEMPLATES_PATH . '/partial/_footer_file_manager.inc.php');
?>
