<?php
namespace app\controllers;

use app\app;
use app\models\magic_links;
use app\models\users;

class magic_link
{
    public static function index()
    {
        $token = $_GET['token'] ?? null;
        if (! $token) {
            $_SESSION['error'] = "Invalid or expired link.";
            header('Location: /account/login');
            exit;
        } else {
            $link = magic_links::validateToken(token: $token);
            if (! $link) {
                $_SESSION['error'] = "Invalid or expired link.";
                header('Location: /account/login');
                exit;
            }
            $user = $link['user_id'] ? users::getById($link['user_id']) : users::getByEmail($link['email']);
            if ($user) { // user with this email exists, log them in
                $_SESSION['user_email'] = $link['email'];
                $_SESSION['user_id']    = $user['id'];
                if (! $user['verified']) {
                    users::verify($link['email']);
                }
                header('Location: /account');
                exit;
            } else { // no users with this email
                $user_replacing_email = users::getByReplaceEmailToken($token);
                if ($user_replacing_email) { // user is replacing their email
                    $user_id = $user_replacing_email['id'];
                    users::updateEmailById($user_id, $link['email']);
                    $_SESSION['user_email'] = $link['email'];
                    $_SESSION['user_id']    = $user_id;
                    if (! $user['verified']) {
                        users::verify($link['email']);
                    }
                    header('Location: /account');
                    exit;
                } else { // new user signup
                    $_SESSION['user_email'] = $link['email'];
                    header('Location: /account/signup');
                    exit;
                }
            }
        }
    }
}
