<?php
// 1. टाइमज़ोन सेट करें और सेशन शुरू करें
date_default_timezone_set('Asia/Kolkata');
$current_time = date('M d, Y, g:i:s A', time());

include('includes/config.php');

$success = false;
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$error_script = "";

// 2. स्टेप 1: OTP जनरेट करना और ईमेल भेजना
if(isset($_POST['fsecret']) && $_POST['fsecret'] == "ahkwebsolutions_reset"){
  $username = mysqli_real_escape_string($conn, $_POST['username']);
  $_SESSION['tmpuser'] = $username;
  
  $res = mysqli_query($conn, "SELECT * FROM `usertable` WHERE phone='$username' or emailid='$username' or userid='$username' ");
  
  if(mysqli_num_rows($res) == 1){
    $userdata = mysqli_fetch_assoc($res);
    
    // 5 अंकों का सुरक्षित रैंडम OTP जनरेट करें
    $otp = rand(10000, 99999);
    $ires = mysqli_query($conn, "UPDATE `usertable` SET `otp`='$otp' WHERE phone='$username' or emailid='$username' or userid='$username' ");
    
    if($ires){
      // PHPMailer और ईमेल कॉन्फ़िगरेशन
      $mob_no = $userdata['phone'];
      $fromName = $ahkweb['name'];
      $subject_home = "Password Reset OTP";
      
      include('gmail-otp/ak.php');
      $msg = "Hello Dear , " . $userdata['name'].  " <br> Your Password Reset OTP is:  "  . $otp. " \n\n <br>Mobile Number is  " .  $mob_no.  "\n\n<br>Username : ".$username .  "<br>";
      
      // PHPMailer क्लास का उपयोग (सुनिश्चित करें कि क्लास पाथ्स सही लोड हो रहे हों)
      $mail = new PHPMailer(); 
      $mail->IsSMTP(); 
      $mail->SMTPAuth = true; 
      $mail->SMTPSecure = 'tls'; 
      $mail->Host = "localhost";
      $mail->Port = 587; 
      $mail->IsHTML(true);
      $mail->CharSet = 'UTF-8';
      $mail->Username = $emailfrom;
      $mail->Password = $smtp_password;
      $mail->SetFrom($emailfrom, $fromName);
      $mail->Subject = $subject_home;
      $mail->Body = $msg;
      $mail->addAddress($userdata['emailid']);
      $mail->SMTPOptions = array('ssl' => array(
          'verify_peer' => false,
          'verify_peer_name' => false,
          'allow_self_signed' => false
      ));
      
      if(!$mail->Send()){
          $error_script = "
              Swal.fire({
                  icon: 'error',
                  title: 'Mail Error',
                  text: 'Mail Not Sent. Error: " . mysqli_real_escape_string($conn, $mail->ErrorInfo) . "'
              });
          ";
      } else {
          $success = true;
          $error_script = "
              Swal.fire({
                  icon: 'success',
                  title: 'Success!',
                  text: 'OTP Sent successfully to your registered Email Id!',
                  timer: 2000,
                  showConfirmButton: false
              });
          ";
      }
    }
  } else {
    $error_script = "
        Swal.fire({
            icon: 'error',
            title: 'Oops!',
            text: 'Entered Username or email does not exist!'
        }).then(() => {
            window.location.href = 'forgot-password.php';
        });
    ";
  }
}

