<?php

namespace User;

use Core\Db;
use PassGen;
use User;

class Email
{
    private array $info = [];

    public function __construct(array $userinfo)
    {
        $this->info = $userinfo ?? User::start()->info;
    }

    public function change(string $old, string $new): string
    {
        if ($old === $new) {
            return $this->info['mail'];
        }

        if ($this->info['emailconfirmation'] === 1) {
            $query = 'insert into emailconfirmation (id, code, pa_em, pass) values (?,?,?,1)';
            $args = [
                $this->info['id'],
                PassGen::intCode(10),
                $new
            ];
            Confirmation::byEmail($this->info, 'email', $new, $args[1]);
        } else {
            $query = 'update users set mail = ?, securetime = unix_timestamp() + 259200 where id = ?';
            $args = [
                $new,
                $this->info['id']
            ];
        }
            Db::sql($query, $args);
            return $new;
    }
}