<?php
require 'database.php';
$error="";

if(isset($_REQUEST['loginsubmit']))
{
$login_email = mysqli_real_escape_string($con, $_POST['login_email']);
$login_password =mysqli_real_escape_string($con, $_POST['login_password']);


if($login_email!='' AND $login_password!='')
{
$loginpassword=md5($login_password);
$adminquery="select user_id from user_master where user_email='$login_email' AND user_password='$loginpassword'";
$adminresult=mysqli_query($con,$adminquery);
$admindata  = mysqli_fetch_array($adminresult);
$user_id=$admindata['user_id'];
$count=mysqli_num_rows($adminresult);
if($count==1)
{
	$_SESSION['user_id'] = $user_id;
	echo '<script> window.location="index"; </script>';
	/*
	$_SESSION['user_id'] = $user_id;
    echo '<script> 
            window.onload = function() {
                registerPushNotification();
            };
          </script>';
	*/
}
else
{
$error="Your Username or Password is invalid";
}	
}
else
{
 $error="Please Enter Username and Password";	
}
	
}
?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="keywords" content="">

    <link rel="icon" href="assets/img/favicon.png" type="image/x-icon">
    <link rel="shortcut icon" href="assets/img/favicon.png" type="image/x-icon">
    <title> SNA Associates </title>
    <!-- Google font-->
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&amp;display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&amp;display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Rubik:ital,wght@0,400;0,500;0,600;0,700;0,800;0,900;1,300;1,400;1,500;1,600;1,700;1,800;1,900&amp;display=swap" rel="stylesheet">
    <!-- Font Awesome-->
    <link rel="stylesheet" type="text/css" href="assets/css/fontawesome.css">
    <!-- ico-font-->
    <link rel="stylesheet" type="text/css" href="assets/css/icofont.css">
    <!-- Themify icon-->
    <link rel="stylesheet" type="text/css" href="assets/css/themify.css">
    <!-- Flag icon-->
    <link rel="stylesheet" type="text/css" href="assets/css/flag-icon.css">
    <!-- Feather icon-->
    <link rel="stylesheet" type="text/css" href="assets/css/feather-icon.css">
    <!-- Plugins css start-->
    <link rel="stylesheet" type="text/css" href="assets/css/sweetalert2.css">
    <!-- Plugins css Ends-->
    <!-- Bootstrap css-->
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
    <!-- App css-->
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
    <link id="color" rel="stylesheet" href="assets/css/color-1.css" media="screen">
    <!-- Responsive css-->
    <link rel="stylesheet" type="text/css" href="assets/css/responsive.css">
    
    <link rel="manifest" href="/sna/manifest.json">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="SNA ERP">

<script>
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sna/sw.js').then(function(registration) {
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}
</script>

<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js"></script>