// 3. स्टेप 2: OTP वेरीफाई करना और पासवर्ड अपडेट करना
if(isset($_POST['preset']) && $_POST['preset'] == "ahkweb_preset"){
  $v_username = mysqli_real_escape_string($conn, $_POST['username']);
  $v_otp = mysqli_real_escape_string($conn, $_POST['v_otp']);
  $password = mysqli_real_escape_string($conn, $_POST['password']);
  $cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']);
  
  $check = mysqli_query($conn, "SELECT * FROM usertable WHERE userid='$v_username' or emailid='$v_username' or phone='$v_username' ");
  if(mysqli_num_rows($check) == 1){
    $data = mysqli_fetch_assoc($check);
    if($v_otp == $data['otp'] && !empty($data['otp'])){
      if($password == $cpassword){
        $vpassword = password_hash($cpassword, PASSWORD_DEFAULT);
        $usql = mysqli_query($conn, "UPDATE usertable SET password='$vpassword', otp='' WHERE userid='$v_username' or emailid='$v_username' or phone='$v_username' ");
        if($usql){
          $error_script = "
              Swal.fire({
                  icon: 'success',
                  title: 'Success!',
                  text: 'Password Reset Successfully! You can Login Now.',
                  timer: 1500,
                  showConfirmButton: false
              }).then(() => {
                  window.location.href = 'login.php';
              });
          ";
        }
      } else {
        $error_script = "
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Confirm Password Does Not Match!'
            }).then(() => {
                window.location.href = 'forgot-password.php';
            });
        ";
      }
    } else {
      $error_script = "
          Swal.fire({
              icon: 'error',
              title: 'Oops!',
              text: 'Incorrect or Expired OTP!'
          }).then(() => {
              window.location.href = 'forgot-password.php';
          });
      ";
    }
  } else {
    $error_script = "
        Swal.fire({
            icon: 'error',
            title: 'Oops!',
            text: 'You are tampering with something on this page. Sorry, we cannot proceed!'
        }).then(() => {
            window.location.href = 'index.php';
        });
    ";
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify OTP & Reset Password</title>
    <!-- Google Fonts & FontAwesome Icons -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- SweetAlert2 CSS -->
	<script disable-devtool-auto src="https://cdn.jsdelivr.net/npm/disable-devtool@latest"></script>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Poppins', sans-serif;
        }

        body {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .login-container {
            background: rgba(255, 255, 255, 0.08);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.15);
            padding: 40px;
            width: 100%;
            max-width: 450px;
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
            color: #fff;
        }

        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .login-header .logo-icon {
            font-size: 3rem;
            color: #00f2fe;
            margin-bottom: 15px;
            text-shadow: 0 0 15px rgba(0, 242, 254, 0.5);
        }

        .login-header h2 {
            font-size: 1.8rem;
            font-weight: 600;
            letter-spacing: 0.5px;
            margin-bottom: 10px;
        }

        .login-header p {
            font-size: 0.85rem;
            color: #cbd5e1;
            line-height: 1.5;
        }

        .form-group {
            position: relative;
            margin-bottom: 20px;
        }

        .form-group i.input-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #cbd5e1;
            font-size: 1.1rem;
            transition: 0.3s;
        }

        .form-control {
            width: 100%;
            padding: 14px 45px 14px 45px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 10px;
            outline: none;
            color: #fff;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            background: rgba(255, 255, 255, 0.15);
            border-color: #00f2fe;
            box-shadow: 0 0 10px rgba(0, 242, 254, 0.2);
        }

        .form-control::placeholder {
            color: #94a3b8;
        }

        .form-control:focus ~ i.input-icon {
            color: #00f2fe;
        }

        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #cbd5e1;
            transition: 0.3s;
        }

        .password-toggle:hover {
            color: #00f2fe;
        }

        .login-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #00f2fe 0%, #4facfe 100%);
            border: none;
            border-radius: 10px;
            color: #fff;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
            margin-top: 10px;
        }

        .login-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(0, 242, 254, 0.6);
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }

        .form-footer {
            text-align: center;
            margin-top: 25px;
            font-size: 0.85rem;
            color: #cbd5e1;
        }

        .form-footer a {
            color: #00f2fe;
            text-decoration: none;
            font-weight: 500;
        }

        .form-footer a:hover {
            text-decoration: underline;
        }
        
        .waiting-box {
            text-align: center;
            padding: 20px 0;
        }
        
        .spinner {
            font-size: 2.5rem;
            color: #00f2fe;
            animation: spin 1s linear infinite;
            margin-bottom: 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>

    <div class="login-container">
        <?php if($success == true): ?>
            <!-- स्टेप 2: नया पासवर्ड और OTP डालने का फॉर्म -->
            <div class="login-header">
                <div class="logo-icon"><i class="fa-solid fa-shield-keyhole"></i><i class="fa-solid fa-lock-open"></i></div>
                <h2>Reset Password</h2>
                <p>You are only one step away from your new password. Recover your account now.</p>
            </div>

            <form action="" method="POST" autocomplete="off">
                <input type="hidden" name="preset" value="ahkweb_preset">
                <input type="hidden" name="username" value="<?php echo htmlspecialchars($_SESSION['tmpuser'] ?? ''); ?>">

                <!-- OTP Input -->
                <div class="form-group">
                    <i class="fa-solid fa-hashtag input-icon"></i>
                    <input type="text" name="v_otp" class="form-control" placeholder="Enter 5-Digit OTP" required>
                </div>

                <!-- New Password Input -->
                <div class="form-group">
                    <i class="fa-solid fa-lock input-icon"></i>
                    <input type="password" id="password" name="password" class="form-control" placeholder="New Password" required>
                    <i class="fa-solid fa-eye password-toggle" id="togglePassword"></i>
                </div>

                <!-- Confirm Password Input -->
                <div class="form-group">
                    <i class="fa-solid fa-check-double input-icon"></i>
                    <input type="password" id="cpassword" name="cpassword" class="form-control" placeholder="Confirm New Password" required>
                    <i class="fa-solid fa-eye password-toggle" id="toggleCPassword"></i>
                </div>

                <button type="submit" class="login-btn">Change Password</button>
            </form>

            <div class="form-footer">
                <p><a href="index">Back to Login</a></p>
            </div>

        <?php else: ?>
            <!-- स्टेप 1: प्रोसेसिंग / एरर होने पर लोडिंग स्टेट या फॉलबैक व्यू -->
            <div class="login-header">
                <div class="logo-icon"><i class="fa-solid fa-envelope-circle-check"></i></div>
                <h2>Processing Request</h2>
                <p>Verifying server protocols and establishing a secure session...</p>
            </div>
            
            <div class="waiting-box">
                <div class="spinner"><i class="fa-solid fa-circle-notch"></i></div>
                <p style="font-size:0.9rem; color:#cbd5e1;">Please wait while we process your execution layout.</p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Scripts (jQuery & SweetAlert2) -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        $(document).ready(function() {
            // PHP बैकएंड संदेशों को SweetAlert पर रेंडर करना
            <?php echo $error_script; ?>
            
            // नया पासवर्ड शो/हाइड स्क्रिप्ट
            if($('#togglePassword').length) {
                $('#togglePassword').on('click', function () {
                    const passwordField = $('#password');
                    const type = passwordField.attr('type') === 'password' ? 'text' : 'password';
                    passwordField.attr('type', type);
                    $(this).toggleClass('fa-eye-slash');
                });
            }

            // कन्फर्म पासवर्ड शो/हाइड स्क्रिप्ट
            if($('#toggleCPassword').length) {
                $('#toggleCPassword').on('click', function () {
                    const cpasswordField = $('#cpassword');
                    const type = cpasswordField.attr('type') === 'password' ? 'text' : 'password';
                    cpasswordField.attr('type', type);
                    $(this).toggleClass('fa-eye-slash');
                });
            }
        });
    </script>
</body>
</html>