<?php
// Guard
defined('_FEXEC') or die();

// ===== CONFIG: choose where Guest Checkout (PWA) appears =====
// Define this constant in your config, or leave it here.
// Allowed: 'top' or 'bottom'
if (!defined('PWA_POSITION')) {
  define('PWA_POSITION', 'top');
}

if (CLOSE_LOGIN === 'no') {

  // ---------- Rate limiting / who’s online ----------
  $show_normal_page = 1;

  if (defined('RESTRICT_NO_LOGONS') && (int)RESTRICT_NO_LOGONS > 0) {
    // prune old sessions
    $xx_mins_ago = (time() - SEATPLAN_TIMEOUT + 60);
    tep_db_query("DELETE FROM " . TABLE_WHOS_ONLINE . " WHERE time_last_click < " . (int)$xx_mins_ago);
    // count logged-in users
    $whos_online_query = tep_db_query("SELECT COUNT(*) AS cnt FROM " . TABLE_WHOS_ONLINE . " WHERE customer_id > 0");
    $whos_online = tep_db_fetch_array($whos_online_query);
    if ((int)$whos_online['cnt'] >= (int)RESTRICT_NO_LOGONS) {
      $show_normal_page = 0;
    }
  }

  // ---------- Enforced login via server load ----------
  if (SEATPLAN_LOGIN_ENFORCED === 'true') {
    $url = tep_href_link('phpinfo/index.php', 'out=php_array');
    $ch  = curl_init();
    curl_setopt_array($ch, [
      CURLOPT_URL            => $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_TIMEOUT        => 3,
    ]);
    $server_resp = trim((string)curl_exec($ch));
    curl_close($ch);

    $load = str_replace('%', '', $server_resp);
    if (is_numeric($load) && defined('SEATPLAN_LOGIN_ENFORCED_LOAD') && $load > (float)SEATPLAN_LOGIN_ENFORCED_LOAD) {
      $show_normal_page = 0;
    }
    // If not numeric, quietly ignore; logging optional
  }

  // ---------- Sign-up visibility rules ----------
  // Default: show (block) unless hidden
  $signup_visible = true;

  if (SEATPLAN_LOGIN_ENFORCED === 'true' && !$FSESSION->is_registered('customer_id')) {
    // When enforced and not logged in, hide sign-up
    $signup_visible = false;
  }

  if (defined('HIDE_SIGNUP') && HIDE_SIGNUP === 'true') {
    $signup_visible = false;
  }

  $signup_class = $signup_visible ? '' : 'd-none';

  // ---------- Branch: High load / restricted ----------
  if ($show_normal_page === 0) {
    echo tep_draw_form('login', tep_href_link(FILENAME_LOGIN, '', 'SSL'));
    ?>
      <div class="container my-4">
        <div class="alert alert-warning">
          <?php echo SEATPLAN_LOGIN_ENFORCED_LOAD_TEXT; ?>
        </div>
        <p class="mb-3"><?php echo SEATPLAN_LOGIN_ENFORCED_LOAD_DESC; ?></p>
        <?php echo tep_template_image_submit('', IMAGE_BUTTON_LOGIN); ?>
      </div>
    </form>
    <?php
    return;
  }

  // ---------- Normal page ----------
  echo tep_draw_form('login', tep_href_link(FILENAME_LOGIN, 'action=process&' . tep_get_all_get_params(['action']), 'SSL'), 'post', 'novalidate');
  // If your platform uses a CSRF token, include it:
  if (isset($sessiontoken)) {
    echo tep_draw_hidden_field('formid', $sessiontoken);
  }

  // Pre-render PWA block into a buffer so we can place it top or bottom
  ob_start();
  if (defined('PURCHASE_WITHOUT_ACCOUNT')
      && ($cart->count_contents() > 0)
      && (PURCHASE_WITHOUT_ACCOUNT === 'yes' || (defined('PURCHASE_NO_ACCOUNT') && PURCHASE_NO_ACCOUNT === 'yes'))) {
    ?>
    <section class="container my-4 <?php echo $signup_class; ?>" id="pwa-block">
      <h2 class="h4 mb-2"><?php echo HEADING_GUEST; ?></h2>
      <p class="mb-3"><?php echo TEXT_GUEST_INTRODUCTION; ?></p>
      <a class="btn btn-primary"
         href="<?php echo tep_href_link(FILENAME_CREATE_ACCOUNT, 'guest=guest', 'SSL'); ?>">
        <?php echo IMAGE_BUTTON_CONTINUE; ?>
      </a>
    </section>
    <?php
  }
  $pwa_html = trim(ob_get_clean());
  ?>

  <div class="container-fluid" data-aos="fade-up">
    <div class="section-header">
      <h2><?php echo HEADING_TITLE; ?></h2>
    </div>

    <div class="index_static">

      <?php if ($messageStack->size('login') > 0): ?>
        <div class="mb-3"><?php echo $messageStack->output('login'); ?></div>
      <?php endif; ?>

      <?php if (PWA_POSITION === 'top' && $pwa_html): ?>
        <?php echo $pwa_html; ?>
      <?php endif; ?>

      <div class="row g-4">

        <!-- Returning customer -->
        <div class="col-sm-6 cm-login-form">
          <h2 class="h4 mb-3"><?php echo HEADING_RETURNING_CUSTOMER; ?></h2>

          <div class="mb-3">
            <?php
              echo tep_draw_input_field(
                'email_address',
                null,
                'id="login-email" required aria-required="true" placeholder="' . (ACCOUNT_USERNAME === 'true' ? ENTRY_USERNAME : ENTRY_EMAIL_ADDRESS) . '" autocomplete="username"',
                (ACCOUNT_USERNAME === 'true' ? 'text' : 'email')
              );
            ?>
          </div>
          <div class="mb-3">
            <?php
              echo tep_draw_input_field(
                'password',
                null,
                'id="login-password" required aria-required="true" placeholder="' . ENTRY_PASSWORD . '" autocomplete="current-password"',
                'password'
              );
            ?>
          </div>

          <div class="d-flex justify-content-between align-items-center">
            <p class="small mb-0">
              <a href="<?php echo tep_href_link(FILENAME_PASSWORD_FORGOTTEN, '', 'SSL'); ?>">
                <?php echo TEXT_PASSWORD_FORGOTTEN; ?>
              </a>
            </p>
            <?php echo tep_template_image_submit('', IMAGE_BUTTON_LOGIN); ?>
          </div>
        </div>

        <!-- New customer (sign-up) -->
        <div class="col-sm-6 cm-create-account-link <?php echo $signup_class; ?>">
          <h2 class="h4 mb-2"><?php echo HEADING_NEW_CUSTOMER; ?></h2>
          <p class="mb-3"><?php echo TEXT_NEW_CUSTOMER_INTRODUCTION; ?></p><br>
          <?php echo '<a class="float-end" href="' . tep_href_link(FILENAME_CREATE_ACCOUNT, '', 'SSL') . '">' . tep_template_image_button('', IMAGE_BUTTON_CONTINUE) . '</a>'; ?>
        </div>

      </div><!-- /.row -->

      <?php if (PWA_POSITION !== 'top' && $pwa_html): ?>
        <?php echo $pwa_html; ?>
      <?php endif; ?>

    </div><!-- /.index_static -->
  </div><!-- /.container-fluid -->
</form>
<?php
} // CLOSE_LOGIN === 'no'
?>
