<?php
include('includes/config.php');
session_start(); // Start session

$success = false;

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);
        
        $otp = generateOTP(); // Generate the OTP

        // Update OTP in the database
        $ires = mysqli_query($conn,"UPDATE `usertable` SET `otp`='$otp' WHERE phone='$username' or emailid='$username' or userid='$username' ");
        if($ires){
            // Send OTP via WhatsApp using the Good SMS API
            $phone_number = $userdata['phone']; // Assuming phone number is stored in 'phone'

            if (sendWhatsAppOTP($phone_number, $otp)) {
                $success = true;
            } else {
                echo "Failed to send OTP via WhatsApp!";
            }
            
            if($success == true){
                echo '<script>
                    window.onload = function() {
                        Swal.fire(
                            "Success!",
                            "OTP Sent to Your WhatsApp!",
                            "success"
                        );
                    };
                </script>';
            } else {
                echo "SMS Not Sent";
            }
        }
    } else {
        echo '<script>
            window.onload = function() {
                Swal.fire(
                    "Opps!",
                    "Entered Username or email not exist!",
                    "error"
                ).then(function() {
                    window.location.href = "forgot.php";
                });
            };
        </script>';
    }
}

// Update Password 
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']){
            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){
                    echo '<script>
                        window.onload = function() {
                            Swal.fire(
                                "Success!",
                                "Password Reset Successfully! You can Login Now",
                                "success"
                            ).then(function() {
                                window.location.href = "https://rubydigital.in";
                            });
                        };
                    </script>';
                }
            } else {
                echo '<script>
                    window.onload = function() {
                        Swal.fire(
                            "Error!",
                            "Confirm Password Not Match!",
                            "error"
                        ).then(function() {
                            window.location.href = "forgot.php";
                        });
                    };
                </script>';
            }
        } else {
            echo '<script>
                window.onload = function() {
                    Swal.fire(
                        "Opps!",
                        "Incorrect OTP!",
                        "error"
                    ).then(function() {
                        window.location.href = "forgot.php";
                    });
                };
            </script>';
        }
    } else {
        echo '<script>
            window.onload = function() {
                Swal.fire(
                    "Opps!",
                    "You are Tempering Something in this page. Sorry, we cannot proceed!",
                    "error"
                ).then(function() {
                    window.location.href = "index.php";
                });
            };
        </script>';
    }
}

// Function to generate a 6-digit OTP
function generateOTP() {
    return rand(100000, 999999); // Generate a 6-digit OTP
}

// Function to send OTP via WhatsApp using Good SMS API
function sendWhatsAppOTP($phoneNumber, $otp) {
    $apiKey = "m3P4xDDxhNbub3yFNXKdbrTcXgVlI9"; // API Key for Good SMS
    $sender = '918373937534'; // Device Number (Sender ID)
    $message = "\n\n  👏 𝐃𝐄𝐀𝐑 𝐔𝐒𝐄𝐑\n\n🔐 𝐘𝐨𝐮𝐫 𝐅𝐨𝐫𝐠𝐨𝐭 𝐏𝐚𝐬𝐬𝐰𝐨𝐫𝐝 𝐎𝐓𝐏 𝐈𝐬: $otp 🔐\n\n𝐓𝐡𝐚𝐧𝐤𝐬 𝐅𝐨𝐫 𝐔𝐬𝐢𝐧𝐠 𝐅𝐨𝐫𝐠𝐨𝐭 𝐏𝐚𝐬𝐬𝐰𝐨𝐫𝐝 𝐅𝐚𝐜𝐢𝐥𝐢𝐭𝐲 𝐁𝐲 𝐍𝐚𝐳𝐮𝐤 𝐈𝐧𝐟𝐨𝐭𝐞𝐜𝐡 𝐏𝐯𝐭. 𝐋𝐭𝐝. 𝐒𝐞𝐫𝐯𝐢𝐜𝐞'𝐬";

    // API URL
    $url = "https://api.good-sms.in/send-message";
    $data = [
        'api_key' => $apiKey,
        'sender' => $sender,
        'number' => "91{$phoneNumber}", // Adding country code (India)
        'message' => $message
    ];

    // Initialize cURL and send the request
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // Sending data as JSON
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    $response = curl_exec($ch);

    // Check for cURL errors
    if (curl_errno($ch)) {
        return false; // Return false if request failed
    }
    curl_close($ch); // Close cURL session

    return true; // Return true if OTP was sent successfully
}
?>





