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

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$success = false;

if(isset($_POST['fsecret'])){

$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){

$data = mysqli_fetch_assoc($res);
$otp = rand(10000,99999);

mysqli_query($conn,"UPDATE usertable SET otp='$otp' WHERE phone='$username' OR emailid='$username' OR userid='$username'");

// ================= EMAIL =================
$mail = new PHPMailer(true);

try{

$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;

$mail->Username = 'yourgmail@gmail.com'; // 👈 apna gmail
$mail->Password = 'your_app_password';   // 👈 app password

$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('yourgmail@gmail.com', 'Janata Service');
$mail->addAddress($data['emailid']);

$mail->isHTML(true);
$mail->Subject = 'Password Reset OTP';
$mail->Body = "Hello ".$data['name']."<br><b>Your OTP: $otp</b>";

$mail->send();

}catch(Exception $e){
echo "Mail Error: ".$mail->ErrorInfo;
}

// ================= WHATSAPP =================
$mob_no = $data['phone'];

if(strlen($mob_no)==10){
$mob_no = "91".$mob_no;
}

$wa_msg = "OTP: $otp - JANATA SERVICE";
$wa_msg = urlencode($wa_msg);

$api_key = "TcwZM2Mr1YNtrinUsyHq51ympYZEV9";
$sender = "919142531828";

$url = "https://whatsapp.adds.us.cc/send-message?api_key=$api_key&sender=$sender&number=$mob_no&message=$wa_msg";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_exec($ch);
curl_close($ch);

$success = true;

}else{
echo "<script>alert('User not found');</script>";
}
}

// RESET PASSWORD
if(isset($_POST['preset'])){

$user = $_POST['username'];
$otp = $_POST['otp'];
$pass = $_POST['password'];
$cpass = $_POST['cpassword'];

$q = mysqli_query($conn,"SELECT * FROM usertable WHERE phone='$user' OR emailid='$user' OR userid='$user'");
$d = mysqli_fetch_assoc($q);

if($otp == $d['otp']){

if($pass == $cpass){

$hash = password_hash($pass,PASSWORD_DEFAULT);
mysqli_query($conn,"UPDATE usertable SET password='$hash', otp='' WHERE phone='$user' OR emailid='$user' OR userid='$user'");

echo "<script>alert('Password Changed');window.location='login.php';</script>";

}else{
echo "<script>alert('Password Not Match');</script>";
}

}else{
echo "<script>alert('Wrong OTP');</script>";
}
}
?>