<?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
    //session_save_path('.tmp');                                                // TEMP
    //session_start();                                                          // START
    //ini_set("session.cookie_httponly", 1);
    require_once __DIR__ . '/../autoload.php';                                  // AUTOLOAD
    use App\LobbySIO\Config\Registry;
    use App\LobbySIO\Misc\Csrf;                                        // ANTICSRF
    $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();
    ob_start();                                                                 // OUTPUT BUFFER
    $session_status = $StaticFunctions->getUserSessionStatus();                     // SET A STATUS
    $defaulttimezone = $StaticFunctions->getDefaultTZ();
    date_default_timezone_set('UTC');                                           // DEFAULT TO UTC
    date_default_timezone_set($defaulttimezone);                                // UPDATE TO DEFAULT APP SETTING
    $timezone = $SiteInfo->getSite($siteid, "0", "0", "0")[0]["sites_timezone"]; // GET TIMEZONE FROM SITE ID
    $timeplus = new DateTime($StaticFunctions->getUTC(), new DateTimeZone('UTC')); // DUMB WAY TO CALCULATE SOME TIMES
    $timeplus->setTimezone(new DateTimeZone("$timezone"));
    $timenow = $timeplus->format('Y-m-d H:i:s');
      header("X-Frame-Options: SAMEORIGIN");
      header("X-Content-Type-Options: nosniff");
      //header("Content-Security-Policy: script-src 'self' 'unsafe-inline'; script-src-elem 'self'; script-src-attr 'self'; style-src 'self'; style-src-elem 'self'; style-src-attr 'self'; img-src 'self'; connect-src 'self'; frame-src 'self'; font-src 'self'; media-src 'self'; object-src 'self'; manifest-src 'self'; worker-src 'self'; prefetch-src 'self'; form-action 'self'; frame-ancestors 'self'; default-src 'self'", false);
      if (!empty($_GET['a'])) {
        echo '<pre>' . print_r($_POST, true) . '</pre>';
        echo 'Verification has been : ' . (Csrf::verifyToken('home') ? 'successful' : 'unsuccessful');
      }
?>
<!doctype html>
<html lang="<?php echo $app_disp_lang; ?>">
<!-- START HEAD -->
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-title" content="<?php echo $transLang['APP_NAME']; ?>">
  <link rel="apple-touch-icon" href="assets/touch-logo.png?v3">
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<?php if (basename($_SERVER['PHP_SELF']) == 'signin_display.php'): ?>  <meta http-equiv="refresh" content="5; url=index.php" /><?php endif; ?>
  <link rel="stylesheet" href="css/bootstrap.min.css?v3"/>
  <link rel="stylesheet" href="css/sticky-footer-navbar.css?v3">
  <link rel="stylesheet" href="css/all.min.css?v3"/>
  <link rel="stylesheet" href="css/fontawesome.min.css?v3"/>
  <link rel="stylesheet" href="css/brands.min.css?v3"/>
  <link rel="stylesheet" href="css/regular.min.css?v3"/>
  <link rel="stylesheet" href="css/animate.min.css?v3"/>
  <link rel="stylesheet" href="css/datatables.min.css?v3" />
  <link rel="stylesheet" href="css/styles.css?v3"/>
  <link rel="stylesheet" href="css/tempusdominus-bootstrap-4.min.css?v3"/>
  <meta name="description" content="<?php echo $transLang['META_DESC']; ?>" />
  <script src="js/jquery.min.js?v3"></script>
  <script src="js/bootstrap.bundle.min.js?v3"></script>
  <script src="js/datatables.min.js?v3"></script>
  <script src="js/buttons.flash.min.js?v3"></script>
  <script src="js/buttons.html5.min.js?v3"></script>
  <script src="js/buttons.print.min.js?v3"></script>
  <script src="js/dataTables.buttons.min.js?v3"></script>
  <script src="js/jszip.min.js?v3"></script>
  <script src="js/pdfmake.min.js?v4"></script>
  <script src="js/vfs_fonts.js?v4"></script>
  <script src="js/moment.min.js?v3"></script>
  <script src="js/tempusdominus-bootstrap-4.min.js?v3"></script>
  <script src="js/jSignature.min.js?v3"></script>
  <title><?php echo $StaticFunctions->getTitle($app_current_pagename, $app_disp_lang); ?></title>
