<?php 
//include('dist/header.php');
include('dist/db.php');
$error = '';
if(isset($_POST['check_company']) && !empty($_POST['check_company'])){
        $comp_name      = $_POST['check_company'];
        if($comp_name != 'admin'){
            $check_comp = mysqli_query($conn, "select * FROM db_users where type='company' and LOWER(username)='".strtolower($comp_name)."'");
            if($check_comp->num_rows == 0){ 
                echo "Company not found.";
                die();
            } else {
                echo "1";
                die();
            }
        } else {
            echo "1";
            die();
        }
}
if(isset($_POST['login'])){
    $email          = $_POST['email'];
    $pass           = md5($_POST['password']);
    $comp_name      = $_POST['company_domain'];
    $comp_not_exist = 0;

    $emp_list = '';
    $error = 'Incorrect email or password.';
    $red_url = 'dist/index.php';
    if($comp_name == 'admin'){
        $emp_list = mysqli_fetch_assoc(mysqli_query($conn, "select * from db_users where email='$email' and password='$pass' and type='admin' "));
        $error = '';
    } else {
        $check_comp = mysqli_query($conn, "select * FROM db_users where type='company' and LOWER(username)='".strtolower($comp_name)."'");
        if($check_comp->num_rows > 0){
            $comp_id = mysqli_fetch_assoc($check_comp)['id'];
            $emp_list = mysqli_fetch_assoc(mysqli_query($conn, "select * from db_users where email='$email' and password='$pass'"));
            
            if($emp_list['type'] == 'company' && $emp_list['id'] == $comp_id){
                $error = '';
               $red_url = '/company/'.strtolower($comp_name)."/";
                
            } else {
                if($emp_list['company_name'] == $comp_id){
                     $error = '';
                     $red_url = '/company/'.strtolower($comp_name)."/";
                } else {
                     $error = 'Incorrect email or password or company name.';
                }
                if(empty($emp_list)){
                    $error = 'Incorrect email or password.';
                }

            }

        } else {
            $comp_not_exist = 1;
        }

    }

  
    if(empty($error)){

        $_SESSION['loggedin_user'] = $emp_list['id'];
        echo $red_url;
        //echo "<script>window.location.href='".$red_url."';</script>";


    } else {
        if($comp_not_exist == 1):
            $error = 'Company not found.';
        endif;
        echo $error;
        
    }
    die();
}

   
?>  
<!doctype html>
<html class="no-js" lang="en" dir="ltr">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>::Timesheethub:: Signin</title>
    <link rel="icon" href="<?= $site_url; ?>favicon.ico" type="image/x-icon"> <!-- Favicon-->

    <!-- project css file  -->
    <link rel="stylesheet" href="<?= $site_url; ?>/assets/css/timetracker.style.min.css">
</head>

<body>
    <div id="timetracker-layout" class="theme-mist">

        <!-- main body area -->
        <div class="main p-2 py-3 p-xl-5">

            <!-- Body: Header -->
            <div class="container-xxl">
                <!-- header rightbar icon -->
                <div class="row align-items-center">
                    <div class="col">
                        <a href="/" class="d-flex align-item-center">
                            <i class="icofont-stopwatch fs-3"></i>
                            <h5 class="mb-0 mt-1 mx-2">Timesheethub</h5>
                        </a>
                    </div>
                    <div class="col-auto">
                        <div class="d-flex align-item-center">
                            
                           
                        </div>
                    </div>
                </div>
            </div>
<div class="body d-flex py-3">
    <div id="timetracker-layout" class="theme-mist">

        <!-- main body area -->
        <div class="main p-2 py-3 p-xl-5">

            <!-- Body: Header -->
            <div class="container-xxl">
                <!-- header rightbar icon -->
                <div class="row align-items-center">
                    
                </div>
            </div>
            
            <!-- Body: Body -->
            <div class="body d-flex p-0 p-md-2 p-xl-5">
                <div class="container-xxl">
                    <div class="row g-0 border border-secondary rounded-3 mt-2 mt-md-0">
                        <div class="col-lg-6 justify-content-center align-items-center bg-secondary py-2 py-md-0" style="padding: 6% !important;
