<?php
require_once __DIR__ . '/../connect.php';

$email = filterRequest("email");
$token = filterRequest("token");

$sql = "SELECT * FROM `email_verifications` WHERE `email` = '$email'";
$stmt = $con->prepare($sql);
$stmt->execute();

$rowCount = $stmt->rowCount();

$admin='support@mobile-app.store';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
$headers .= "From: $admin" . "\r\n";

$subject = "Verify your email address";
$bodyEmail = "
<html>
<head>
<title>Verify your email address</title>
</head>
<body>
<p>Hi [$email],</p>

<p>We recently received a request to verify your email address for your account on SEFER App.</p>

<p>To verify your email address, please write this to app .</p>
$token

<p>If you did not request to verify your email address, please ignore this email.</p>

<p>Thank you,</p>
SEFER Team.
</body>
</html>
";



if ($rowCount > 0) {
    // The email already exists, so update the data
    $sql = "UPDATE `email_verifications` SET `token` = '$token' WHERE `email` = '$email'";
    $stmt = $con->prepare($sql);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        // The update was successful
        jsonSuccess($message = "Email verification data updated successfully");
        mail($email, $subject, $bodyEmail, $headers);
    } else {
        // The update was unsuccessful
        jsonError($message = "Failed to update email verification data");
    }
} else {
    // The email does not exist, so insert the data
    $sql = "INSERT INTO `email_verifications` (`email`, `token`) VALUES ('$email', '$token')";
    $stmt = $con->prepare($sql);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        // The insertion was successful
        jsonSuccess($message = "Email verification data saved successfully");
        mail($email, $subject, $bodyEmail, $headers);
    } else {
        // The insertion was unsuccessful
        jsonError($message = "Failed to save email verification data");
    }
}
?>