<script>
  // Your Firebase configuration
  const firebaseConfig = {
    apiKey: "AIzaSyDGlBocq5uuiaU8lDi1M1lHRV20xJSjW8g",
    projectId: "sna-crm-software",
    messagingSenderId: "1004217416886",
    appId: "1:1004217416886:web:29790211f3156c07c0fa17"
  };
  
  firebase.initializeApp(firebaseConfig);
  const messaging = firebase.messaging();

  // Function to get token and save via AJAX
  function registerPushNotification() {
    // 1. Pehle check karein ki browser Service Worker support karta hai ya nahi
    if ('serviceWorker' in navigator) {
        
        // 2. Wait karein jab tak Service Worker ready na ho jaye
        navigator.serviceWorker.ready.then((registration) => {
            
            console.log("Service Worker ready, fetching token...");

            // 3. Get Token - Registration object pass karna zaruri hai
            messaging.getToken({ 
                vapidKey: 'BBjvzb60aFQY9P1RhTOCsxwk0EmWDBjt8RWSphJ64sTftgY44l3GxDp4SpxQYjZOMt0IDzCOqnpzX7jYffOQqMY',
                serviceWorkerRegistration: registration  // <--- Yeh missing tha
            })
            .then((currentToken) => {
                if (currentToken) {
                    console.log("Token Generated: ", currentToken);
                    
                    // 4. AJAX to Save Token
                    $.ajax({
                        url: 'save_token.php',
                        type: 'POST',
                        data: { token: currentToken },
                        success: function(response) {
                            //console.log("Server Response: " + response);
                            window.location="index"; 
                        },
                        error: function() {
                            //console.log("AJAX Error: Token save failed");
                            window.location="index";
                        }
                    });
                } else {
                    console.warn("No registration token available. Request permission first.");
                    window.location="index";
                }
            })
            .catch((err) => {
                // Yahan aapko exact error dikhega console mein
                console.error('FCM Token Error: ', err);
                // Testing khatam hone ke baad niche wali line uncomment karein
                // window.location="index"; 
            });
        });
    } else {
        console.log("Service workers are not supported in this browser.");
        window.location="index";
    }
}
</script>

  </head>
  <body>
    <!-- Loader starts-->
    <div class="loader-wrapper">
      <div class="theme-loader">    
        <div class="loader-p"></div>
      </div>
    </div>
    <!-- Loader ends-->
    <!-- page-wrapper Start-->
    <section>         
      <div class="container-fluid p-0">
        <div class="row">
          <div class="col-12">              
            <div class="login-card">
              <form class="theme-form login-form" action="" method="post">
			    <center> <img src="assets/img/logo.png" style="width:220px"> </center>
                <h4>Login</h4>
                <h6>Welcome back! Log in to your account.</h6>
                <div class="form-group">
                  <label>Email Address</label>
                  <div class="input-group"><span class="input-group-text"><i class="icon-email"></i></span>
                    <input class="form-control" name="login_email" type="email" required="" placeholder="Test@gmail.com">
                  </div>
                </div>
                <div class="form-group">
                  <label>Password</label>
                  <div class="input-group"><span class="input-group-text"><i class="icon-lock"></i></span>
                    <input class="form-control" name="login_password" type="password" required="" placeholder="*********">
                    <!-- <div class="show-hide"><span class="show"></span></div> -->
                  </div>
                </div>
                 
				<div class="form-group">
                  <div class="checkbox">
                    <input id="checkbox1" type="checkbox">
                   <!-- <label class="text-muted" for="checkbox1">Remember password</label> -->
                  </div><a class="link" href="forget-password">Forgot password?</a>
                </div>
				
                <div class="form-group">
                  <button class="btn btn-primary btn-block" type="submit" name="loginsubmit">Sign in</button>
                </div>
                
				<?php
				if($error)
				{
				?>
				<div class="m-t-2"><p class="text-danger"><?php echo $error; ?></p></div>
				<?php
				}
				?>
              </form>
            </div>
          </div>
        </div>
      </div>
    </section>
    <!-- page-wrapper end-->
	
	
    <!-- latest jquery-->
    <script src="assets/js/jquery-3.5.1.min.js"></script>
    <!-- feather icon js-->
    <script src="assets/js/icons/feather-icon/feather.min.js"></script>
    <script src="assets/js/icons/feather-icon/feather-icon.js"></script>
    <!-- Sidebar jquery-->
    <script src="assets/js/sidebar-menu.js"></script>
    <script src="assets/js/config.js"></script>
    <!-- Bootstrap js-->
    <script src="assets/js/bootstrap/popper.min.js"></script>
    <script src="assets/js/bootstrap/bootstrap.min.js"></script>
    <!-- Plugins JS start-->
    <script src="assets/js/sweet-alert/sweetalert.min.js"></script>
    <!-- Plugins JS Ends-->
    <!-- Theme js-->
    <script src="assets/js/script.js"></script>
    <!-- login js-->
    <!-- Plugin used-->
  </body>
</html>