">
                            <div class="d-flex flex-column p-2 login-text">
                                <h1>Account Login</h1>
                                <span>Welcome back! Log In with your Email</span>
                                <div class="tab-content mt-4 mb-3">
                                    <div class="tab-pane fade show active" id="Email">
                                        <div class="card">
                                            <div class="card-body p-4">
                                                <div class="error_msg"><?= $error; ?></div>
                                                <form method="post" action="" class="fisrt_form"  onsubmit="return false;">
                                                    <div class="card-body p-4 company-domain-field">    
                                                        <div class="mb-3 main-domain">
                                                            <label for="company_domain" class="form-label">Company Name</label>
                                                            <input type="text" name="company_domain" class="form-control" id="company_domain" aria-describedby="domainHelp" value="" required="" onkeydown="return /[a-z0-9\d\-_]/i.test(event.key);" onkeyup="this.value = this.value.toLowerCase();" readonly="" onfocus="this.removeAttribute('readonly');">
                                                            <span class="comp_error" style="color:red; display:none;">Company name is required.</span>
                                                        </div>
                                                        <div class="next-btn next-prev-btn">
                                                            <a href="javascript:void(0)" class="next-btn-link" title="Next">Next <i class="icofont-arrow-right"></i> </a>
                                                        </div>
                                                    </div>
                                                </form>
                                                <form method="post" action="" class="second_form" onsubmit="return false;">
                                                <input type="hidden" name="company_domain" id="hidden-company" value="">
                                                <div class="card-body p-4 email-password-field" style="display: none;">
                                                    <div class="back-btn next-prev-btn">
                                                        <a href="javascript:void(0)" class="back-btn-link"><i class="icofont-arrow-left"></i> Back</a>
                                                    </div>
                                                    <span class="login_error" style="color:red; display:none;"></span>
                                                    <div class="mb-3">
                                                        <label for="exampleInputEmail1" class="form-label">Email address</label>
                                                        <input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" value="<?= $_POST['email']; ?>" required>
                                                
                                                    </div>
                                                    <div class="mb-3">
                                                        <label for="exampleInputPassword1" class="form-label">Password</label>
                                                        <div class="password-icon">
                                                            <input type="password" name="password" class="form-control" id="exampleInputPassword1" required>
                                                            <i class="icofont-eye-alt text-warning pwd-toggle icofont-eye"></i>
                                                        </div>
                                                    </div>
                                                    <div class="mb-3 form-check">
                                                        <input type="checkbox" class="form-check-input" id="exampleCheck1">
                                                        <label class="form-check-label" for="exampleCheck1">Remember me</label>
                                                    </div>

                                                    <button type="button"  value="login" name="login" class="btn btn-primary call_login">Log In</button>
                                                    <button type="submit" value="login" name="login" class="btn btn-primary call_submit" style="display: none;"></button>
                                                </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <a href="reset_password.php" title="Forgot password" class="text-primary text-decoration-underline">Forgot password?</a>
                                <a href="register.php" title="Register now" class="text-primary text-decoration-underline">Register now</a>
                            </div>
                        </div>

                        <div class="col-lg-6 d-none d-lg-flex justify-content-center align-items-center">
                            <div class="qr-block text-center">
                               <div class="col">
                                    <a href="<?= $site_url; ?>" class="timetracker-logo align-item-center">
                                        <i class="icofont-stopwatch fs-3" style="font-size: 70px !important;line-height: 70px !important;"></i>
                                        <h5 class="logo-text">Timesheethub</h5>
                                    </a>
                                </div>
                                
                            </div>
                        </div>
                    </div> <!-- End Row -->
                    
                </div>
            </div>
        </div>

    </div>
