<?php
session_start();
require_once('../database/config.php');

// Generate CSRF token if it doesn't exist
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>pay2inr</title>
<meta content="UPIGateway  | Accept payments from your customers through our easy-to-use Dynamic QR code service, with transaction fees." name="descriptison">
<meta content="UPI gateway, pay2inr, UPI payment gateway integration, pay2inr, UPI payment gateways, best UPI payment gateway, UPI Payment Stack, Payment UPI , UPI Payment apps , UPI money transfer, UPI payment gateway , Collect payments, Payment gateway UPI , Merchant payment"><meta name="description" content="UPIGateway Merchant |pay2inr." name="keywords">
<!-- plugins:css -->
<link rel="stylesheet" href="../assets/vendors/mdi/css/materialdesignicons.min.css">
<link rel="stylesheet" href="../assets/vendors/base/vendor.bundle.base.css">
<!-- endinject -->
<!-- plugin css for this page -->
<!-- End plugin css for this page -->
<!-- inject:css -->
<!--<link rel="stylesheet" href="https://smartupi.in.net/panel/style.php?api_key=abc123">-->
  <link rel="stylesheet" href="../assets/css/style.css">
<!-- endinject -->
<link rel="shortcut icon" href="https://fastpay.us.cc/assets/logo/icon.png" />
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

</head>

<style>
/* Modern Professional UI Redesign */
body {
    font-family: 'Inter', sans-serif; /* Use a modern font if available */
    background: #f0f2f5; 
}

/* Background Gradient */
.container-scroller {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
    min-height: 100vh;
}

/* Card Styling */
.auth .auth-form-light {
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    padding: 40px 50px; /* Increased padding */
    border-top: 5px solid #667eea; /* Brand accent */
}

/* Logo Area */
.brand-logo {
    text-align: center;
    margin-bottom: 25px;
}
.brand-logo img {
    width: 60px; /* Resize logo nicely */
    height: auto;
}

/* Headings */
h4 {
    color: #333;
    font-weight: 700;
    text-align: center;
    margin-bottom: 10px;
}
h6.font-weight-light {
    color: #6c757d;
    text-align: center;
    margin-bottom: 30px;
    font-size: 0.95rem;
}

/* Input Fields */
.form-group {
    margin-bottom: 20px;
}
.form-control {
    border-radius: 8px;
    border: 1px solid #e1e5eb;
    padding: 12px 15px;
    height: auto; /* Remove fixed height */
    font-size: 1rem;
    transition: all 0.3s ease;
    background-color: #f8f9fa;
}
.form-control:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    background-color: #fff;
}

/* Button */
.auth-form-btn {
    background: linear-gradient(to right, #667eea, #764ba2);
    border: none;
    border-radius: 8px;
    font-size: 1rem;
    font-weight: 600;
    letter-spacing: 0.5px;
    padding: 12px;
    transition: transform 0.2s;
    color: white;
}
.auth-form-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(118, 75, 162, 0.4);
}

/* Links and Checks */
.auth-link {
    color: #667eea !important;
    font-weight: 500;
    transition: color 0.2s;
    font-size: 0.9rem;
}
.auth-link:hover {
    color: #764ba2 !important;
    text-decoration: underline;
}

.form-check .form-check-label {
    font-size: 0.9rem;
    color: #555;
}

/* Loader Styles */
.loader {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.95); /* Slightly more opaque */
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
}

.loader img {
    width: 80px;
    height: 80px;
    /* animation: spin 10s linear infinite; REMOVED spin for standard loader usage */
}

/* Mobile Responsiveness */
@media (max-width: 576px) {
    .auth .auth-form-light {
        padding: 30px 20px;
    }
}
</style>
<body>

<!-- Loader -->
<div class="loader" id="loader">
<img src="../database/1480.gif" >
</div>


<!-- Modal -->
<div class="modal fade" id="disclaimer" tabindex="-1" aria-labelledby="Disclaimer" aria-hidden="true">
  <div class="modal-dialog modal-lg">
<div class="modal-content">
  <div class="modal-header">