</head>
<!-- END HEAD -->
<!-- START BODY -->
<body>
<!-- START NAVBAR -->
  <nav class="navbar navbar-expand-lg navbar-light bg-light mb-2">
    <div class="container-fluid">
      <a class="navbar-brand" href="index.php"><img src="<?php echo $StaticFunctions->getLogo(); ?>" width="120" height="60" alt=""></a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbar"><span class="navbar-toggler-icon"></span></button>
      <div class="collapse navbar-collapse" id="navbar">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
<?php if ($session_status == true): ?>
          <!-- START NAVBAR MENU FOR ALL LOGGED IN -->
          <li class="nav-item"><a class="nav-link<?php if ($app_current_pagename==$transLang['STR_COMMON_HOME']): echo " active"; endif; ?>" href="index.php"><i class="fas fa-home"></i> <?php echo $transLang['STR_COMMON_HOME']; ?></a></li>
          <li class="nav-item"><a class="nav-link<?php if ($app_current_pagename==$transLang['ACCOUNT']): echo " active"; endif; ?>" href="profile.php"><i class="fas fa-user-circle"></i> <?php echo $transLang['ACCOUNT']; ?></a></li>
          <li class="nav-item"><a class="nav-link<?php if ($app_current_pagename==$transLang['REPORTS']): echo " active"; endif; ?>" href="reports.php"><i class="fas fa-chart-pie"></i> <?php echo $transLang['REPORTS']; ?></a></li>
          <!-- END NAVBAR MENU FOR ALL LOGGED IN -->
<?php endif; ?>
<?php if (isset($session_user)) { if ($session_user["0"]["users_usertype"] == "USER-TYPES-ADMIN"): ?>
          <!-- START NAVBAR MENU FOR ADMIN LOGGED IN -->
          <li class="nav-item"><a class="nav-link<?php if ($app_current_pagename==$transLang['ADMINISTRATION']): echo " active"; endif; ?>" href="users.php"><i class="fas fa-users"></i> <?php echo $transLang['ADMINISTRATION']; ?></a></li>
          <!-- END NAVBAR MENU FOR ADMIN LOGGED IN -->
<?php endif; }; ?>
<?php if ($session_status == false): ?>
          <!-- START NAVBAR MENU FOR ALL LOGGED OUT - BOTTOM END -->
          <li class="nav-item"><a class="nav-link<?php if ($app_current_pagename==$transLang['SIGNIN']): echo " active"; endif; ?>" href="signin.php"><i class="fas fa-sign-in-alt"></i> <?php echo $transLang['SIGNIN']; ?></a></li>
          <li class="nav-item"><a class="nav-link<?php if ($app_current_pagename==$transLang['SIGNOUT']): echo " active"; endif; ?>" href="signout.php"><i class="fas fa-sign-out-alt"></i> <?php echo $transLang['SIGNOUT']; ?></a></li>
        </ul>
        <ul class="navbar-nav mr-sm-2">
          <li class="nav-item"><a class="nav-link btn btn-sm btn-outline-success<?php if ($app_current_pagename==$transLang['LOGIN']): echo " active"; endif; ?>" href="login.php"><i class="fas fa-cogs"></i> </a></li>
          <!-- END NAVBAR MENU FOR ALL LOGGED OUT - BOTTOM END -->