</div>
<?php
if(isset($_POST['login']))  
{  
    $user_email=$_POST['email'];  
    $user_pass=$_POST['password'];  
  
    $check_user="select * from db_users WHERE email='$user_email'AND password='$user_pass'";  
  
    $run=mysqli_query($conn,$check_user);  
  
    if(mysqli_num_rows($run))  
    {  
        echo "<script>window.open('".$site_url."dist/projects.php','_self')</script>";  
  
        $_SESSION['email']=$user_email;
  
    }  
    else  
    {  
      echo "<script>alert('".$error."')</script>";  
    }  
}  
?>  
</div>

    </div>
    <div class="spinner-border float-right" role="status" style="display: none;">
                <span class="sr-only">Loading...</span>
              </div>

    <!-- Jquery Core Js -->
    <script src="<?= $site_url; ?>/assets/bundles/libscripts.bundle.js"></script>

    <!-- Jquery Page Js -->
    <script src="<?= $site_url; ?>/js/template.js"></script>
    <style type="text/css">
        .spinner-border {
            display: inline-block;
            width: 2rem;
            height: 2rem;
            vertical-align: -.125em;
            border: .25em solid currentColor;
            border-right-color: transparent;
            border-radius: 50%;
            animation: .75s linear infinite spinner-border;
            position: fixed;
            top: 50%;
            left: 50%;
        }
        
        .error_msg {
            color: red;
        }
        .login-text h1, .login-text span {
            color: #fff;
        }
        .login-text a.text-primary.text-decoration-underline {
            color: #fff !important;
        }
        /* === login form css START === */

        .next-btn {
            text-align: right;
        }
        .back-btn {
            margin-bottom: 16px;
        }
        .card-body.p-4.email-password-field.show {
            display: block !important;
        }
        .card-body.p-4.company-domain-field.hide {
            display: none !important;
        }

        .next-prev-btn a{
            color: #555555;
            font-weight: 600;
            font-size: 16px;
            position: relative;
            transition: .5s;
        }
        .next-prev-btn a:before{
            content: '';
            height: 10px;
            width: 10px;
            position: absolute;
            border-top: #555555 solid 2px;
            border-left: #555555 solid 2px;
            display: none;
        }
        /*.next-btn-link {
            padding-right: 16px;
        }*/
        .next-btn-link:before {
            top: 6px;
            right: 0px;
            transform: rotate(135deg);
            transition: .5s;
        }
        /*.back-btn-link{
            padding-left: 16px;
        }*/
        .back-btn-link:before {
            top: 6px;
            left: 0px;
            transform: rotate(-45deg);
        }
        .next-btn-link:hover::before {
            border-top: #cea254 solid 2px;
            border-left: #cea254 solid 2px;
        }
        .password-icon{
            display: flex;
        }
        .form-control[name="password"] {
            border-right: 0px;
            border-radius: 0.25rem 0px 0px 0.25rem;
            padding-right: 0;
        }
        i.pwd-toggle {
            padding: 11px 6px 9px 0px;
            cursor: pointer;
            background: rgb(232, 240, 254);
            margin-left: -5px;
            border: 1px solid #f0f0f0;
            border-left: 0px;
            border-radius: 0px 0.25rem 0.25rem 0px;
        }
        input.form-control:focus + i {
            border: 1px solid black;
            border-left: 0;
        }

        /* === login form css START === */
    </style>
    <script type="text/javascript">
    $(document).on('submit', '.fisrt_form', function(){
        $(".next-btn-link").click();
    });
        $(document).on("click", ".next-btn-link", function(){
            if($("#company_domain").val() == ''){
                $(".comp_error").show();
            } else {
                $(".spinner-border").show();
                $.ajax({
                    type:"post",
                    data:{check_company:$("#company_domain").val()},
                    url:window.location.pathname,
                    success:function(res){
                        if(res != 1){
                            $(".comp_error").html(res).show();
                        } else {
                            $(".comp_error").hide();
                            $("#hidden-company").val($("input#company_domain").val());
                            $(".email-password-field").addClass("show");
                            $(".company-domain-field").addClass("hide");
                        }
                        $(".spinner-border").hide();
                    }
                })
                
                
            }
            
        });
        $(document).on('submit', '.second_form', function(){
        $(".call_login").click();
    });
        $(document).on("click", ".call_login", function(){ 
            let valid = true;
            jQuery('div#Email form [required]:not([readonly])').each(function() {
                if (jQuery(this).is(':invalid') || !jQuery(this).val()) valid = false;
            })
           
            if (!valid){
                 jQuery('.call_submit').click();
            } else {
            $(".spinner-border").show();
                $.ajax({
                    type:"post",
                    data:{login:1,company_domain:$("#company_domain").val(),email:$("input[name='email']").val(),password:$("input[name='password']").val()},
                    url:window.location.pathname,
                    success:function(res){
                        if(res.indexOf("/") > -1){
                            $(".login_error").hide();
                            window.location.href = res;
                        } else {
                            $(".login_error").html(res).show();
                        }
                        $(".spinner-border").hide();
                    }
                });
            }
        });
        
        $(".back-btn-link").click(function(){
            $(".email-password-field").removeClass("show");
            $(".company-domain-field").removeClass("hide");
        }); 
        jQuery(document).on("click", ".pwd-toggle", function(){
            var cur_type = jQuery(this).prev('input').attr('type');
            if(cur_type == 'password'){
                jQuery(this).prev('input').attr('type','text');
                jQuery(this).removeClass('icofont-eye');
                jQuery(this).addClass('icofont-eye-blocked');
            } else {
                jQuery(this).prev('input').attr('type','password');
                jQuery(this).removeClass('icofont-eye-blocked');
                jQuery(this).addClass('icofont-eye');
                
            }
          });

    </script>
</body>
</html>