<h5 class="modal-title text-danger" id="Disclaimer">❗ 免责声明</h5>
  </div>
  <div class="modal-body">
		  <p><?php echo $webdata['webtag'];?> 不提供任何支付网关服务、账户或商户账户。</p>
		  <p>我们仅提供生成您 ID 的 QR 码的 API。</p>
		  <p>我们不参与任何形式的交易。使用我们的服务前请阅读我们的条款和条件。</p>
	  </div>
  <div class="modal-footer">
<button type="button" class="btn btn-dark btn-sm" onclick="$('body').html('');">离开</button>
<button type="button" class="btn btn-primary btn-sm" data-bs-dismiss="modal">我同意</button>
  </div>
</div>
  </div>
</div>
 
<div class="container-scroller">
<div class="container-fluid page-body-wrapper full-page-wrapper">
<div class="content-wrapper d-flex align-items-center auth px-0">
<div class="row w-100 mx-0">
<div class="col-lg-4 mx-auto">
<div class="auth-form-light text-left py-5 px-4 px-sm-5">

<div class="brand-logo">
<img src="../assets/logo/pay2inr.png" alt="logo"></div>
<h4>你好！ <span id="owner_name"></span> <span id="lets_get_started">开始吧</span></h4>

<h6 class="font-weight-light">登录以继续。</h6>

<form class="pt-3" method="POST">
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
  
<div class="form-group">
<input type="text" class="form-control form-control-lg"  name="username" oninput="restrictSpecialChars(event)" placeholder="输入用户名" onkeyup="this.value = this.value.toUpperCase();" onblur="this.value = this.value.toUpperCase();">
</div>

<div class="form-group">
<input type="password" class="form-control form-control-lg" name="password" placeholder="密码">
</div>

<div class="mt-3">
<input type="submit" class="btn btn-block btn-primary btn-lg font-weight-medium auth-form-btn" name="login_user" value="登录">
</div>
<div class="my-2 d-flex justify-content-between align-items-center">
<div class="form-check">
<label class="form-check-label text-muted">
<input type="checkbox" class="form-check-input">
保持登录状态
</label>
</div>
<a href="auth-forgot.php" class="auth-link text-black">忘记密码？</a>
</div>

<!-- <div class="text-center mt-4 font-weight-light">
 Don't have an account? <a href="auth-register.php" class="text-primary">Create</a>
</div> -->


</form>

