<?php
define('_FEXEC', 1);
require('includes/application_top.php');

require(DIR_WS_INCLUDES . '/tweak/general.php');
frequire($FSESSION->language.'/password_reset_log.php',RLANG);	
// ---- Page Meta
//define('HEADING_TITLE', 'Password Reset Requests (Last 20)');

// ---- Helpers
function fmt_ts($raw) {
  // Accepts UNIX int or DATETIME string
  if (!$raw) return '-';
  if (ctype_digit((string)$raw)) {
    // UNIX timestamp
    $dt = new DateTime('@' . $raw);
    // Use store timezone if defined, otherwise server default
    if (defined('STORE_TIMEZONE') && STORE_TIMEZONE) {
      $dt->setTimezone(new DateTimeZone(STORE_TIMEZONE));
    } else {
      // fall back to default timezone already set in app
      $dt->setTimezone(new DateTimeZone(date_default_timezone_get()));
    }
  } else {
    // Try parsing as DATETIME string
    $dt = date_create($raw);
    if (!$dt) return htmlspecialchars($raw);
    if (defined('STORE_TIMEZONE') && STORE_TIMEZONE) {
      $dt->setTimezone(new DateTimeZone(STORE_TIMEZONE));
    }
  }

  // Prefer your configured formats if available
  $dateFmt = defined('EVENTS_DATE_FORMAT') && EVENTS_DATE_FORMAT ? EVENTS_DATE_FORMAT : 'm-d-Y';
  $timeFmt = defined('TIME_FORMAT') && TIME_FORMAT == 24 ? 'H:i' : 'h:i A';

  return $dt->format(php_date_format($dateFmt) . ' ' . $timeFmt);
}

/**
 * Convert osC-style strftime formats to PHP date() tokens (simple subset).
 * EVENTS_DATE_FORMAT often holds things like "m-d-Y" already; then we just pass it through.
 */
function php_date_format($fmt) {
  // If it contains % tokens, map the common ones
  if (strpos($fmt, '%') !== false) {
    $map = [
      '%Y' => 'Y', '%y' => 'y',
      '%m' => 'm', '%d' => 'd',
      '%e' => 'j', // day of month no leading zero
      '%B' => 'F', '%b' => 'M',
      '%H' => 'H', '%I' => 'h',
      '%M' => 'i', '%S' => 's',
      '%p' => 'A'
    ];
    return strtr($fmt, $map);
  }
  // Otherwise assume it's already a PHP date() format like "m-d-Y"
  return $fmt;
}

// ---- Query
$sql = "
  SELECT
    c.customers_id,
    c.customers_email_address,
    c.customers_token,
    c.customers_timestamp,
    ci.customers_info_date_of_last_logon
  FROM " . TABLE_CUSTOMERS . " c
  LEFT JOIN " . TABLE_CUSTOMERS_INFO . " ci
    ON ci.customers_info_id = c.customers_id
  WHERE (c.customers_token IS NOT NULL AND c.customers_token <> '')
     OR (c.customers_timestamp IS NOT NULL AND c.customers_timestamp <> '' AND c.customers_timestamp <> '0')
  ORDER BY c.customers_timestamp DESC
  LIMIT 20
";
$rs = tep_db_query($sql);

// Optional: quick count for badge
$count_sql = "
  SELECT COUNT(*) AS cnt
  FROM " . TABLE_CUSTOMERS . " c
  WHERE (c.customers_token IS NOT NULL AND c.customers_token <> '')
     OR (c.customers_timestamp IS NOT NULL AND c.customers_timestamp <> '' AND c.customers_timestamp <> '0')
";
$cnt_row = tep_db_fetch_array(tep_db_query($count_sql));
$total_count = (int)$cnt_row['cnt'];
?>
<!doctype html>
<html <?php echo HTML_PARAMS; ?>>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
  <title><?php echo TITLE . ' : ' . HEADING_TITLE; ?></title>
  <link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <script src="includes/javascript/jquery-3.6.0.min.js"></script>
  <style>
    .token-cell { max-width: 320px; }
    .token-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; font-size: .85rem; }
    .nowrap { white-space: nowrap; }
  </style>
</head>
<body bgcolor="#FFFFFF">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->
<input type="hidden" id="csrf_token" value="<?php echo $csrf_token; ?>">



<?php
// Make sure this is set once per session, not regenerated every render.
if (empty($_SESSION['csrf_manual_reset'])) {
  $_SESSION['csrf_manual_reset'] = bin2hex(random_bytes(16));
}
$csrf_token = $_SESSION['csrf_manual_reset'];
?>
<script>
  const CSRF_TOKEN = '<?php echo addslashes($csrf_token); ?>';
</script>


