<?php 
session_start();
error_reporting(0);
include('includes/dbconnection.php');
// Registration is now handled via AJAX with OTP verification
if(isset($_POST['login']))
  {
    $emailcon=$_POST['emailcont'];
    $password=md5($_POST['password']);
    $query=mysqli_query($con,"select ID from tbluser where  (Email='$emailcon' || MobileNumber='$emailcon') && Password='$password' ");
    $ret=mysqli_fetch_array($query);
    if($ret>0){
      $_SESSION['msmsuid']=$ret['ID'];
     header('location:index.php');
    }
    else{
    $msg="Invalid Details.";
    }
  }
 ?>
<!DOCTYPE html>
<html lang="zxx">
<head>
    <title>Phone Bazaar Management System | Login Page</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   
    <!-- Vendor CSS Files -->
    <link rel="stylesheet" href="assets/css/vendor/jquery-ui.min.css">
    <link rel="stylesheet" href="assets/css/vendor/fontawesome.css">
    <link rel="stylesheet" href="assets/css/vendor/plaza-icon.css">
    <link rel="stylesheet" href="assets/css/vendor/bootstrap.min.css">

    <!-- Plugin CSS Files -->
    <link rel="stylesheet" href="assets/css/plugin/swiper.min.css">
    <link rel="stylesheet" href="assets/css/plugin/material-scrolltop.css">
    <link rel="stylesheet" href="assets/css/plugin/price_range_style.css">
    <link rel="stylesheet" href="assets/css/plugin/in-number.css">
    <link rel="stylesheet" href="assets/css/plugin/venobox.min.css">

    <!-- Main Style CSS File -->
    <link rel="stylesheet" href="assets/css/main.css">
    <!-- Modern Auth Styles -->
    <link rel="stylesheet" href="assets/css/auth-modern.css">
    <link rel="stylesheet" href="assets/css/responsive-custom.css">
    <script type="text/javascript">
function checkpass()
{
if(document.signup.password.value!=document.signup.repeatpassword.value)
{
alert('Password and Repeat Password field does not match');
document.signup.repeatpassword.focus();
return false;
}
return true;
} 
</script>
</head>

<body class="auth-page">