<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?php echo $ahkweb['name'] ?> Password Recovery</title>
  <!-- Unicons -->
  <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css" />
  <!-- Google Font -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: "Poppins", sans-serif;
    }
    body {
      background-color: #f8f9fa;
      background-image: url('https://source.unsplash.com/random');
      background-size: cover;
      background-position: center;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .login-box {
      background-color: rgba(255, 255, 255, 0.9);
      border-radius: 12px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      padding: 40px;
      max-width: 400px;
      width: 100%;
      position: relative;
      z-index: 1;
    }
    .login-logo {
      text-align: center;
      margin-bottom: 20px;
    }
    .login-logo a {
      color: #333;
      font-size: 24px;
      text-decoration: none;
    }
    .login-logo a:hover {
      color: #555;
    }
    .form-group {
      position: relative;
      margin-top: 20px;
      width: 100%;
    }
    .form-control {
      width: 100%;
      border: none;
      outline: none;
      padding: 10px 15px;
      color: #333;
      transition: all 0.2s ease;
      border-bottom: 1.5px solid #aaaaaa;
      border-radius: 5px;
      background-color: #fff;
    }
    .form-control:focus {
      border-color: #7d2ae8;
    }
    .btn-primary {
      background: #7d2ae8;
      margin-top: 20px;
      width: 100%;
      padding: 10px 0;
      border-radius: 10px;
      border: none;
      color: #fff;
      cursor: pointer;
      font-size: 16px;
    }
    .btn-primary:active {
      transform: scale(0.98);
    }
    .text-center {
      text-align: center;
      margin-top: 20px;
    }
    .text-center a {
      color: #7d2ae8;
      text-decoration: none;
    }
    .text-center a:hover {
      text-decoration: underline;
    }
  </style>
          <script>
    document.addEventListener('DOMContentLoaded', function() {
        const body = document.querySelector('body');
        
        // Function to generate a random color
        function getRandomColor() {
            const letters = '0123456789ABCDEF';
            let color = '#';
            for (let i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        }

        // Change background color when the page loads
        body.style.background = `linear-gradient(to right, ${getRandomColor()}, ${getRandomColor()})`;
    });
</script>
</head>
<body>
  <div class="login-box">
    <div class="login-logo">
      <a href="index.php"><?php echo $ahkweb['name'] ?> Password Recovery</a>
    </div>
    <div class="text-center"> <!-- Centered text -->
      <p class="login-box-msg">You are only one step away from your new password. Recover your password now.</p>
    </div>
    <form action="recover.php" method="post">
      <input type="hidden" name="preset" value="ahkweb_preset">
      <input type="hidden" name="username" value="<?php echo $_SESSION['tmpuser']; ?>">
      <div class="form-group">
        <div class="form-floating">
          <label for="v_otp">Enter OTP</label>
          <input type="text" class="form-control" id="v_otp" name="v_otp" placeholder="OTP" required>
        </div>
      </div>
      <div class="form-group">
        <div class="form-floating">
          <label for="password">Password</label>
          <input type="password" class="form-control" id="password" name="password" placeholder="Password" required>
        </div>
      </div>
      <div class="form-group">
        <div class="form-floating">
          <label for="cpassword">Confirm Password</label>
          <input type="password" class="form-control" id="cpassword" name="cpassword" placeholder="Confirm Password" required>
        </div>
      </div>
      <div class="form-group">
        <button class="btn btn-primary w-100 py-3" type="submit">Change Password</button>
      </div>
    </form>
  </div>
</body>
</html>
