<?php
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.gc_maxlifetime', 60 * 60 * 24 * 365);
    session_set_cookie_params([
        'lifetime' => 60 * 60 * 24 * 365,
        'path' => '/',
        'samesite' => 'Lax',
    ]);
}
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "config.php";

include_once __DIR__ . '/../includes/white_label_lib.php';
block_if_white_label_domain($conn);

if (isset($_SESSION['username'])) {
    header('Location: dashboard');
    exit;
}

if (isset($_POST['submit'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $remember = isset($_POST['remember']);

    $query = "SELECT * FROM users WHERE mobile = '$username'";
    $run = mysqli_query($conn, $query);
    $row = mysqli_fetch_array($run);

    if (mysqli_num_rows($run) > 0) {
        $hashFromDatabase = $row['password'];
        $acc_lock = $row['acc_lock'] ?? 0;
        $acc_ban = $row['acc_ban'] ?? 'off';
        $byteuserid = $row['id'];

        if ($acc_ban == 'on') {
            echo '<script>document.addEventListener("DOMContentLoaded",function(){Swal.fire({title:"Account Blocked!",text:"Please contact the administrator.",icon:"error",confirmButtonText:"Ok",background:"#14141f",color:"#fff"}).then(()=>{window.location.href="index";});});</script>';
        } elseif ($acc_lock >= 3) {
            // BUG FIX: previously acc_lock reaching 3 only showed a warning
            // message — it never actually stopped the login. The very next
            // attempt still ran password_verify() as normal, so a correct
            // password logged the user in anyway and silently reset the
            // lock to 0. The lockout is now actually enforced here: once
            // locked, login is refused (even with the right password) until
            // an admin resets it from Merchant List.
            echo '<script>document.addEventListener("DOMContentLoaded",function(){Swal.fire({title:"Account Locked!",text:"Too many failed attempts. Contact admin to unlock your account.",icon:"error",confirmButtonText:"Ok",background:"#14141f",color:"#fff"}).then(()=>{window.location.href="index";});});</script>';
        } elseif (password_verify($password, $hashFromDatabase)) {
            if (($row['email_verified'] ?? 'Yes') === 'No' && !empty($row['email'])) {
                // Registered but never finished email verification - send
                // them to finish that first instead of logging in.
                $_SESSION['pending_otp_user_id'] = $byteuserid;
                echo '<script>window.location.href = "verify_email_otp";</script>';
                exit;
            }

            // "Remember me" previously did nothing at all — the checkbox
            // was collected in $_POST but never referenced anywhere. Now it
            // extends the session cookie to 30 days instead of the default
            // browser-session-only cookie.
            // Stay logged in until the user manually logs out (Amazon-style) -
            // no more re-login after closing the browser, "remember me" or not.
            $params = session_get_cookie_params();
            setcookie(session_name(), session_id(), time() + (365 * 24 * 60 * 60), $params["path"], $params["domain"], $params["secure"], $params["httponly"]);

            $siteSettingsRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT login_otp_enabled FROM site_settings LIMIT 1"));
            $loginOtpOn = $siteSettingsRow ? ((int)($siteSettingsRow['login_otp_enabled'] ?? 1) === 1) : true;
            // The Profile page's own "OTP Verification" toggle lets each
            // user opt out individually - that must win over the admin's
            // site-wide default for that specific user.
            if (($row['is_otp'] ?? '') === 'NO') {
                $loginOtpOn = false;
            }

            if ($loginOtpOn && !empty($row['email'])) {
                include_once "../includes/notify_lib.php";
                $_SESSION['pending_login_user_id'] = $byteuserid;
                $_SESSION['pending_login_remember'] = $remember;
                $otpResult = issue_email_otp($conn, $byteuserid, $row['email'], $row['name'] ?? $username, 'login');
                if ($otpResult['ok']) {
                    echo '<script>window.location.href = "verify_login_otp";</script>';
                    exit;
                }
                // Email failed to send - don't lock the user out of their
                // own account over an SMTP hiccup, log them straight in,
                // but SHOW the real reason so it's fixable instead of a
                // silent fallback that looks like "OTP is just not working".
                unset($_SESSION['pending_login_user_id'], $_SESSION['pending_login_remember']);
                echo '<script>alert("Login OTP email nahi bhej paya (" + ' . json_encode($otpResult['message']) . ' + ") - is baar bina OTP ke login kar rahe hain. Website Manage me SMTP settings check karein.");</script>';
            }

            $_SESSION["username"] = $username;
            $_SESSION["user_id"] = $byteuserid;
            $query2 = "UPDATE users SET acc_lock = 0 WHERE mobile = '$username'";
            mysqli_query($conn, $query2);
            if (!empty($row['email'])) {
                include_once "../includes/notify_lib.php";
                send_login_alert($conn, $byteuserid, $row['email'], $row['name'] ?? $username);
            }
            echo '<script>window.location.href = "dashboard";</script>';
            exit;
        } else {
            $acc_lock++;
            $query3 = "UPDATE users SET acc_lock = $acc_lock WHERE mobile = '$username'";
            mysqli_query($conn, $query3);
            if ($acc_lock >= 3) {
                echo '<script>document.addEventListener("DOMContentLoaded",function(){Swal.fire({title:"Account Locked!",text:"Too many failed attempts. Contact admin.",icon:"error",confirmButtonText:"Ok",background:"#14141f",color:"#fff"}).then(()=>{window.location.href="index";});});</script>';
            } else {
                $attemptsLeft = 3 - $acc_lock;
                echo '<script>document.addEventListener("DOMContentLoaded",function(){Swal.fire({title:"Wrong Password!",text:"Please try again. ' . $attemptsLeft . ' attempt(s) left before your account is locked.",icon:"error",background:"#14141f",color:"#fff"});});</script>';
            }
        }
    } else {
        echo '<script>document.addEventListener("DOMContentLoaded",function(){Swal.fire({title:"Not Found!",text:"No account with this mobile number.",icon:"error",background:"#14141f",color:"#fff"});});</script>';
    }
}

// Get site settings
$sq = mysqli_query($conn, "SELECT * FROM site_settings LIMIT 1");
$site_settings = mysqli_num_rows($sq) > 0 ? mysqli_fetch_assoc($sq) : ['brand_name'=>'VIP Gateway','logo_url'=>''];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
<title><?php echo htmlspecialchars($site_settings['brand_name']); ?> | Login</title>
<link rel="icon" type="image/x-icon" href="../common/img/favicon.png"/>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#0a0a12;position:relative;overflow:hidden}
.bg-animated{position:fixed;inset:0;z-index:0;background:linear-gradient(135deg,#0a0a12,#0f0c29,#1a0533);background-size:400% 400%;animation:bgShift 8s ease infinite}
@keyframes bgShift{0%{background-position:0% 50%}50%{background-position:100% 50%}100%{background-position:0% 50%}}
.orb{position:fixed;border-radius:50%;filter:blur(80px);opacity:.25;pointer-events:none}
.o1{width:400px;height:400px;background:#6c63ff;top:-100px;left:-100px;animation:orbF 7s ease-in-out infinite alternate}
.o2{width:300px;height:300px;background:#e040fb;bottom:-80px;right:-80px;animation:orbF 9s ease-in-out infinite alternate-reverse}
@keyframes orbF{0%{transform:scale(1)}100%{transform:scale(1.2) translate(20px,15px)}}
.grid{position:fixed;inset:0;background-image:linear-gradient(rgba(108,99,255,.06) 1px,transparent 1px),linear-gradient(90deg,rgba(108,99,255,.06) 1px,transparent 1px);background-size:50px 50px;z-index:0}
.wrapper{position:relative;z-index:1;width:100%;max-width:420px;padding:20px}
.card{background:rgba(255,255,255,.05);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.1);border-radius:24px;padding:40px 36px;box-shadow:0 25px 60px rgba(0,0,0,.4)}
.brand{text-align:center;margin-bottom:32px}
.brand-logo{width:60px;height:60px;border-radius:18px;background:linear-gradient(135deg,#6c63ff,#e040fb);display:flex;align-items:center;justify-content:center;margin:0 auto 16px;font-size:26px;color:#fff;box-shadow:0 8px 24px rgba(108,99,255,.4);overflow:hidden}
.brand-logo img{width:100%;height:100%;object-fit:cover;border-radius:18px}
.brand h1{font-size:22px;font-weight:800;color:#fff;margin-bottom:4px}
.brand p{font-size:13px;color:rgba(255,255,255,.45)}
.fg{margin-bottom:18px}
.fg label{display:block;font-size:12px;font-weight:600;color:rgba(255,255,255,.6);margin-bottom:7px;text-transform:uppercase;letter-spacing:.4px}
.iw{position:relative}
.iw i{position:absolute;left:14px;top:50%;transform:translateY(-50%);color:rgba(255,255,255,.3);font-size:14px}
.iw input{width:100%;background:rgba(255,255,255,.07);border:1.5px solid rgba(255,255,255,.1);border-radius:12px;padding:13px 14px 13px 42px;font-size:14px;color:#fff;outline:none;transition:.3s;font-family:'Inter',sans-serif}
.iw input::placeholder{color:rgba(255,255,255,.2)}
.iw input:focus{border-color:#6c63ff;background:rgba(108,99,255,.1);box-shadow:0 0 0 4px rgba(108,99,255,.15)}
.eye{position:absolute;right:14px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:rgba(255,255,255,.3);font-size:14px}
.opts{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px}
.rem{display:flex;align-items:center;gap:8px;cursor:pointer}
.rem input{width:16px;height:16px;accent-color:#6c63ff;cursor:pointer}
.rem span{font-size:13px;color:rgba(255,255,255,.45)}
.forgot{font-size:13px;color:#6c63ff;text-decoration:none}
.forgot:hover{color:#a78bfa}
.btn-login{width:100%;padding:14px;background:linear-gradient(135deg,#6c63ff,#e040fb);border:none;border-radius:12px;font-size:15px;font-weight:700;color:#fff;cursor:pointer;transition:.3s;font-family:'Inter',sans-serif;letter-spacing:.3px}
.btn-login:hover{transform:translateY(-2px);box-shadow:0 10px 30px rgba(108,99,255,.4)}
.btn-login:active{transform:translateY(0)}
.divider{display:flex;align-items:center;gap:12px;margin:22px 0;color:rgba(255,255,255,.15);font-size:12px}
.divider::before,.divider::after{content:'';flex:1;height:1px;background:rgba(255,255,255,.08)}
.reg-link{text-align:center;font-size:13px;color:rgba(255,255,255,.4)}
.reg-link a{color:#6c63ff;text-decoration:none;font-weight:600;margin-left:4px}
.reg-link a:hover{color:#a78bfa}
.badges{display:flex;align-items:center;justify-content:center;gap:16px;margin-top:18px;flex-wrap:wrap}
.bi{display:flex;align-items:center;gap:5px;font-size:11px;color:rgba(255,255,255,.25)}
.bi i{color:#43e97b;font-size:12px}
@media(max-width:480px){.card{padding:28px 20px;border-radius:16px}.wrapper{padding:14px}}
</style>
</head>
<body>
<div class="bg-animated"></div>
<div class="orb o1"></div>
<div class="orb o2"></div>
<div class="grid"></div>
<div class="wrapper">
  <div class="card">
    <div class="brand">
      <div class="brand-logo">
        <?php if(!empty($site_settings['logo_url'])): ?>
        <img src="../<?php echo htmlspecialchars($site_settings['logo_url']); ?>" alt="Logo" onerror="this.style.display='none';this.parentElement.innerHTML='<i class=\'fas fa-bolt\'></i>'">
        <?php else: ?>
        <i class="fas fa-bolt"></i>
        <?php endif; ?>
      </div>
      <h1>Welcome Back 👋</h1>
      <p>Sign in to <?php echo htmlspecialchars($site_settings['brand_name']); ?></p>
    </div>
    <form action="index.php" method="POST" autocomplete="off">
      <div class="fg">
        <label>Mobile Number</label>
        <div class="iw">
          <i class="fas fa-mobile-alt"></i>
          <input type="text" name="username" placeholder="Enter mobile number" required autofocus oninput="this.value=this.value.replace(/[^0-9]/g,'').slice(0,10)"/>
        </div>
      </div>
      <div class="fg">
        <label>Password</label>
        <div class="iw">
          <i class="fas fa-lock"></i>
          <input type="password" name="password" id="passInput" placeholder="Enter your password" required/>
          <button type="button" class="eye" onclick="togglePass()"><i class="fas fa-eye" id="eyeIcon"></i></button>
        </div>
      </div>
      <div class="opts">
        <label class="rem"><input type="checkbox" name="remember"><span>Remember me</span></label>
        <a href="../forgot-password" class="forgot">Forgot password?</a>
      </div>
      <button class="btn-login" type="submit" name="submit">
        <i class="fas fa-sign-in-alt" style="margin-right:8px"></i>Login to Dashboard
      </button>
    </form>
    <div class="divider">or</div>
    <p class="reg-link">Don't have an account?<a href="../Register">Create Account</a></p>
    <div class="badges">
      <span class="bi"><i class="fas fa-shield-alt"></i>SSL Secured</span>
      <span class="bi"><i class="fas fa-lock"></i>Encrypted</span>
      <span class="bi"><i class="fas fa-check-circle"></i>Verified</span>
    </div>
  </div>
</div>
<script>
function togglePass(){
  var i=document.getElementById('passInput'),e=document.getElementById('eyeIcon');
  i.type=i.type==='password'?'text':'password';
  e.className=i.type==='password'?'fas fa-eye':'fas fa-eye-slash';
}
</script>
</body>
</html>
