<?php
/* -----------------------------------------------------------------------------
 * BroRiser AMS - Modern Login (LIGHT MODE, FIXED LOGO WIDTH + CLOUD/SMOKE BG)
 * Stack : Core PHP + MySQLi (NO PDO). DB connection via config.php
 * DB     : utf8mb4 / utf8mb4_general_ci enforced
 * Notes  : - Exact mobile responsive
 *          - Logo width set to clamp(150px, 24vw, 180px)
 *          - Removed moving/tilt/shimmer/orb effects on the box
 *          - Added soft animated "cloud flow / colorful smoke" background
 *          - Device info, geolocation & fingerprint retained
 * ---------------------------------------------------------------------------*/
include('config.php');
date_default_timezone_set('Asia/Kolkata');
@mysqli_set_charset($conn, 'utf8mb4');
@mysqli_query($conn, "SET NAMES 'utf8mb4' COLLATE 'utf8mb4_general_ci'");
@mysqli_query($conn, "SET collation_connection='utf8mb4_general_ci'");
$date = date("Y-m-d", time());

/* ---------- Helpers: IP, UA parsing ---------- */
function getUserIpAddr(){
    if(!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    return $_SERVER['REMOTE_ADDR'] ?? '';
}
$getUserIpAddr = getUserIpAddr();

$arr_browsers = ["Opera","Edg","Chrome","Safari","Firefox","MSIE","Trident"];
$agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$user_browser = '';
foreach ($arr_browsers as $browser) {
    if (strpos($agent, $browser) !== false) { $user_browser = $browser; break; }
}
if ($user_browser === 'MSIE' || $user_browser === 'Trident') $user_browser = 'Internet Explorer';
if ($user_browser === 'Edg') $user_browser = 'Microsoft Edge';

$isMob = is_numeric(strpos(strtolower($agent), "mobile"));
$isTab = is_numeric(strpos(strtolower($agent), "tablet"));
$isWin = is_numeric(strpos(strtolower($agent), "windows"));
$isAndroid = is_numeric(strpos(strtolower($agent), "android"));
$isIPhone = is_numeric(strpos(strtolower($agent), "iphone"));
$isIPad = is_numeric(strpos(strtolower($agent), "ipad"));
$isIOS = $isIPhone || $isIPad;
if($isIOS){ $user_device = 'IOS'; }
elseif($isAndroid){ $user_device = 'ANDROID'; }
elseif($isWin){ $user_device = 'WINDOWS'; }
else { $user_device = 'UNKNOWN'; }

/* ---------- Login Handler ---------- */
@session_start();
$login_error = '';
if (isset($_POST['loginad'])) {
    // Sanitize inputs
    $loginname      = mysqli_real_escape_string($conn, $_POST['loginname'] ?? '');
    $loginpass      = mysqli_real_escape_string($conn, $_POST['loginpass'] ?? '');
    $hardwareModel  = mysqli_real_escape_string($conn, $_POST['hardwareModel'] ?? '');
    $fingerprint    = mysqli_real_escape_string($conn, $_POST['fingerprint'] ?? '');
    $user_browser_p = mysqli_real_escape_string($conn, $_POST['user_browser'] ?? $user_browser);
    $user_device_p  = mysqli_real_escape_string($conn, $_POST['user_device'] ?? $user_device);
    $user_IP        = mysqli_real_escape_string($conn, $_POST['user_IP'] ?? $getUserIpAddr);
    $hardwareName   = mysqli_real_escape_string($conn, $_POST['hardwareName'] ?? '');
    $lat            = mysqli_real_escape_string($conn, $_POST['lat'] ?? '');
    $longt          = mysqli_real_escape_string($conn, $_POST['longt'] ?? '');
    $OfficeDate     = date('Y-m-d');

    // Excluded IPs
    $excludedIPs = ['72.16.0.58'];
    if (in_array($user_IP, $excludedIPs, true)) {
        $status = 'Excluded';
    } else {
        // Duplicate checks for non-excluded IPs
        $initialDupCheckSql = mysqli_query(
            $conn,
            "SELECT 1 FROM tracker_login
             WHERE user_browser='$user_browser_p'
               AND user_device='$user_device_p'
               AND hardwareModel='$hardwareModel'
               AND fingerprint='$fingerprint'
               AND OfficeDate='$OfficeDate'
               AND loginname <> '$loginname'
               AND status='Success'
             LIMIT 1"
        );
        if ($initialDupCheckSql && mysqli_num_rows($initialDupCheckSql) > 0) {
            $refinedDupCheckSql = mysqli_query(
                $conn,
                "SELECT 1 FROM tracker_login
                 WHERE user_browser='$user_browser_p'
                   AND user_device='$user_device_p'
                   AND hardwareModel='$hardwareModel'
                   AND fingerprint='$fingerprint'
                   AND user_IP='$user_IP'
                   AND OfficeDate='$OfficeDate'
                   AND loginname <> '$loginname'
                   AND status='Success'
                 LIMIT 1"
            );
            if ($refinedDupCheckSql && mysqli_num_rows($refinedDupCheckSql) > 0) {
                $status = "Duplicate";
                @mysqli_query($conn,
                    "INSERT INTO tracker_login (user_IP, user_browser, user_device, hardwareName, hardwareModel, fingerprint, loginname, loginpass, status, OfficeDate, lat, longt)
                     VALUES ('$user_IP','$user_browser_p','$user_device_p','$hardwareName','$hardwareModel','$fingerprint','$loginname','$loginpass','$status','$OfficeDate','$lat','$longt')"
                );
                header('Location: duplicate.html'); exit;
            }
        }
        $status = 'Success';
    }

    // Attempt login
    $sql = mysqli_query(
        $conn,
        "SELECT empid FROM hr_dump
         WHERE empid='$loginname' AND Password='$loginpass' AND Status='Active'
         LIMIT 1"
    );
    if ($sql && ($fetch1 = mysqli_fetch_assoc($sql))) {
        $_SESSION['empid']    = $fetch1['empid'];
        $_SESSION['user_id1'] = $fetch1['empid'];
        @mysqli_query($conn,
            "INSERT INTO tracker_login (user_IP, user_browser, user_device, hardwareName, hardwareModel, fingerprint, loginname, loginpass, status, OfficeDate, lat, longt)
             VALUES ('$user_IP','$user_browser_p','$user_device_p','$hardwareName','$hardwareModel','$fingerprint','$loginname','$loginpass','$status','$OfficeDate','$lat','$longt')"
        );
        header("Location: user/dashboard.php"); exit;
    } else {
        $status = "Failed";
        @mysqli_query($conn,
            "INSERT INTO tracker_login (user_IP, user_browser, user_device, hardwareName, hardwareModel, fingerprint, loginname, loginpass, status, OfficeDate, lat, longt)
             VALUES ('$user_IP','$user_browser_p','$user_device_p','$hardwareName','$hardwareModel','$fingerprint','$loginname','$loginpass','$status','$OfficeDate','$lat','$longt')"
        );
        $login_error = 'Sorry! You have entered wrong credentials.';
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, viewport-fit=cover" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>BroRiser AMS Login</title>
<meta name="description" content="BroRiser Attendance Management System">
<meta name="keywords" content="BroRiser Attendance Management System" />
<link rel="icon" type="image/png" href="assets/img/logo.png" sizes="32x32">
<link rel="apple-touch-icon" sizes="180x180" href="assets/img/icon/192x192.png">
<link rel="stylesheet" href="assets/css/bootstrap.css">
<link rel="stylesheet" href="assets/css/style.css">
<style>
/* ---------------- Light, exact mobile-responsive UI ---------------- */
:root{
  --bg1:#f7faff;
  --bg2:#ffffff;
  --bgAccent1:#e6f0ff;
  --bgAccent2:#e8fff8;
  --card:#ffffff;
  --txt:#0b122b;
  --muted:#6b7280;
  --brand:#2563eb;     /* blue-600 */
  --brand2:#06b6d4;    /* cyan-500 */
  --ok:#16a34a;
  --danger:#ef4444;
  --ring1:#7c3aed;     /* violet-600 */
  --ring2:#06b6d4;     /* cyan-500 */
  --ring3:#22c55e;     /* green-500 */
  --radius:20px;
}

/* Soft light background base */
body.modern-bg{
  min-height:100vh;
  background:
    radial-gradient(800px 500px at 10% 15%, var(--bgAccent1) 0%, transparent 60%),
    radial-gradient(900px 600px at 85% 10%, var(--bgAccent2) 0%, transparent 60%),
    linear-gradient(180deg, var(--bg1), var(--bg2));
  color:var(--txt);
  -webkit-font-smoothing:antialiased; -moz-osx-font-smoothing:grayscale;
}

/* ---------- Colorful smoke / cloud flow layers (behind the card) ---------- */
.clouds{ position:fixed; inset:0; overflow:hidden; z-index:0; pointer-events:none; }
.cloud{
  position:absolute; width:160%; height:160%; top:-30%; left:-30%;
  filter: blur(36px);
  opacity:.42;
  mix-blend-mode:multiply;
  background:
    radial-gradient(1200px 700px at 20% 30%, #93c5fd 0%, transparent 60%),
    radial-gradient(1000px 600px at 80% 25%, #c084fc 0%, transparent 60%),
    radial-gradient(900px 500px at 30% 80%, #99f6e4 0%, transparent 60%),
    radial-gradient(1100px 650px at 75% 75%, #fde68a 0%, transparent 60%);
  transform: translate3d(0,0,0);
  will-change: transform, opacity;
}
.cloud.layer1{ animation: flowX 55s linear infinite; }
.cloud.layer2{
  filter: blur(48px);
  opacity:.33;
  animation: flowY 70s linear infinite reverse;
}
.cloud.layer3{
  filter: blur(60px);
  opacity:.25;
  animation: flowXY 95s linear infinite;
}
@keyframes flowX {
  0%   { transform: translateX(-6%) translateY(-2%) rotate(0deg); }
  50%  { transform: translateX(6%)  translateY( 2%) rotate(180deg); }
  100% { transform: translateX(-6%) translateY(-2%) rotate(360deg); }
}
@keyframes flowY {
  0%   { transform: translateX(2%)  translateY(-6%) rotate(0deg); }
  50%  { transform: translateX(-2%) translateY(6%)  rotate(-180deg); }
  100% { transform: translateX(2%)  translateY(-6%) rotate(-360deg); }
}
@keyframes flowXY {
  0%   { transform: translateX(-4%) translateY(4%) rotate(0deg) scale(1); }
  50%  { transform: translateX(4%)  translateY(-4%) rotate(180deg) scale(1.02); }
  100% { transform: translateX(-4%) translateY(4%) rotate(360deg) scale(1); }
}

/* Center container (card sits above clouds) */
.auth-wrap{ position:relative; z-index:2; min-height:100svh; display:flex; align-items:center; justify-content:center; padding:clamp(12px,3vw,24px); }

/* Glass card with STATIC glow edge (no rotation / no moving box) */
.glass-card{
  position:relative;
  width:min(520px, 100%);
  border-radius:var(--radius);
  background: linear-gradient(180deg, rgba(255,255,255,.94), rgba(255,255,255,.90));
  backdrop-filter: blur(8px);
  border:1px solid rgba(15, 23, 42, 0.06);
  box-shadow:
    0 18px 60px rgba(2,8,23,.06),
    0 1px 0 rgba(255,255,255,.85) inset;
  overflow:hidden;
}
/* Static pastel edge glow */
.glass-card::before{
  content:"";
  position:absolute; inset:0;
  padding:2px; border-radius:inherit;
  background:conic-gradient(from 0deg, var(--ring1), var(--ring2), var(--ring3), var(--ring1));
  -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
  -webkit-mask-composite: xor; mask-composite: exclude;
  filter: blur(1.1px) saturate(1.05);
  /* No animation here per requirement */
  pointer-events:none;
}

/* Inner */
.card-inner{ position:relative; z-index:2; padding:clamp(18px,4vw,28px); }

/* Brand header with FIXED requested logo width */
.brand{
  display:flex; flex-direction:column; align-items:center; gap:10px; text-align:center;
}
.brand img{
  width: clamp(150px, 24vw, 180px); /* as requested */
  height: auto;
  border-radius:12px;
  box-shadow:0 8px 24px rgba(2,8,23,.08);
  background:#fff;
}
.brand h1{ font-size:clamp(20px,3.4vw,26px); margin:8px 0 4px; color:#0f172a; font-weight:800; letter-spacing:.2px; }
.brand p{ margin:0; color:var(--muted); font-size:clamp(12px,2.8vw,14px); }

/* Form */
.form-modern .form-label{ color:#334155; font-weight:700; letter-spacing:.2px; }
.form-modern .form-control{
  background:#ffffff;
  border:1px solid rgba(15, 23, 42, 0.12);
  color:#0f172a;
  border-radius:14px;
  padding:12px 14px;
  box-shadow:0 1px 0 rgba(255,255,255,.9) inset;
  transition: box-shadow .2s ease, border-color .2s ease, transform .12s ease;
}
.form-modern .form-control::placeholder{ color:#9aa3b2; }
.form-modern .form-control:focus{
  outline:0;
  border-color:rgba(37,99,235,.6);
  box-shadow:
    0 0 0 4px rgba(37,99,235,.12),
    0 0 14px rgba(37,99,235,.10),
    0 1px 0 rgba(255,255,255,.9) inset;
  background:#fff;
  transform: translateY(-1px);
}
.input-wrap{ position:relative; }
.input-trailing{
  position:absolute; right:10px; top:50%; transform:translateY(-50%);
  background:transparent; border:0; color:#64748b; padding:6px 8px; border-radius:10px;
  transition: color .15s ease, transform .15s ease;
}
.input-trailing:hover{ color:#0f172a; transform: scale(1.05); }

/* CTA (subtle breathing shadow, not moving the box) */
.btn-modern{
  background: linear-gradient(90deg, var(--brand), var(--brand2));
  color:#ffffff; border:0; border-radius:14px; font-weight:800; letter-spacing:.3px;
  padding:12px 18px; width:100%;
  box-shadow: 0 2px 0 rgba(255,255,255,.6) inset, 0 0 0 0 rgba(37,99,235,.18);
  transition: transform .06s ease, filter .2s ease, box-shadow .6s ease;
  animation: ctabreathe 4s ease-in-out infinite;
}
.btn-modern:hover{ filter:brightness(1.05); }
.btn-modern:active{ transform:translateY(1px) scale(.995); }
@keyframes ctabreathe{
  0%,100%{ box-shadow: 0 2px 0 rgba(255,255,255,.6) inset, 0 0 10px 0 rgba(37,99,235,.12); }
  50%{    box-shadow: 0 2px 0 rgba(255,255,255,.6) inset, 0 0 18px 2px rgba(6,182,212,.22); }
}

/* helper text */
.helper{
  color:#475569;
  font-size:12px;
  line-height:1.65;
  border-top:1px dashed rgba(15, 23, 42, 0.12);
  padding-top:12px; margin-top:16px;
}

/* Alert styles */
.alert-modern{
  border-radius:12px;
  padding:10px 12px;
  background:rgba(239, 68, 68, .08);
  color:#7f1d1d;
  border:1px solid rgba(239, 68, 68, .35);
}

/* Small print footer */
.copy{
  display:block; text-align:center; color:#64748b; font-size:12px; margin-top:14px;
}

/* Accessibility: reduce motion */
@media (prefers-reduced-motion: reduce) {
  .cloud.layer1, .cloud.layer2, .cloud.layer3, .btn-modern { animation: none !important; }
}
</style>
</head>

<body class="modern-bg">
<!-- Colorful smoke / cloud flow backdrop -->
<div class="clouds" aria-hidden="true">
  <span class="cloud layer1"></span>
  <span class="cloud layer2"></span>
  <span class="cloud layer3"></span>
</div>

<div class="auth-wrap">
  <div class="glass-card">
    <div class="card-inner">
      <div class="brand">
        <!-- Requested logo width -->
        <img src="assets/img/logo.png" alt="BroRiser Logo">
        <h1>BroRiser AMS</h1>
        <p>Attendance Management System • Secure Login</p>
      </div>

      <?php if ($login_error): ?>
        <div class="alert-modern mt-3" role="alert"><?php echo htmlspecialchars($login_error, ENT_QUOTES, 'UTF-8'); ?></div>
      <?php endif; ?>

      <form class="form-modern mt-3" action="" method="post" enctype="multipart/form-data" autocomplete="off" novalidate>
        <!-- Hidden telemetry -->
        <input type="hidden" id="user_IP" name="user_IP" value="<?php echo htmlspecialchars($getUserIpAddr, ENT_QUOTES, 'UTF-8'); ?>">
        <input type="hidden" id="user_browser" name="user_browser" value="<?php echo htmlspecialchars($user_browser, ENT_QUOTES, 'UTF-8'); ?>">
        <input type="hidden" id="user_device" name="user_device" value="<?php echo htmlspecialchars($user_device, ENT_QUOTES, 'UTF-8'); ?>">
        <input type="hidden" id="hardwareName" name="hardwareName">
        <input type="hidden" id="hardwareModel" name="hardwareModel">
        <input type="hidden" id="fingerprint" name="fingerprint">
        <input type="hidden" name="lat" id="lat">
        <input type="hidden" name="longt" id="longt">

        <div class="mb-3">
          <label for="loginname" class="form-label">Employee ID</label>
          <input type="text" class="form-control" id="loginname" name="loginname" maxlength="20" placeholder="e.g. RE001" required
                 onclick="getMyLocation();" onkeyup="this.value=this.value.toUpperCase();">
        </div>

        <div class="mb-3 input-wrap">
          <label for="loginpass" class="form-label">Password</label>
          <input type="password" class="form-control" id="loginpass" name="loginpass" placeholder="Password" maxlength="20" required>
          <button type="button" class="input-trailing" aria-label="Toggle password visibility" onclick="togglePass()">
            <span id="eye">👁️</span>
          </button>
        </div>

        <button type="submit" name="loginad" class="btn-modern mt-2" onclick="saveUsername()">Login</button>

        <div class="helper">
          • Best on latest Chrome / Safari<br>
          • Use Mobile Data to access AMS Portal<br>
          • Clear browser history before punching attendance<br>
          • Allow location access to the browser<br>
          • Select the location from drop down
        </div>
        <span class="copy">© <script>document.write(new Date().getFullYear());</script> All Rights Reserved</span>
      </form>

      <!-- hidden device debug to avoid JS errors -->
      <div id="htmlExampleOutput" class="visually-hidden"></div>
    </div>
  </div>
</div>

<script src="assets/js/lib/bootstrap.bundle.min.js"></script>
<script src="assets/js/plugins/splide/splide.min.js"></script>
<script src="assets/js/base.js"></script>
<script src="client.js"></script>
<script async src="https://cloud.51degrees.com/api/v4/AQR6ugX3KzEAXStH3Eg.js"></script>
<script>
/* ---------------- UI Helpers ---------------- */
function togglePass(){
  const i = document.getElementById('loginpass');
  const e = document.getElementById('eye');
  if(i.type === 'password'){ i.type='text'; e.textContent='🙈'; } else { i.type='password'; e.textContent='👁️'; }
}
function saveUsername(){
  try { localStorage.setItem('ams_empid', document.getElementById('loginname').value.trim()); } catch(e){}
}
(function prefill(){
  try {
    const v = localStorage.getItem('ams_empid'); if(v){ document.getElementById('loginname').value = v; }
  } catch(e){}
})();

/* ---------------- Geolocation ---------------- */
function getMyLocation(){
  if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(function(position){
      document.getElementById('lat').value   = position.coords.latitude || '';
      document.getElementById('longt').value = position.coords.longitude || '';
    }, function(err){
      console.warn('Geolocation error:', err && err.message ? err.message : err);
    }, {enableHighAccuracy:true, timeout:10000, maximumAge:300000});
  }
}

/* ---------------- 51Degrees (Hardware info) ---------------- */
document.body.onload = function() {
  if (typeof fod !== 'undefined' && fod.complete) {
    fod.complete(function (data) {
      document.getElementById('hardwareName').value  = (data.device && (data.device.hardwarename || data.device["hardwarename"])) || 'Unknown';
      document.getElementById('hardwareModel').value = (data.device && (data.device.hardwaremodel || data.device["hardwaremodel"])) || 'Unknown';
      displayDeviceData(data);
    });
  }
};
function displayDeviceData(data) {
  var outputDiv = document.getElementById("htmlExampleOutput");
  if(!outputDiv) return;
  outputDiv.innerHTML = "HardwareModel: " + ((data.device && (data.device["hardwaremodel"]||data.device.hardwaremodel)) || 'Unknown') + "<br>" +
                        "HardwareName: "  + ((data.device && (data.device["hardwarename"]||data.device.hardwarename)) || 'Unknown');
}

/* ---------------- ClientJS Fingerprint ---------------- */
(function(){
  try{
    var client = new ClientJS();
    var fingerprint = client.getFingerprint();
    document.getElementById('fingerprint').value = fingerprint;
  }catch(e){ console.warn('ClientJS not available', e); }
})();
</script>

<!-- Optional: Anti-tamper (disabled)
<script>
  // document.addEventListener('contextmenu', e => e.preventDefault());
  // document.addEventListener('keydown', function(e){ if(e.ctrlKey || e.key==="F12"){ e.preventDefault(); }});
</script>
-->
</body>
</html>