<?php endif; ?>
<?php if ($session_status == true): ?>
          <!-- START NAVBAR MENU FOR ALL LOGGED IN - BOTTOM END -->
        </ul>
        <ul class="navbar-nav mr-sm-2">
          <li class="nav-item"><a class="nav-link<?php $sname=$SiteInfo->getSite($siteid, "0", "0", "0")[0]["sites_name"]; if($sname=="NOSITE") { echo " btn btn-sm btn-outline-warning"; } else { echo " btn btn-sm btn-outline-secondary"; } ?>" href="#" data-bs-toggle="modal" data-bs-target="#sitetimeModal"><i class="fas fa-map-marker-alt"></i> <?php if ($sname=="NOSITE") {echo $transLang['NOSITE'];} else { echo $sname; } ?></a></li>
  <?php if (Registry::AUTHMETHOD == 'SAML') { ?>
          <!-- SAML SESSION BUTTONS -->
          <li class="nav-item"><a class="nav-link btn btn-sm btn-outline-danger<?php if ($app_current_pagename==$transLang['LOGOUT']): echo " active"; endif; ?>" href="<?php echo str_replace("http%3A%2F%2F","https%3A%2F%2F",$auth->getLogoutURL()); ?>"><span class="badge bg-light text-dark"><?php echo $session_user["0"]["users_firstname"] . " " . $session_user["0"]["users_lastname"];?></span> <i class="fas fa-ban"></i> <?php echo $transLang['LOGOUT']; ?></a></li>
  <?php } else { ?>
          <!-- BUILTIN SESSION BUTTONS -->
          <li class="nav-item"><a class="nav-link btn btn-sm btn-outline-danger<?php if ($app_current_pagename==$transLang['LOGOUT']): echo " active"; endif; ?>" href="logout.php"><span class="badge bg-light text-dark"><?php echo $session_user["0"]["users_firstname"] . " " . $session_user["0"]["users_lastname"];?></span> <i class="fas fa-ban"></i> <?php echo $transLang['LOGOUT']; ?></a></li>
  <?php } ?>
          <!-- END NAVBAR MENU FOR ALL LOGGED IN - BOTTOM END -->
<?php endif; ?>
          <form action="changelang.php" method="post" name="changelang" class="changelang">
            <?php echo Csrf::getInputToken('home') ?>
            <div class="input-group">
              
              <?php 
              foreach(glob('src/Language/*.lang.ini.example') as $file){
  
              }
  
  ?>
              
              
              <select class="form-select btn-outline-secondary" id="app_disp_lang" name="app_disp_lang">
<?php foreach(glob('src/Language/*.lang.ini.example') as $file){
  if(!is_dir($file)) { $filename=basename(explode('.', $file, 2)[0]); } ?>
                <option value="<?php echo $filename; ?>"<?php if ($filename==$app_disp_lang) { echo " selected"; } ?>><?php echo strtoupper($filename); ?></option>
<?php } ?>
              </select>
            </div>
          </form>
        </ul>
      </div>
    </div>
  </nav>
<!-- END NAVBAR -->
<!-- START MODAL -->
  <div class="modal fade" id="sitetimeModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="Site"><i class="fas fa-map-marker-alt"></i> <?php echo $transLang['STR_COMMON_SITE']; ?></h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <form class="row g-3" action="changesite.php" method="post">
            <?php echo Csrf::getInputToken('home') ?>
            <div class="input-group">
              <select class="form-select" id="site" aria-label="Site" name="site" required>
<?php foreach($SiteInfo->getSite("0", $uid, "0", "0") as $row): ?>
                <option value="<?php echo $row['sites_id']; ?>"<?php if ($row['sites_id']==$siteid) { echo " selected"; } ?>><?php if ($row['sites_name']=="NOSITE") {echo $transLang['NOSITE'];} else { echo $row['sites_name']; } ?></option>
<?php endforeach; ?>
              </select>
              <button class="btn btn-primary" type="submit" value="<?php echo $transLang['STR_COMMON_SAVE']; ?>"><i class="fas fa-save"></i>&nbsp;<?php echo $transLang['STR_COMMON_SAVE']; ?></button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
  <script>
    $(".changelang").change(function(e){
      e.preventDefault();
      $(this).closest("form").submit();
    });
  </script>
  <script>
    $(document).ready(function () {
      //POP MODAL IF NO COOKIE
      if ( document.cookie.indexOf("app_site=") < 0) {
        $("#sitetimeModal").modal("show");
      }
    });
  </script>
<!-- END MODAL -->
