<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// error_reporting(E_ALL);
// ini_set("display_errors", 1);


header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

session_start();

//Load Composer's autoloader
require __DIR__.'/../../vendor/autoload.php';

require __DIR__.'/classes/CNetcupMailer.php';


require __DIR__.'/classes/Database.php';
require __DIR__.'/classes/lib.php';

$db_connection = new Database();
$conn = $db_connection->dbConnection();
function updatePwtoken($email, $pwtoken)
{
    global $conn;
    $now = new DateTime();
    $sql = "UPDATE dogs SET pwtoken=?, pwt_time=? WHERE email=?";
    $conn->prepare($sql)->execute([$pwtoken, $now->format('Y-m-d H:i:s'), $email]);
}

function sendMail($email, $pwtoken)
{
    global $G_pwtoken_time_expire;
    $expires = new DateTime();
    $expires->add(new DateInterval('PT' . $G_pwtoken_time_expire . 'M'));
    $expiresStr = $expires->format('d.m.Y H:i:s');
    $mail = new CNetcupMailer();
    $mail->CharSet = "UTF-8";
    
    $mail->setFrom('dog@hope-fly.de', 'Administrator hope-fly.de/dog');
    $mail->addAddress($email);     //Add a recipient
    $mail->addReplyTo('No Reply');
    $mail->isHTML(true);
    //Attachments

    //Content
    $mail->Subject = 'Ihr neues Passwort!';
    $mail->Body    = 
"<h3>Neues Passwort setzen</h3>
<p>Link gültig 30 Minuten bis $expiresStr</p>
<a href='https://hope-fly.de/dog/pwreset/$pwtoken'>Passwort setzen</a>";

    return $mail->send();
}

$data = json_decode(file_get_contents("php://input"));
// $data = json_decode(
//     '{
//         "email": "a@q.q"
//     }'
// );
$returnData = new CMsg(0);

//IF REQUEST METHOD IS NOT EQUAL TO POST
if($_SERVER["REQUEST_METHOD"] != "POST")
{
    $returnData = new CMsg(0,404,'Page Not Found! REQUEST_METHOD');
    echo $returnData->jsonarray();
    return;
}

$fields = ['fields' => ['email']];

// CHECKING EMPTY FIELDS
if(
    !isset($data->email) 
    || empty(trim($data->email))
    )
{
    $returnData = new CMsg(0,422,'Please Fill in all Required Fields!',$fields);
    echo $returnData->jsonarray();
    return;
}

// IF THERE ARE NO EMPTY FIELDS THEN-
$email = trim($data->email);

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    $returnData = new CMsg(0, 422, 'Invalid Email Address!');
    echo $returnData->jsonarray();
    return;
}

try
{
    $stmt = $conn->prepare("SELECT * FROM `dogs` WHERE `email`=?");
    $stmt->execute([$email]); 

    // IF THE USER IS FOUND BY EMAIL
    if($stmt->rowCount())
    {
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        $pwtoken = getNewPwtoken(20, $conn);
        if (strlen($pwtoken) == 0) 
        {
            $returnData = new CMsg(
                0,
                507,
                'Too many Passwordrequests on the server, try it again later'
            );
            echo $returnData->jsonarray();
            return;
        }
        updatePwtoken($email, $pwtoken);
        if(sendMail($email, $pwtoken))
        {
            $returnData = new CMsg(
                1,
                200,
                'Successful Passwordrequest, Email is send! pwtoken: ' . $pwtoken,
                null,
                $row
            );
        }
        else
        {
            $returnData = new CMsg(0, 500, "Sorry, there was an error sending your email.");
        }
    // IF THE USER IS NOT FOUND BY EMAIL THEN SHOW THE FOLLOWING ERROR
    }
    else
    {
        $returnData = new CMsg(0,422,'Invalid Email Address! No Email found!');
    }
}
catch(PDOException $e)
{
    $returnData = new CMsg(0,500,$e->getMessage());
}

echo $returnData->jsonarray();
?>