<?php
/*
 * Copyright (C) 2018 josh.north@point808.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

    ini_set('session.gc_maxlifetime', 24*60*60);                                // MIN SESSION
    ini_set('session.gc_probability', 1);                                       // GC RATES
    ini_set('session.gc_divisor', 100);                                         // TIMES
    ini_set('session.use_cookies', '1');
    ini_set('session.use_only_cookies', '1');
    ini_set('session.cookie_secure', '0');
    ini_set('session.cookie_httponly', '0');
    ini_set('session.cookie_samesite', 'Lax');
    session_save_path('.tmp');                                                  // TEMP
    session_start();                                                            // START
    require_once __DIR__ . '/autoload.php';                                     // AUTOLOAD
    use App\LobbySIO\Config\Registry;
    $Users = new \App\LobbySIO\Database\Users();
    if (Registry::AUTHMETHOD == 'SAML') {
        //simplesaml
        require_once('../simplesamlphp/lib/_autoload.php');
        $auth = new \SimpleSAML\Auth\Simple(Registry::AUTHIDP);
        //$auth->requireAuth();
        $auth->isAuthenticated();
        if (!$auth->isAuthenticated()) {
            $attributes = 'none';
        } else {
            $attributes = $auth->getAttributes();
            $saml_user_email = $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0];
            $saml_user_info = $Users->getUserInfoByEmail($saml_user_email, "1", "0");
            $saml_user_id = $saml_user_info["0"]["users_id"];
        }
        $session = \SimpleSAML\Session::getSessionFromRequest();
        $session->cleanup();
    }
    $StaticFunctions = new \App\LobbySIO\Misc\StaticFunctions();                // DEFAULT CLASSES
    $SiteInfo = new \App\LobbySIO\Database\SiteInfo();
    if (isset($_SESSION['user_id'])) {                                          // LOGGED IN? GET USER OBJECT
        if (isset($saml_user_id)) {
            $sessuserid=$saml_user_id;
        } else {
            $sessuserid=$_SESSION['user_id'];
        }
        } elseif (!isset($_SESSION['user_id'])) {
        if (isset($saml_user_id)) {
            $sessuserid=$saml_user_id;
        } else {
            $sessuserid='2';
        }
    $session_user = $Users->getUserInfo($sessuserid, "1", "0"); }
    if (isset($session_user)) {                                                 // GET UID OR SET TO KIOSK
        $uid = $session_user["0"]["users_id"];} else { $uid = "2"; }
    $app_disp_lang = filter_input(INPUT_COOKIE, 'app_disp_lang');               // SETUP LANGUAGE
    if(!isset($app_disp_lang)) {
        $app_disp_lang=$StaticFunctions->getDefaultLanguage(); }
    $siteidcookie = filter_input(INPUT_COOKIE, 'app_site');                     // SETUP SITE
    foreach($SiteInfo->getSite("0", $uid, "0", "0") as $arr) {
        $lookup_array[$arr['sites_id']]=1; }
        if(isset($lookup_array[$siteidcookie])) {
            $siteid = $siteidcookie; } else { $siteid = "1"; }
        if(!isset($siteid)) { $siteid="1"; }
    $Translate = new \App\LobbySIO\Language\Translate($app_disp_lang);          // SETUP TRANSLATOR
    $transLang =  $Translate->userLanguage();
    $app_current_pagename = $transLang['ACCOUNT'];                              // PAGE SETUP
    $app_current_pageicon = '<i class="fas fa-user-circle"></i> ';
    require_once("inc/header.inc.php");
    if ($StaticFunctions->getUserSessionStatus() == false) {                        // CHECK STATUS
        echo $StaticFunctions->killSession();                                   // ELSE DIE
    } else { ?>



<?php                                                                           // FILTER POSTED DATA
$form_data = filter_input_array(INPUT_POST, [
  'fd_saveProfile' => (string)FILTER_SANITIZE_STRING,
  'fd_initialPassword' => (string)FILTER_SANITIZE_STRING,
  'fd_confirmPassword' => (string)FILTER_SANITIZE_STRING,
  'fd_firstName' => (string)FILTER_SANITIZE_STRING,
  'fd_lastName' => (string)FILTER_SANITIZE_STRING,
  'fd_userEmail' => (string)FILTER_SANITIZE_STRING
]);
?>

<?php                                                                           // PAGE CONSTANTS
  $selfName = (string)'profile.php';                                            // PAGE URL
?>

<?php
  $minpasslength = $StaticFunctions->getMinPass();
  if (isset($form_data['fd_saveProfile'])):
    if (empty($form_data['fd_initialPassword']) && empty($form_data['fd_confirmPassword'])):
      $Users->setUserInfo($session_user["0"]["users_id"], $form_data['fd_firstName'], $form_data['fd_lastName'], $form_data['fd_userEmail'], $session_user["0"]["users_usertypeid"], $session_user["0"]["users_password"]);
      header("Location: $selfName");
    elseif (strlen($form_data['fd_initialPassword']) < $minpasslength):
      echo "Password must be at least $minpasslength characters.";
    elseif (!empty($form_data['fd_initialPassword']) && empty($form_data['fd_confirmPassword'])):
      echo "Please confirm password if you wish to change it";
    elseif ($form_data['fd_initialPassword'] != $form_data['fd_confirmPassword']):
      echo "New passwords do not match";
    elseif (!empty($form_data['fd_initialPassword']) && ($form_data['fd_initialPassword'] = $form_data['fd_confirmPassword'])):
    // change pass
    require_once("src/Misc/PasswordHash.php");
    $hasher = new PasswordHash(8, FALSE);
    $password = $hasher->HashPassword($form_data['fd_initialPassword']);
    $Users->setUserInfo($session_user["0"]["users_id"], $form_data['fd_firstName'], $form_data['fd_lastName'], $form_data['fd_userEmail'], $session_user["0"]["users_usertypeid"], $password);
    header("Location: $selfName");
    endif;
  endif;
?>
  <div class="container-fluid">
    <div class="row row-cols-3 mb-2">
      <div class="col d-grid gap-2">
        <h2><i class="fas fa-user-circle"></i> <?=$transLang['STR_ACCOUNTINFO_EDITPROFILE_TITLE']?></h2>
      </div>
      <div class="col d-grid gap-2 text-center">
      </div>
      <div class="col text-end">
        <a href="<?=$selfName?>" type="button" class="btn btn-primary btn-lg"><i class="fa fa-redo"></i> <?=$transLang['REFRESH']?></a>
      </div>
    </div>
    <?php if (Registry::AUTHMETHOD == 'INTERNAL') { ?>
    <div class="row row-cols-1 mb-2">
      <div class="col d-grid gap-2">
        <p class="lead"><?=$transLang['STR_ACCOUNTINFO_DESC'] . $minpasslength; ?></p>
      </div>
    </div>
    <?php } elseif (Registry::AUTHMETHOD == 'SAML') { ?>
    <div class="row row-cols-1 mb-2">
      <div class="col d-grid gap-2">
        <p class="lead"><?=$transLang['STR_ACCOUNTINFO_AUTHLOCKED']?></p>
      </div>
    </div>
    <?php } ?>
    <form method="post">
      <fieldset>
        <div class="row row-cols-2 mb-2">
          <div class="col d-grid gap-2">
            <div class="input-group">
              <span class="input-group-text"><?=$transLang['USER-USERNAME']?></span>
              <input class="form-control bg-white" type="text" name="fd_userName" id="fd_userName" maxlength="50" value="<?php echo $session_user["0"]["users_username"]; ?>" readonly />
            </div>
          </div>
          <div class="col d-grid gap-2">
            <div class="input-group">
              <span class="input-group-text"><?=$transLang['CREATED']?></span>
              <input class="form-control bg-white" type="text" name="fd_userCreated" id="fd_userCreated" value="<?php echo $session_user["0"]["users_created"]; ?>" readonly />
            </div>
          </div>
        </div>
        <div class="row row-cols-2 mb-2">
          <div class="col d-grid gap-2">
            <div class="input-group">
              <span class="input-group-text"><?=$transLang['USER-TYPE']?></span>
              <input class="form-control bg-white" type="text" name="fd_userType" id="fd_userType" maxlength="50" value="<?php echo $transLang[$session_user["0"]["users_usertype"]]; ?>" readonly />
            </div>
          </div>
          <div class="col d-grid gap-2">
            <div class="input-group">
              <span class="input-group-text"><?=$transLang['EMAIL']?></span>
              <input class="form-control bg-white" type="text" name="fd_userEmail" id="fd_userEmail" maxlength="100" value="<?php echo $session_user["0"]["users_email"]; ?>" <?php if (Registry::AUTHMETHOD == 'SAML') { echo "readonly "; } ?>/>
            </div>
          </div>
        </div>
        <div class="row row-cols-2 mb-2">
          <div class="col d-grid gap-2">
            <div class="input-group">
              <span class="input-group-text"><?=$transLang['FIRSTNAME']?></span>
              <input class="form-control bg-white" type="text" name="fd_firstName" id="fd_firstName" maxlength="50" value="<?php echo $session_user["0"]["users_firstname"]; ?>" <?php if (Registry::AUTHMETHOD == 'SAML') { echo "readonly "; } ?>/>
            </div>
          </div>
          <div class="col d-grid gap-2">
            <div class="input-group">
              <span class="input-group-text"><?=$transLang['LASTNAME']?></span>
              <input class="form-control bg-white" type="text" name="fd_lastName" id="fd_lastName" maxlength="50" value="<?php echo $session_user["0"]["users_lastname"]; ?>" <?php if (Registry::AUTHMETHOD == 'SAML') { echo "readonly "; } ?>/>
            </div>
          </div>
        </div>
        <?php if (Registry::AUTHMETHOD == 'INTERNAL') { ?>
        <div class="row row-cols-3 mb-2">
          <div class="col d-grid gap-2">
            <div class="input-group">
              <span class="input-group-text"><?=$transLang['NEW'] . " " . $transLang['PASSWORD']?></span>
              <input class="form-control bg-white" type="password" name="fd_initialPassword" id="fd_initialPassword" />
            </div>
          </div>
          <div class="col d-grid gap-2">
            <div class="input-group">
              <span class="input-group-text"><?=$transLang['STR_COMMON_CONFIRM'] . " " . $transLang['NEW'] . " " . $transLang['PASSWORD']?></span>
              <input class="form-control bg-white" type="password" name="fd_confirmPassword" id="fd_confirmPassword" />
            </div>
          </div>
          <div class="col d-grid gap-2">
            <div class="input-group">
              <button type="submit" name="fd_saveProfile" id="fd_saveProfile" class="form-control btn btn-success"><i class="fas fa-save"></i>&nbsp;<?=$transLang['STR_COMMON_SAVE']?></button>
            </div>
          </div>
        </div>
        <?php } ?>
      </fieldset>
    </form>
    <hr />
  </div>
<!-- END CONTENT -->

<?php } require_once("inc/footer.inc.php");
