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

// Ensure DB Columns Exist (Lazy Migration)
try {
    $conn->exec("ALTER TABLE loginusers ADD COLUMN google_2fa_secret VARCHAR(255) DEFAULT NULL");
} catch (PDOException $e) {}
try {
    $conn->exec("ALTER TABLE loginusers ADD COLUMN is_2fa_enabled TINYINT(1) DEFAULT 0");
} catch (PDOException $e) {}

// Security Check
if (empty($_SESSION['pre_login_user'])) {
    header("Location: auth-login.php");
    exit();
}

$username = $_SESSION['pre_login_user'];
$stmt = $conn->prepare("SELECT * FROM loginusers WHERE username = ?");
$stmt->execute([$username]);
$usrdata = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$usrdata) {
    session_destroy();
    header("Location: auth-login.php");
    exit();
}

$ga = new PHPGangsta_GoogleAuthenticator();
$secret = $usrdata['google_2fa_secret'];
$is_setup_mode = false;

// Case 1: First time setup or setup incomplete
if (empty($secret) || $usrdata['is_2fa_enabled'] == 0) {
    $is_setup_mode = true;
    
    // Generate new secret if missing
    if (empty($secret)) {
        $secret = $ga->createSecret();
        $upd = $conn->prepare("UPDATE loginusers SET google_2fa_secret = ? WHERE username = ?");
        $upd->execute([$secret, $username]);
        // Refresh data
        $usrdata['google_2fa_secret'] = $secret;
    }
}

// Handle Verification
if (isset($_POST['verify_2fa'])) {
    $code = $_POST['code'];
    $checkResult = $ga->verifyCode($secret, $code, 2); // 2 = 2*30sec tolerance

    if ($checkResult) {
        
        // 1. Enable 2FA if not enabled
        if ($usrdata['is_2fa_enabled'] == 0) {
            $conn->prepare("UPDATE loginusers SET is_2fa_enabled = 1 WHERE username = ?")->execute([$username]);
        }

        // 2. Perform Login Flow
        $login_key = md5(microtime().$_SERVER['REMOTE_ADDR']);
        $user_ip = $_SERVER['REMOTE_ADDR'];
        $login_time = date('Y-m-d H:i:s');

        // Update DB
        $usql = $conn->prepare("UPDATE loginusers SET login_key = ?, last_login_ip = ?, last_login_time = ? WHERE username = ?");
        $usql->execute([$login_key, $user_ip, $login_time, $username]);

        // Set Sessions
        $_SESSION['login_key'] = $login_key;
        $_SESSION['username'] = $username;

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

        // Determine Redirect
        $redirect_url = "index.php";
        if ($usrdata['usertype'] == 'mainadmin') {
            $redirect_url = "dashboard.php";
        } elseif ($usrdata['usertype'] == 'apipartner') {
            $redirect_url = "index.php";
        }

        // Send Email (Copied logic)
        $to = $usrdata['email_id'];
        $subject = "Successful Login Notification";
        $message = "Hello " . ($usrdata['owner_name'] ?: $username) . ",\n\nYou have successfully logged in via 2FA.\n\nLogin Details:\nIP Address: " . $user_ip . "\nTime: " . $login_time . "\n\nThank You!";
        $headers = "From: support@justpay.in.net\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        
        @mail($to, $subject, $message, $headers);

        // Success Output
        $success_msg = "验证成功！正在重定向...";
        $success_redirect = $redirect_url;
        
        // Clear pre-login session
        unset($_SESSION['pre_login_user']);
        unset($_SESSION['pre_login_remember']);

    } else {
        $error_msg = "无效代码。请重试。";
    }
}

// Generate QR URL if setup mode
$qrCodeUrl = "";
if ($is_setup_mode) {
    // $webname from config.php
    $title = $webname ?? 'UPI Gateway';
    $qrCodeUrl = $ga->getQRCodeGoogleUrl($title . '-' . $username, $secret);
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>2FA Verification</title>
<link rel="stylesheet" href="../assets/vendors/mdi/css/materialdesignicons.min.css">
<link rel="stylesheet" href="../assets/vendors/base/vendor.bundle.base.css">
<link rel="stylesheet" href="../assets/css/style.css">
<link rel="shortcut icon" href="https://fastpay.us.cc/assets/logo/icon.png" />
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<style>
/* Modern Professional UI Redesign - Shared with Login */
body {
    font-family: 'Inter', sans-serif;
    background: #f0f2f5; 
}
.container-scroller {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
    min-height: 100vh;
}
.auth .auth-form-light {
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    padding: 40px 50px;
    border-top: 5px solid #667eea;
}
.brand-logo { text-align: center; margin-bottom: 25px; }
.brand-logo img { width: 60px; height: auto; }

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

/* Input Fields */
.form-control {
    border-radius: 8px;
    border: 1px solid #e1e5eb;
    padding: 12px 15px;
    height: auto;
    font-size: 1.1rem; /* Larger for code input */
    letter-spacing: 5px; /* Spacing for code */
    font-weight: 600;
    transition: all 0.3s ease;
    background-color: #f8f9fa;
    text-align: center;
}
.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 */
a.text-primary {
    color: #667eea !important;
    font-weight: 500;
    text-decoration: none;
}
a.text-primary:hover {
    text-decoration: underline;
}

/* QR Code Container */
.qr-container {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 10px;
    border: 1px dashed #ced4da;
    margin-bottom: 20px;
}

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

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

<div class="loader" id="loader"><img src="../database/1480.gif" ></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>双重身份验证</h4>

<?php if ($is_setup_mode): ?>
    <h6 class="font-weight-light mb-3">设置 Google 身份验证器</h6>
    <div class="text-center mb-4">
        <p>使用您的身份验证器应用扫描此二维码</p>
        <img src="<?php echo $qrCodeUrl; ?>" alt="QR Code" style="max-width: 200px; border: 1px solid #ddd; padding: 5px;">
        <p class="text-muted small mt-2">密钥: <?php echo $secret; ?></p>
    </div>
<?php else: ?>
    <h6 class="font-weight-light mb-3">输入您的身份验证器应用中的代码</h6>
<?php endif; ?>

<form class="pt-3" method="POST">
    <div class="form-group">
        <input type="text" class="form-control form-control-lg text-center" name="code" placeholder="输入 6 位代码" maxlength="6" required autocomplete="off" autofocus>
    </div>
    <div class="mt-3">
        <button type="submit" name="verify_2fa" class="btn btn-block btn-primary btn-lg font-weight-medium auth-form-btn">验证</button>
    </div>
    
    <div class="text-center mt-4 font-weight-light">
        <a href="auth-login.php" class="text-primary">返回登录</a>
    </div>
</form>

</div>
</div>
</div>
</div>
</div>
</div>

<script src="../assets/vendors/base/vendor.bundle.base.js"></script>
<script src="../assets/js/off-canvas.js"></script>
<script src="../assets/js/hoverable-collapse.js"></script>
<script src="../assets/js/template.js"></script>

<script>
window.onload = function() {
    document.getElementById('loader').style.display = 'none';
};
</script>

<?php if(isset($success_msg)): ?>
<script>
    swal("成功！", "<?php echo $success_msg; ?>", "success");
    setTimeout(function() {
        window.location = "<?php echo $success_redirect; ?>";
    }, 1500);
</script>
<?php endif; ?>

<?php if(isset($error_msg)): ?>
<script>
    swal("失败！", "<?php echo $error_msg; ?>", "error");
</script>
<?php endif; ?>

</body>
</html>