<div class="container my-4">
  <div class="d-flex align-items-center mb-3">
    <h1 class="h4 mb-0"><?php echo HEADING_TITLE; ?></h1>
    <span class="badge bg-secondary ms-2"><?php echo (int)$total_count; ?> total</span>
    <div class="ms-auto">
      <a href="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-arrow-clockwise"></i> Refresh
      </a>
    </div>
  </div>

  <div class="alert alert-info small" role="alert">
   <?php echo TEXT_PASSWORD_RESET_LOG_INFO; ?>
  </div>

  <div class="table-responsive">
    <table class="table table-sm table-striped align-middle">
      <thead class="table-light">
        <tr>
          <th scope="col">#</th>
          <th scope="col"><?php echo TABLE_HEADING_CUSTOMER; ?></th>
          <th scope="col"><?php echo TABLE_HEADING_EMAIL; ?></th>
          <th scope="col" class="nowrap"><?php echo TABLE_HEADING_REQUESTED_AT; ?></th>
          <th scope="col" class="nowrap"><?php echo TABLE_HEADING_LAST_LOGON; ?></th>
          <th scope="col" class="token-cell"><?php echo TABLE_HEADING_TOKEN; ?></th>
          <th scope="col" class="text-end"><?php echo TABLE_HEADING_ACTIONS; ?></th>
        </tr>
      </thead>
      <tbody>
      <?php
      $i = 0;
      while ($row = tep_db_fetch_array($rs)) {
        $i++;
        $id   = (int)$row['customers_id'];
        $mail = $row['customers_email_address'];
        $tok  = $row['customers_token'];
        $ts   = $row['customers_timestamp'];
        $logon = $row['customers_info_date_of_last_logon'];

        // Format timestamps
        $requested_at = fmt_ts($ts);
        $last_logon   = $logon ? fmt_ts(strtotime($logon)) : '-';

        // Customer admin link (adjust to your route)
        $search_link = tep_href_link(FILENAME_CUSTOMERS_MAINPAGE, 'search=' . urlencode($mail));
		$edit_link = tep_href_link(FILENAME_CUSTOMERS_MAINPAGE,'cID=' . $id . '&action=edit&return=ps');
        ?>
        <tr>
          <td class="text-muted"><?php echo $i; ?></td>
          <td>
            <a href="<?php echo $search_link; ?>" class="text-decoration-none">
              ID <?php echo $id; ?>
            </a>
          </td>
          <td><span class="text-break"><?php echo htmlspecialchars($mail); ?></span></td>
          <td class="nowrap"><?php echo htmlspecialchars($requested_at); ?></td>
          <td class="nowrap"><?php echo htmlspecialchars($last_logon); ?></td>
          <td>
            <?php if ($tok) { ?>
              <div class="input-group input-group-sm">
                <input type="text" class="form-control token-mono" readonly value="<?php echo htmlspecialchars($tok); ?>">
                <button class="btn btn-outline-secondary btn-copy" type="button" data-clip="<?php echo htmlspecialchars($tok); ?>">
                  <i class="bi bi-clipboard"></i>
                </button>
              </div>
            <?php } else { ?>
              <span class="text-muted">—</span>
            <?php } ?>
          </td>

		  <td class="text-end">
  <div class="btn-group btn-group-sm">
    <button
      type="button"
      class="btn btn-outline-secondary btn-resend"
      data-email="<?php echo htmlspecialchars($mail); ?>"
      title="Resend password reset email">
      <i class="bi bi-send"></i> Resend
    </button>
    <a href="<?php echo $edit_link; ?>" class="btn btn-outline-primary">
      <i class="bi bi-person-lines-fill"></i> View
    </a>
  </div>
</td>

        </tr>
        <?php
      }
      if ($i === 0) {
        echo '<tr><td colspan="7" class="text-center text-muted py-4">No password reset requests found.</td></tr>';
      }
      ?>
      </tbody>
    </table>
  </div>
  <?php 
  // Ensure token is set once per session
if (empty($_SESSION['csrf_manual_reset'])) {
  $_SESSION['csrf_manual_reset'] = bin2hex(random_bytes(16));
}
echo '<!-- CSRF_PAGE=' . $_SESSION['csrf_manual_reset'] . ' SID=' . session_id() . ' -->';
?>

  <p class="small text-muted mt-3">
    Showing the most recent 20 records ordered by the request timestamp stored in <code>customers.customers_timestamp</code>.
  </p>
</div>

<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<script>
  // Copy-to-clipboard for tokens
  $(document).on('click', '.btn-copy', function() {
    const val = $(this).data('clip');
    navigator.clipboard.writeText(val).then(() => {
      const btn = $(this);
      const orig = btn.html();
      btn.html('<i class="bi bi-check2"></i>');
      setTimeout(() => btn.html(orig), 1200);
    });
  });
</script>

<script>
$(document).on('click', '.btn-resend', function () {
  const btn = $(this);
  const email = btn.data('email');

  btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>Sending');

  $.ajax({
    url: 'ajax_resend_password_reset.php',
    method: 'POST',
    data: { email: email, csrf: CSRF_TOKEN },
    headers: { 'X-CSRF-Token': CSRF_TOKEN } // bonus path
  })
  .done(function(res){
    showAlert('success', res?.msg || 'Reset email sent');
    btn.html('<i class="bi bi-check2"></i> Sent');
    setTimeout(() => btn.prop('disabled', false).html('<i class="bi bi-send"></i> Resend'), 2000);
  })
  .fail(function(xhr){
    showAlert('danger', xhr.responseJSON?.msg || 'Failed to resend');
    btn.prop('disabled', false).html('<i class="bi bi-send"></i> Resend');
  });
});


// Simple stacked alert (you can replace with a real Toast if you prefer)
function showAlert(type, text) {
  const $box = $('<div class="alert alert-'+type+' py-2 my-2"></div>').text(text);
  $('.container').first().prepend($box);
  setTimeout(() => $box.fadeOut(300, () => $box.remove()), 3000);
}
</script>

</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
