<?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\Misc\Csrf;                                                 // ANTICSRF
    $StaticFunctions = new \App\LobbySIO\Misc\StaticFunctions();                // DEFAULT CLASSES
    $SiteInfo = new \App\LobbySIO\Database\SiteInfo();
    $Users = new \App\LobbySIO\Database\Users();
    if (isset($_SESSION['user_id'])) {                                          // LOGGED IN? GET USER OBJECT
        $session_user = $Users->getUserInfo($_SESSION['user_id'], "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();
    $VisitInfo = new \App\LobbySIO\Database\VisitInfo();
    $VisitActions = new \App\LobbySIO\Database\VisitActions();
    $app_current_pagename = $transLang['SIGNOUT'];                              // PAGE SETUP
    $app_current_pageicon = '<i class="fas fa-sign-out-alt"></i> ';
    require_once("inc/header.inc.php");
    if ($StaticFunctions->getSessionStatus() == true) {                         // CHECK STATUS
        header('Location: index.php');                                          // ELSE HOME
    } else {
      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');
      }
    ?>



<?php                                                                           // FILTER POSTED DATA
$form_data = filter_input_array(INPUT_POST, [
  'fd_formAction' => (string)FILTER_SANITIZE_STRING,
  'fd_pageNumber' => (int)FILTER_VALIDATE_INT,
  'fd_endVisitForId' => (int)FILTER_VALIDATE_INT
]);
if(empty($form_data['fd_formAction'])){                                         // SET INITIAL STAGE
  $form_data['fd_formAction'] = 'fa_initial';
}
?>

<?php                                                                           // PAGE CONSTANTS
  $selfName = (string)'signout.php';                                            // PAGE URL
  $isApproved = (int)2;                                                         // VISIT APPROVED (0=DECLINE,1=WAIT,2=APPROVED)
?>

<?php if ($form_data['fd_formAction'] == 'fa_initial') {                        // SHOW SIGNOUT LISTING
  $pgNum=(int)1;                                                                // PAGINATION LOGIC
  if(!empty($form_data['fd_pageNumber'])){$pgNum = $form_data['fd_pageNumber'];}
  $pgOffset=(int)($pgNum-1)*$StaticFunctions->getPageRows();
  $pgRowCount=(int)count($VisitInfo->getVisitInfo($siteid, $isApproved, "empty", "%", "%", "%", "%", "%", "%"));
  $pgCount=(int)0;
  if(0===$pgRowCount){}else{$pgCount=(int)ceil($pgRowCount/$StaticFunctions->getPageRows());if($pgNum>$pgCount){$pgNum=(int)1;}}
?>
<!-- SIGNOUT LIST -->
  <div class="container-fluid">
    <div class="row row-cols-3 mb-2">
      <div class="col d-grid gap-2">
        <h2><i class="fas fa-sign-out-alt"></i> <?=$transLang['SIGNOUT']?></h2>
      </div>
      <div class="col d-grid gap-2 text-center">
        <form method="post">
        <input type="hidden" name="fd_formAction" id="fd_formAction" value="fa_initial" />
        <ul class="pagination pagination-sm">
          <li class="page-item disabled"><a class="page-link" href="#" tabindex="-1"><?=$transLang['STR_COMMON_PAGE']?></a></li>
          <?php for($i=1; $i<=$pgCount; $i++){ ?>
          <li class="page-item<?php if($i===$pgNum){echo ' active';} ?>"><button type="submit" class="page-link<?php if($i===$pgNum){echo ' active';} ?>" id="fd_pageNumber" name="fd_pageNumber" value="<?php echo $i; ?>"><?php echo $i; ?></button></li>
          <?php } ?>
        </ul>
        </form>
      </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>
  </div>
  <div class="container-fluid">
    <form class="form-signout" method="post" onsubmit="return confirm('<?=$transLang['END_VISIT_WARNING']?>')">
    <input type="hidden" name="fd_formAction" id="fd_formAction" value="fa_signout" />
    <?php echo Csrf::getInputToken('home') ?>
    <table class="table table-striped">
      <thead class="thead-dark">
        <tr><th><?=$transLang['BADGE']?></th><th><?=$transLang['IN']?></th><th><?=$transLang['NAME']?></th><th><?=$transLang['ESCORT']?></th><th><?=$transLang['ACTIONS']?></th></tr>
      </thead>
      <tbody>
        <?php foreach ($VisitInfo->getVisitInfo($siteid, $isApproved, "empty", "%", "%", "%", "%", $StaticFunctions->getPageRows(), $pgOffset) as $row) {
          $timein = new DateTime($row['visits_intime'], new DateTimeZone('UTC'));
          $timein->setTimezone(new DateTimeZone("$timezone"));
          $timein_disp = $timein->format('Y-m-d H:i:s');
          $isvendor = $row['visits_isvendor'];
        ?>
        <tr>
          <td><?=$row['visits_badge']?></td>
          <td><?=$timein_disp?></td>
          <td><?php echo $row['visits_lastname'] . ", " . $row['visits_firstname']; ?><br /><img src="<?php echo $row['visits_signature']; ?>" width="200" height="50" /></td>
          <td><?php if (!empty($row['visits_escort'])) {echo $row['visits_escort'] . '<br /><img src="' . $row['visits_escort_signature'] . '" width="200" height="50" />'; } ?></td>
          <td><nobr><?php if($isvendor===0){ ?><button type="submit" name="fd_endVisitForId" value="<?php echo $row['visits_id']; ?>" class="btn btn-warning btn-lg"><i class="fas fa-sign-out-alt"></i><?=$transLang['SIGNOUT']?></button>
              <?php } elseif($isvendor===1){
                foreach ($VisitInfo->getInfoVendorVisitFinal($row['visits_id']) as $rowvm) {
                  $db_vendorinfo_workcompleted = $rowvm['db_vendorinfo_workcompleted'];
                  $db_vendorinfo_sitecleanup = $rowvm['db_vendorinfo_sitecleanup'];
                  if ($db_vendorinfo_workcompleted === 1 && $db_vendorinfo_sitecleanup === 1) { $finalvendorformcomplete=1; } else { $finalvendorformcomplete=0; }
                  if($finalvendorformcomplete===1){ ?>
              <button type="submit" name="fd_endVisitForId" value="<?php echo $row['visits_id']; ?>" class="btn btn-warning btn-lg"><i class="fas fa-sign-out-alt"></i><?=$transLang['SIGNOUT']?></button>
                  <?php } elseif ($finalvendorformcomplete===0) { ?>
              <span class="d-inline-block" tabindex="0" data-bs-toggle="popover" data-bs-trigger="hover focus" data-bs-content="<?=$transLang['STR_VENDORINFO_UNABLETOSIGNOUT_DESC']?>">
              <button class="btn btn-warning btn-lg" disabled><i class="fas fa-sign-out-alt"></i><?=$transLang['SIGNOUT']?></button>
              </span>
              <?php } } } ?></nobr>
          </td>
        </tr>
        <?php } ?>
      </tbody>
    </table>
    </form>
  </div>
<!-- SIGNOUT LIST END -->

<?php } elseif($form_data['fd_formAction']=='fa_signout') {                     // END VISIT AND DISPLAY THANKS IF POSTED
  $VisitActions->endVisit($form_data['fd_endVisitForId'], $StaticFunctions->getUTC()); ?>
<!-- SIGNOUT ACKNOWLEGEMENT -->
  <div class="container-fluid">
    <div class="row row-cols-3 mb-2">
      <div class="col d-grid gap-2">
        <h2><i class="fas fa-sign-out-alt"></i> <?=$transLang['STR_SIGNOUT_THANKYOU_TITLE']?></h2>
      </div>
      <div class="col d-grid gap-2 text-center">
      </div>
      <div class="col text-end">
        <a href="index.php" type="button" class="btn btn-primary btn-lg"><i class="fa fa-redo"></i> <?=$transLang['REFRESH']?></a>
      </div>
    </div>
    <div class="row row-cols-1 mb-2">
      <div class="col d-grid gap-2">
        <p><?=$transLang['STR_SIGNOUT_THANKYOU_DESC']?></p>
      </div>
    </div>
  </div>
  <script>
    setTimeout(function(){ window.location.href = 'index.php'; }, 5000);
  </script>
<!-- SIGNOUT ACKNOWLEGEMENT END-->

<?php } else { echo "<!-- INVALID STAGE -->"; }                                 // INVALID STAGE - GO HOME
} require_once("inc/footer.inc.php");                                           // PRINT FOOTER
