<?php

use mystic\forum\orm\User;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;

$token = $_GET["token"] ?? call_user_func(function() {
    http_response_code(400);
    msg_error(__("Missing token"));
    exit;
});
$sig = $_GET["sig"] ?? call_user_func(function() {
    http_response_code(400);
    msg_error(__("Missing signature"));
    exit;
});

$user = new User();
$user->activationToken = $token;

if (!$db->fetchWhere($user, "activation_token")) {
    http_response_code(400);
    msg_error(__("Invalid token"));
    exit;
}

$expectedSignature = base64_encode(hash("sha256", env("SECRET") . $user->activationToken . $user->id, true));

if ($expectedSignature !== $sig) {
    http_response_code(400);
    msg_error(__("Invalid signature."));
    exit;
}

$isActivation = !$user->activated;
if ($isActivation) {
    $user->activated = true;
    $user->activationToken = "";

    if (!$db->update($user)) {
        http_response_code(400);
        msg_error(__("Failed to update user"));
        exit;
    }

    msg_info("?!HTML::" . __(
        "Your account has been activated!\nPlease click %link%here%/link% to log in!",
        [
            "link" => '<a href="?_action=auth">',
            "/link" => '</a>',
        ]
    ));
} else {
    $oldEmail = $user->email;
    $newEmail = $user->pendingEmail;

    $user->activationToken = "";
    $user->email = $user->pendingEmail;
    $user->pendingEmail = null;
    $user->pendingEmailCreated = null;

    if (!$db->update($user)) {
        http_response_code(400);
        msg_error(__("Failed to update user"));
        exit;
    }

    $transport = Transport::fromDsn(env("MAILER_DSN"));

    try {
        $transport->send(
            (new Email())
                ->from(env("MAILER_FROM"))
                ->to(new Address($oldEmail, $user->displayName))
                ->text(__(
                    "Hello, %user_display_name%!\n" .
                    "\n" .
                    "Your email address has been successfully changed from %old_email% to %new_email%!\n" .
                    "\n" .
                    "Kind regards,\n" .
                    "%forum_copyright%",
                    params: [
                        "forum_title" => (env("MYSTIC_FORUM_TITLE") ?? "Forum"),
                        "user_display_name" => $user->displayName,
                        "old_email" => $oldEmail,
                        "new_email" => $newEmail,
                        "forum_copyright" => (env("MYSTIC_FORUM_COPYRIGHT") ?? env("MYSTIC_FORUM_TITLE") ?? "Forum")
                    ]
                ))
                ->subject(__("Email address changed"))
        );
    } catch (TransportException $_) {
        // fail silently
    }

    try {
        $transport->send(
            (new Email())
                ->from(env("MAILER_FROM"))
                ->to(new Address($newEmail, $user->displayName))
                ->text(__(
                    "Hello, %user_display_name%!\n" .
                    "\n" .
                    "Your email address has been successfully changed from %old_email% to %new_email%!\n" .
                    "\n" .
                    "Kind regards,\n" .
                    "%forum_copyright%",
                    params: [
                        "forum_title" => (env("MYSTIC_FORUM_TITLE") ?? "Forum"),
                        "user_display_name" => $user->displayName,
                        "old_email" => $oldEmail,
                        "new_email" => $newEmail,
                        "forum_copyright" => (env("MYSTIC_FORUM_COPYRIGHT") ?? env("MYSTIC_FORUM_TITLE") ?? "Forum")
                    ]
                ))
                ->subject(__("Email address changed"))
        );
    } catch (TransportException $_) {
        // fail silently
    }

    msg_info("?!HTML::" . __(
        "Your email address has been changed successfully!\nPlease click %link%here%/link% to return to your profile!",
        [
            "link" => '<a href="?_action=viewuser&user=' . htmlentities(urlencode($user->id)) . '">',
            "/link" => '</a>',
        ]
    ));
}