<?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 = $_POST['email'] ?? '';

if (empty($email)) {
    echo json_encode(["success" => false, "message" => "Email is required"]);
    exit;
}

// Generate 6-digit OTP as string
$otp = strval(rand(100000, 999999));

// Check if user exists
$stmtCheck = $conn->prepare("SELECT * FROM tblcred WHERE email = ?");
if (!$stmtCheck) {
    echo json_encode(["success" => false, "message" => "Prepare failed: " . $conn->error]);
    exit;
}
$stmtCheck->bind_param("s", $email);
$stmtCheck->execute();
$result = $stmtCheck->get_result();

if ($result->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "Email not found"]);
    exit;
}

// Update OTP in DB (otp_code is varchar)
$stmtUpdate = $conn->prepare("UPDATE tblcred SET otp_code = ? WHERE email = ?");
if (!$stmtUpdate) {
    echo json_encode(["success" => false, "message" => "Prepare failed: " . $conn->error]);
    exit;
}
$stmtUpdate->bind_param("ss", $otp, $email);

//echo "OTP: $otp\nEmail: $email\n";

if ($stmtUpdate->execute()) {
    // Send email via PHPMailer
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'mail.cloudsoftonline.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'noreply@cloudsoftonline.com';
        $mail->Password   = 'Rforce#456#8925';
        /*$mail->Username   = 'rzaman@cloudsoftonline.com';
        $mail->Password   = 'Rforce@123';*/
        $mail->SMTPSecure = 'tls';
        $mail->Port       = 587;

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

        $mail->isHTML(true);
        $mail->Subject = 'Your OTP Code - Wavoo Laundry Service';
        $mail->Body    = "<h3>Your OTP code is: {$otp}</h3><p>Please do not share this code with anyone.</p>";

        $mail->send();
        echo json_encode(["success" => true, "message" => "OTP sent to your email"]);
    } catch (Exception $e) {
        echo json_encode(["success" => false, "message" => "Mailer Error: {$mail->ErrorInfo}"]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Database update failed: " . $stmtUpdate->error]);
}

$stmtCheck->close();
$stmtUpdate->close();
$conn->close();
