<?php
header('Content-Type: application/json');
include '../connection.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

$email = isset($_POST['email']) ? $_POST['email'] : null;

$otprp = rand(100000, 999999);

// Check if email exists
$query = "SELECT * FROM tblcred WHERE LOWER(email) = LOWER('$email')";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) > 0) {
    $update = "UPDATE tblcred SET otp_code='$otprp' WHERE LOWER(email)=LOWER('$email')";
    mysqli_query($conn, $update);

    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = 'mail.cloudsoftonline.com'; // your SMTP host
        $mail->SMTPAuth = true;
        $mail->Username = 'noreply@cloudsoftonline.com';
        $mail->Password = 'Rforce#456#8925';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->setFrom('noreply@cloudsoftonline.com', 'Wavoo Laundry Service');
        $mail->addAddress($email);

        $mail->isHTML(true);
        $mail->Subject = 'Wavoo Password Reset OTP';
        $mail->Body = "Your OTP for password reset is <b>$otprp</b>";

        $mail->send();
        echo json_encode(['success' => true, 'message' => 'OTP sent']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Email sending failed']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Email not registered']);
}
?>