<?php include_once('includes/header.php');?>
    
   <!-- ::::::  Start  Breadcrumb Section  ::::::  -->
    <div class="page-breadcrumb">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <ul class="page-breadcrumb__menu">
                        <li class="page-breadcrumb__nav"><a href="index.php">Home</a></li>
                        <li class="page-breadcrumb__nav active">Login Page</li>
                    </ul>
                </div>
            </div>
        </div>
    </div> <!-- ::::::  End  Breadcrumb Section  ::::::  -->

    <!-- ::::::  Start  Main Container Section  ::::::  -->
    <main id="main-container" class="main-container">
        <div class="container">
            <div class="row">
               <div class="col-12">
                <!-- login area start -->
                <div class="login-register-area auth-modern">
                    <div class="container">
                        <div class="row">
                            <div class="col-lg-7 col-md-12 ml-auto mr-auto">
                                <div class="login-register-wrapper">
                                    <div class="login-register-tab-list nav">
                                        <a class="active" data-toggle="tab" href="#lg1">
                                            <h4>login</h4>
                                        </a>
                                        <a data-toggle="tab" href="#lg2">
                                            <h4>register</h4>
                                        </a>
                                    </div>
                                    <div class="tab-content">
                                        <div id="lg1" class="tab-pane active">
                                            <div class="login-form-container">
                                                <div class="login-register-form">
                                                    <form action="#" method="post">
                                                        <p class="form-message" style="font-size:16px; color:red" align="center"> <?php if($msg){
    echo $msg;
  }  ?> </p>
                                                        <div class="form-box__single-group input-with-icon">
                                                            <i class="fas fa-at input-icon"></i>
                                                            <input type="text" name="emailcont" required="true" placeholder="Registered Email or Contact Number">
                                                        </div>
                                                        <div class="form-box__single-group input-with-icon">
                                                            <i class="fas fa-lock input-icon"></i>
                                                            <input id="loginPassword" type="password" name="password" placeholder="Password" required="true">
                                                            <button type="button" class="toggle-password" data-target="#loginPassword"><i class="fas fa-eye"></i></button>
                                                        </div>
                                                        <div class="d-flex justify-content-between flex-wrap m-tb-20">
                                                           
                                                            <a class="link--gray" style="color: blue;" href="forgot-password.php">Forgot Password?</a>
                                                        </div>
                                                        <button class="btn btn--box btn--small btn--blue btn--uppercase btn--weight" type="submit" name="login">Login</button>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                        <div id="lg2" class="tab-pane">
                                            <div class="login-form-container">
                                                <div class="login-register-form">
                                                    <form id="registrationForm" name="signup" action="javascript:void(0);" onsubmit="sendOTP(event); return false;">
                                                        <p id="regMessage" class="form-message" style="font-size:16px; color:red" align="center"></p>
                                                        <div class="form-box__single-group input-with-icon">
                                                            <i class="fas fa-user input-icon"></i>
                                                            <input type="text" placeholder="First Name" name="firstname" id="regFirstname" required="true">
                                                        </div>
                                                        <div class="form-box__single-group input-with-icon">
                                                            <i class="fas fa-user input-icon"></i>
                                                            <input type="text" name="lastname" id="regLastname" placeholder="Last Name" required="true">
                                                        </div>
                                                        <div class="form-box__single-group input-with-icon">
                                                            <i class="fas fa-phone input-icon"></i>
                                                            <input type="text" name="mobilenumber" id="regMobile" maxlength="10" pattern="[0-9]{10}" placeholder="Mobile Number" required="true">
                                                        </div>
                                                        <div class="form-box__single-group input-with-icon">
                                                            <i class="fas fa-envelope input-icon"></i>
                                                            <input type="email" name="email" id="regEmail" placeholder="Email address" required="true">
                                                        </div>
                                                        <div class="form-box__single-group input-with-icon m-b-20">
                                                            <i class="fas fa-lock input-icon"></i>
                                                            <input id="regPassword" type="password" name="password" placeholder="Password" required="true">
                                                            <button type="button" class="toggle-password" data-target="#regPassword"><i class="fas fa-eye"></i></button>
                                                        </div>
                                                        <div class="form-box__single-group input-with-icon m-b-20">
                                                            <i class="fas fa-lock input-icon"></i>
                                                            <input id="regRepeatPassword" type="password" name="repeatpassword" placeholder="Repeat password" required="true">
                                                            <button type="button" class="toggle-password" data-target="#regRepeatPassword"><i class="fas fa-eye"></i></button>
                                                        </div>
                                                        <button class="btn btn--box btn--small btn--blue btn--uppercase btn--weight" type="button" id="sendOtpBtn">Send OTP & Register</button>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- login area end -->
               </div>
            </div>
        </div>
    </main> <!-- ::::::  End  Main Container Section  ::::::  -->

    <!-- OTP Verification Modal -->
    <div class="modal fade" id="otpModal" tabindex="-1" role="dialog" aria-labelledby="otpModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content" style="border-radius: 15px; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.2);">
                <div class="modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px 15px 0 0; border: none;">
                    <h5 class="modal-title" id="otpModalLabel" style="color: white; font-weight: 600;">
                        <i class="fas fa-shield-alt mr-2"></i>OTP Verification
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color: white; opacity: 1;">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" style="padding: 30px;">
                    <div class="text-center mb-4">
                        <div style="width: 80px; height: 80px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 50%; margin: 0 auto 20px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-mobile-alt" style="font-size: 35px; color: white;"></i>
                        </div>
                        <p style="color: #666; margin-bottom: 5px;">We have sent a verification code to</p>
                        <p id="otpMobileDisplay" style="font-weight: 600; color: #333; font-size: 18px;"></p>
                    </div>
                    <form id="otpForm" onsubmit="return verifyOTP(event);">
                        <div class="form-group">
                            <label style="font-weight: 500; color: #333;">Enter 6-digit OTP</label>
                            <input type="text" id="otpInput" class="form-control" maxlength="6" pattern="[0-9]{6}" 
                                   style="text-align: center; font-size: 24px; letter-spacing: 10px; font-weight: 600; padding: 15px; border: 2px solid #e0e0e0; border-radius: 10px;" 
                                   placeholder="------" required>
                        </div>
                        <p id="otpMessage" class="text-center" style="font-size: 14px; min-height: 20px;"></p>
                        <button type="submit" id="verifyOtpBtn" class="btn btn-block" 
                                style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px; font-weight: 600; border-radius: 10px; border: none;">
                            Verify & Complete Registration
                        </button>
                    </form>
                    <div class="text-center mt-3">
                        <p style="color: #999; font-size: 13px;">Didn't receive the code? 
                            <a href="#" id="resendOtp" onclick="resendOTP(); return false;" style="color: #667eea; font-weight: 500;">Resend OTP</a>
                        </p>
                        <p id="timerDisplay" style="color: #667eea; font-weight: 500; font-size: 14px;"></p>
                    </div>
                </div>
            </div>
        </div>
    </div>

   <?php include_once('includes/footer.php');?>

    <!-- material-scrolltop button -->
    <button class="material-scrolltop" type="button"></button>
    

    <!-- ::::::::::::::All Javascripts Files here ::::::::::::::-->

    <!-- Vendor JS Files -->
    <script src="assets/js/vendor/jquery-3.5.1.min.js"></script>
    <script src="assets/js/vendor/modernizr-3.7.1.min.js"></script>
    <script src="assets/js/vendor/jquery-ui.min.js"></script>
    <script src="assets/js/vendor/bootstrap.bundle.js"></script>

    <!-- Plugins JS Files -->
    <script src="assets/js/plugin/swiper.min.js"></script>
    <script src="assets/js/plugin/jquery.countdown.min.js"></script>
    <script src="assets/js/plugin/material-scrolltop.js"></script>
    <script src="assets/js/plugin/price_range_script.js"></script>
    <script src="assets/js/plugin/in-number.js"></script>
    <script src="assets/js/plugin/jquery.elevateZoom-3.0.8.min.js"></script>
    <script src="assets/js/plugin/venobox.min.js"></script>

    <!-- Use the minified version files listed below for better performance and remove the files listed above -->
    <!-- <script src="assets/js/vendor/vendor.min.js"></script>
    <script src="assets/js/plugin/plugins.min.js"></script> -->

    <!-- Main js file that contents all jQuery plugins activation. -->
    <script src="assets/js/main.js"></script>
    <script>
      // Simple password visibility toggle
      document.querySelectorAll('.toggle-password').forEach(function(btn){
        btn.addEventListener('click', function(){
          var target = document.querySelector(this.getAttribute('data-target'));
          if (!target) return;
          var isPassword = target.getAttribute('type') === 'password';
          target.setAttribute('type', isPassword ? 'text' : 'password');
          this.innerHTML = isPassword ? '<i class="fas fa-eye-slash"></i>' : '<i class="fas fa-eye"></i>';
        });
      });

      // OTP Registration System
      var otpTimer;
      var timerSeconds = 60;

      function checkpass() {
        if(document.getElementById('regPassword').value != document.getElementById('regRepeatPassword').value) {
          showRegMessage('Password and Repeat Password do not match', 'red');
          document.getElementById('regRepeatPassword').focus();
          return false;
        }
        return true;
      }

      function showRegMessage(msg, color) {
        var msgEl = document.getElementById('regMessage');
        msgEl.innerHTML = msg;
        msgEl.style.color = color || 'red';
      }

      function showOtpMessage(msg, color) {
        var msgEl = document.getElementById('otpMessage');
        msgEl.innerHTML = msg;
        msgEl.style.color = color || 'red';
      }

      function sendOTP(e) {
        if(e) e.preventDefault();
        
        // Validate all required fields
        var firstname = document.getElementById('regFirstname').value.trim();
        var lastname = document.getElementById('regLastname').value.trim();
        var mobile = document.getElementById('regMobile').value.trim();
        var email = document.getElementById('regEmail').value.trim();
        var password = document.getElementById('regPassword').value;
        var repeatPassword = document.getElementById('regRepeatPassword').value;
        var btn = document.getElementById('sendOtpBtn');

        // Validate required fields
        if(!firstname || !lastname || !mobile || !email || !password || !repeatPassword) {
          showRegMessage('Please fill all required fields', 'red');
          return false;
        }
        
        // Validate passwords match
        if(!checkpass()) return false;
        
        // Validate mobile number
        if(!/^[0-9]{10}$/.test(mobile)) {
          showRegMessage('Please enter a valid 10-digit mobile number', 'red');
          return false;
        }

        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending OTP...';
        showRegMessage('');

        $.ajax({
          url: 'send-otp.php',
          type: 'POST',
          data: { mobilenumber: mobile, email: email },
          dataType: 'json',
          success: function(response) {
            btn.disabled = false;
            btn.innerHTML = 'Send OTP & Register';
            
            if(response.status === 'success') {
              showRegMessage(response.message, 'green');
              document.getElementById('otpMobileDisplay').innerHTML = '+91 ' + mobile.substring(0,2) + '****' + mobile.substring(6);
              document.getElementById('otpInput').value = '';
              showOtpMessage('');
              $('#otpModal').modal('show');
              startTimer();
            } else {
              showRegMessage(response.message, 'red');
            }
          },
          error: function() {
            btn.disabled = false;
            btn.innerHTML = 'Send OTP & Register';
            showRegMessage('Network error. Please try again.', 'red');
          }
        });

        return false;
      }

      function verifyOTP(e) {
        e.preventDefault();
        
        var otp = document.getElementById('otpInput').value;
        var btn = document.getElementById('verifyOtpBtn');
        
        if(!/^[0-9]{6}$/.test(otp)) {
          showOtpMessage('Please enter a valid 6-digit OTP', 'red');
          return false;
        }

        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Verifying...';

        $.ajax({
          url: 'verify-otp.php',
          type: 'POST',
          data: {
            otp: otp,
            firstname: document.getElementById('regFirstname').value,
            lastname: document.getElementById('regLastname').value,
            mobilenumber: document.getElementById('regMobile').value,
            email: document.getElementById('regEmail').value,
            password: document.getElementById('regPassword').value
          },
          dataType: 'json',
          success: function(response) {
            btn.disabled = false;
            btn.innerHTML = 'Verify & Complete Registration';
            
            if(response.status === 'success') {
              showOtpMessage(response.message, 'green');
              clearInterval(otpTimer);
              setTimeout(function() {
                $('#otpModal').modal('hide');
                // Reset form
                document.getElementById('registrationForm').reset();
                // Switch to login tab
                $('a[href="#lg1"]').tab('show');
                alert('Registration successful! Please login with your credentials.');
              }, 1500);
            } else {
              showOtpMessage(response.message, 'red');
            }
          },
          error: function() {
            btn.disabled = false;
            btn.innerHTML = 'Verify & Complete Registration';
            showOtpMessage('Network error. Please try again.', 'red');
          }
        });

        return false;
      }

      function resendOTP() {
        if(timerSeconds > 0) {
          showOtpMessage('Please wait ' + timerSeconds + ' seconds before resending', 'orange');
          return;
        }
        
        var mobile = document.getElementById('regMobile').value;
        var email = document.getElementById('regEmail').value;
        
        document.getElementById('resendOtp').innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
        
        $.ajax({
          url: 'send-otp.php',
          type: 'POST',
          data: { mobilenumber: mobile, email: email },
          dataType: 'json',
          success: function(response) {
            document.getElementById('resendOtp').innerHTML = 'Resend OTP';
            if(response.status === 'success') {
              showOtpMessage('OTP resent successfully!', 'green');
              startTimer();
            } else {
              showOtpMessage(response.message, 'red');
            }
          },
          error: function() {
            document.getElementById('resendOtp').innerHTML = 'Resend OTP';
            showOtpMessage('Failed to resend OTP. Please try again.', 'red');
          }
        });
      }

      function startTimer() {
        timerSeconds = 60;
        clearInterval(otpTimer);
        updateTimerDisplay();
        
        otpTimer = setInterval(function() {
          timerSeconds--;
          updateTimerDisplay();
          if(timerSeconds <= 0) {
            clearInterval(otpTimer);
          }
        }, 1000);
      }

      function updateTimerDisplay() {
        var display = document.getElementById('timerDisplay');
        if(timerSeconds > 0) {
          display.innerHTML = 'Resend available in ' + timerSeconds + 's';
        } else {
          display.innerHTML = '';
        }
      }

      // Clear timer when modal is closed
      $('#otpModal').on('hidden.bs.modal', function() {
        clearInterval(otpTimer);
      });

      // Also bind click event as backup
      $(document).ready(function() {
        $('#sendOtpBtn').on('click', function(e) {
          e.preventDefault();
          e.stopPropagation();
          sendOTP(e);
          return false;
        });

        $('#registrationForm').on('submit', function(e) {
          e.preventDefault();
          e.stopPropagation();
          sendOTP(e);
          return false;
        });
      });
    </script>
</body>

</html>
