<?php
include "config.php";
require_once "sms/SmsHelper.php";

error_reporting(0);
session_start();

if (isset($_SESSION['log']) && $_SESSION['log'] !== '') {
    header('Location:home.php');
    exit();
}

$loginError = '';
$loginDebug = '';
$smsConfig = include "sms/sms_config.php";

if (isset($_POST['sub'])) {
    $user = isset($_POST['user']) ? trim($_POST['user']) : '';
    $pass = isset($_POST['password']) ? trim($_POST['password']) : '';
    $userEscaped = mysqli_real_escape_string($connect, $user);
    $passEscaped = mysqli_real_escape_string($connect, $pass);
    $employee = false;
    $query = "SELECT id, employeecode, employeename, username, mobile FROM employeedetails WHERE username='$userEscaped' AND password='$passEscaped' AND status!='deleted' AND statuslive='1' ORDER BY id DESC LIMIT 1";
    $result = mysqli_query($connect, $query);

    if ($result) {
        $employee = mysqli_fetch_assoc($result);
    }

    if (!$employee) {
        $loginError = 'Invalid username or password';
    } else {
        $otpMobile = '';
        if (isset($employee['mobile']) && trim($employee['mobile']) !== '') {
            $otpMobile = trim($employee['mobile']);
        } elseif (!empty($smsConfig['fixed_admin_number'])) {
            $otpMobile = trim($smsConfig['fixed_admin_number']);
        }

        if ($otpMobile === '') {
            $loginError = 'OTP mobile number is not configured for this employee.';
        } else {
            $otpCode = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
            $smsHelper = new SmsHelper($smsConfig);
            $smsResponse = $smsHelper->sendOtp($otpMobile, $otpCode, $employee['employeename'], $employee['employeecode']);

            if ($smsResponse['success']) {
                $_SESSION['pending_login'] = array(
                    'employee_id' => $employee['id'],
                    'employee_code' => $employee['employeecode'],
                    'employee_name' => $employee['employeename'],
                    'username' => $employee['username'],
                    'otp_mobile' => $otpMobile,
                );
                $_SESSION['login_otp_employee_code'] = $employee['employeecode'];
                $_SESSION['login_otp_value'] = $otpCode;
                $_SESSION['login_otp_expires_at'] = time() + 1000;
                $_SESSION['login_otp_resend_after'] = time() + 30;
                $_SESSION['login_otp_attempts'] = 0;
     //$loginError = json_encode($smsResponse);
               header('Location:login_otp.php');
               exit();
            } else {
                $loginError = 'OTP could not be sent. Please check SMS API settings.';
                if (isset($smsResponse['response']) && $smsResponse['response'] !== null && $smsResponse['response'] !== false) {
                    $loginDebug = 'SMS API response: ' . $smsResponse['response'];
                } elseif (isset($smsResponse['message'])) {
                    $loginDebug = 'SMS error: ' . $smsResponse['message'];
                }
            }
        }
    }
}
?>
<html>
    <head>
    <link rel="stylesheet" href="fontawesome-free-5.15.1-web/css/all.css">
  <link rel="stylesheet" href="bootstrap/min.css">
  <script src="javascript/min.js" type="text/javascript"></script>
  <script src="bootstrap/jquery.min.js"></script>
  <script src="bootstrap/popper.min.js"></script>
  <script src="bootstrap/bootstrap.js"></script>
        <style>
            body
            {
                background-image:url("image/mountain2.jpg");
                 background-position: center;
            }
            .logo i
            {
                border-radius:20px;
                font-size:70px;
                color:rgba(161, 143, 93);
                
            }
            .logo
            {
                margin-left:230px;
                padding-top:20px;
            }
            .full-login 
            {
                background-color:rgba(228, 237, 230,0.7);
                width:500px;
                height:400px;
                margin:auto;
                margin-top:100px;
                border-radius:20px;
                font-family:timesnewroman;
            }
            h1
            {
                text-align:center;
                font-family:timesnewroman;
                padding-top:20px;
              
            }
             .inputtext,.inputtextdis
             {
                 width:300px;
                 background-color:rgba(228, 237, 230,0.4);
                 border:1px solid black;

             }
             .inputtext
             {
                 margin-bottom:40px;
             }
             .textfield 
             {
                 margin-left:100px;
                 margin-top:50px;
             }
             .chkbox
             {
                 margin-left:100px;
             }
             .forgot
             {
                 margin-left:120px;
             }
             .buttonsub
             {
                 margin-left:220px;
                 margin-top:30px;
             }
        </style>
    </head>
    <body>
        <div class="full-login">
        <!-- <div class="logo">
        <i class="fas fa-user-tie"></i>
        </div> -->
        <h1>LOGIN</h1>
        <div class="textfield">
            <form method="post" action="index.php">
            <?php if ($loginError != '') { ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($loginError); ?></div>
            <?php } ?>
            <?php if ($loginDebug != '') { ?>
            <div class="alert alert-warning" style="font-size:12px;word-break:break-word;"><?php echo htmlspecialchars($loginDebug); ?></div>
            <?php } ?>
            <input type="text" name="user" autocomplete="off" class="form-control inputtext" placeholder="Username">
            <input type="password" name="password" class="form-control inputtextdis" id="pass" placeholder="Password">
            <input type="text" class="form-control inputtextdis" id="passtext" placeholder="passwordd">
        </div>
        <br>
        <div><span class="chkbox"><input type="checkbox" id="showpass"> Show Password</span><span class="forgot"><a href="#"data-toggle="modal" data-target="#myModal" >Forgot Password</a></span></div>
    <input type="submit" name="sub" class="btn btn-warning buttonsub">  
            </form> 
    </div>
    <!--  -->
    <div class="modal fade" id="myModal">
    <div class="modal-dialog">
      <div class="modal-content">
      
        <!-- Modal Header -->
        
        
        <!-- Modal body -->
        <div class="modal-body">
            <form action="updatepassword.php" method="post">
        <input type="text" class="form-control " name="userpass" placeholder="Username"><br>
            <input type="password" class="form-control" id="pass" name="password" placeholder="Change-Password">
        </div>
        
        <!-- Modal footer -->
        <div class="modal-footer">
        <button type="submit" class="btn btn-info">OK</button>
          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </form>
        </div>
        
      </div>
    </div>
  </div>
    <!--  -->
    <script>
        $(document).ready(function(){
            $("#passtext").hide();
            //alert('hai');
        $("#showpass").click(function(){
        if($(this).is(":checked")){
            $("#passtext").show();
            $("#pass").hide();
        }
        else
        {
            $("#passtext").hide();
            $("#pass").show();
        }
        });
        });
    </script>
    <script>
        $(document).ready(function(){
           
            //alert('hai');
        $("#pass").keyup(function(){
            var a =$(this).val();
            //alert(a);
        $("#passtext").val(a);
        });
        });
    </script>
    <script>
        $(document).ready(function(){
            
            //alert('hai');
            $("#passtext").keyup(function(){
            var a =$(this).val();
           // alert(a);
        $("#pass").val(a);
        });
        });
    </script>
    </body>
</html>