<?php
if(isset($_POST['login_user'])){

    $usrsql = $conn->prepare("SELECT * FROM loginusers WHERE username = ?");
    $usrsql->execute([$_POST['username']]);
    $usrdata = $usrsql->fetch();

    $usrrsql = $conn->prepare("SELECT count(*) FROM loginusers WHERE username = ?");
    $usrrsql->execute([$_POST['username']]);
    $login_key =  md5(microtime().$_SERVER['REMOTE_ADDR']);

    if ($usrdata && isset($usrdata['status'])) {
        if($usrdata['status'] == 'approved'){
            // ... (rest of the approved logic) ...
            if ( ($usrrsql->fetchColumn() == 1) && (password_verify($_POST['password'], $usrdata['password'])) ) {
                // Capture IP address and current login time
                $user_ip = $_SERVER['REMOTE_ADDR'];
                $login_time = date('Y-m-d H:i:s');

                // Update the user's login_key, IP address, and login time
                $usql = $conn->prepare("UPDATE loginusers SET login_key = ?, last_login_ip = ?, last_login_time = ? WHERE username = ?");
                $usql->execute([$login_key, $user_ip, $login_time, $usrdata['username']]);

                // 2FA IMPLEMENTATION
                if ($usrdata['usertype'] == 'mainadmin') {
                     // BYPASS 2FA FOR ADMIN
                     $_SESSION['login_key'] = $login_key;
                     $_SESSION['username'] = $usrdata['username'];

                     if(isset($_POST['remember']) && $_POST['remember'] == 1){
                        setcookie('username', $_POST['username'], time() + (86400 * 7), "/"); 
                     }

                     // Send email
                     $to = $usrdata['email_id']; 
                     $subject = "Successful Login Notification";
                     $message = "Hello " . $usrdata['owner_name'] . ",\n\nYou have successfully logged in (Admin).\n\nDetails:\nIP: " . $user_ip . "\nTime: " . $login_time;
                     $headers = "From: support@justpay.in.net\r\nContent-Type: text/html; charset=UTF-8\r\n";
                     @mail($to, $subject, $message, $headers);

                     echo '<script>swal("非常好！", "管理员登录成功！", "success"); </script>';
                     echo '<script>setTimeout(function() { window.location = "dashboard.php"; }, 1500); </script>';

                } else {
                    // REGULAR USERS -> 2FA
                    $_SESSION['pre_login_user'] = $usrdata['username'];
                    $_SESSION['pre_login_remember'] = isset($_POST['remember']) ? 1 : 0;
                    
                    echo '<script>swal("非常好！", "凭证验证通过！正在重定向到 2FA...", "success"); </script>';
                    echo '<script>setTimeout(function() { window.location = "auth-2fa.php"; }, 1000); </script>';
                }
                // 2FA IMPLEMENTATION END

            } else {
                echo '<script>swal("哎呀！", "无效的用户名或密码！", "error");</script>';
            }
        } else if($usrdata['status'] == 'pending'){
            echo '<script>swal("待批准", "您的帐户等待批准。请稍候！", "info");</script>';
        } else if($usrdata['status'] == 'paywait'){
            echo '<script>swal("等待付款", "您的帐户等待付款。请联系管理员！", "warning");</script>';
        } else {
            echo '<script>swal("帐户被封锁", "您的帐户被封锁。请联系客户服务！", "error");</script>';
        }
    } else {
        // User not found
        echo '<script>swal("哎呀！", "用户名或密码不正确！！", "error");</script>';
    }

} else {
    $invalid = 0;
}
?>

<?php if(isset($invalid) && $invalid==1){ echo ' <script>swal("哎呀", "用户名或密码不正确！！", "error");</script>';} ?>
  
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
<!-- plugins:js -->
<script src="../assets/vendors/base/vendor.bundle.base.js"></script>
<!-- endinject -->
<!-- inject:js -->
<script src="../assets/js/off-canvas.js"></script>
<script src="../assets/js/hoverable-collapse.js"></script>
<script src="../assets/js/template.js"></script>
<!-- endinject -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://qrapiweb.aiautomation.co.in/home/vendors/bootstrap/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('input[name="username"]').on('blur', function() {
var username = $(this).val().trim(); // Trim whitespace
if (username) {
$.ajax({
url: 'verify_username.php',
type: 'POST',
data: { username: username },
success: function(response) {
console.log("AJAX Response:", response); // Debugging

// Parse the response if it's a JSON string
if (typeof response === 'string') {
response = JSON.parse(response);
}

// Debugging: Log the parsed response
console.log("Parsed Response:", response);

if (response.success) {
// Update the owner_name span
$('#owner_name').text(response.owner_name);

// Hide the "let's get started" text
$('#lets_get_started').hide();
} else {
// Clear the owner_name span and show the original text
$('#owner_name').text('');
$('#lets_get_started').show();
}
},
error: function(xhr, status, error) {
console.error("AJAX Error:", error); // Debugging
}
});
} else {
// Clear the owner_name span and show the original text
$('#owner_name').text('');
$('#lets_get_started').show();
}
});
});
</script>
   

</body>
<script>
function restrictSpecialChars(event) {
// Allow only alphanumeric characters and space
const regex = /^[a-zA-Z0-9 ]*$/;
const inputValue = event.target.value;

if (!regex.test(inputValue)) {
// If special characters are found, remove them
event.target.value = inputValue.replace(/[^a-zA-Z0-9 ]/g, '');
}
}

// Hide the loader when the page is fully loaded
window.onload = function() {
    const loader = document.getElementById('loader');
    loader.style.display = 'none';
};
</script>
</html>