<?php

class EmailUser extends db {

    protected $address;

    public function __construct($to = null) {
        $this->address = $to;
    }

    public function getUser() {
        $callback = $this->getAddres();

        return call_user_func(array($this, $callback['method']));
    }

    protected function getAddres() {
        if (preg_match("#^[A-z0-9-\._-]+@[A-z0-9\._-]{2,}\.[A-z]{2,8}$#ui", $this->address)) {
            $data = array('method' => 'getUserEmail');
        } elseif ($this->address === '0') {
            $data = array('method' => 'getUserSystem');
        } elseif (is_numeric($this->address) || preg_match('/^([A-z0-9-\.-_]+)$/ui', $this->address, $matches)) {
            $data = array('method' => 'getUserSite');
        } else {
            $data = array('method' => 'getUserNew');
        }

        return $data;
    }

    protected function getUserEmail() {
        global $config;
        $db = new db;

        if (preg_match("#^[A-z0-9-\._-]+@[A-z0-9\._-]{2,}\.[A-z]{2,4}$#ui", $this->address)) {
            if (in_array(strtolower(preg_replace("/.*?@/", '', $this->address)), $config['aliase'])) {
                $user = $db->get_row($db->query("SELECT * FROM `user` AS u WHERE `nick` = '" . $db->safesql(preg_replace("/@.*/", '', $this->address)) . "' LIMIT 1"));
                return $this->getUserSite($user);
            }
        }

        return array(
            'avatar' => '<img src="style/icons/email.jpg" />',
            'icon' => '<img src="style/icons/e.gif" />',
            'nick' => stripcslashes(htmlspecialchars($this->address)),
            'link' => stripcslashes(htmlspecialchars($this->address)),
            'id' => $this->address,
            'ban' => false,
        );
    }

    protected function getUserSite($user = null) {
        $db = new db;

        if ($user == null) {
            $user = $db->get_row($db->query("SELECT * FROM `user` AS u WHERE `id` = '" . (int) $this->address . "' OR `nick` = '" . $db->safesql($this->address) . "' LIMIT 1"));
        }

        if (empty($user)) {
            return $this->getUserNew();
        }

        $user['icon'] = "<i class='fa fa-user fa-fw'></i>";
        $user['link'] = "<a href='/id$user[id]'>$user[nick]</a>";
        return $user;
    }

    #Система сайта

    protected function getUserSystem() {
        return array(
            'icon' => "<i class='fa fa-user fa-fw'></i>",
            'id' => 0,
            'nick' => 'Система',
            'ncolor' => '000',
            'ncolor2' => '000',
            'ban' => false,
        );
    }

    /**
     * Если новое сообщение
     * @return Array()
     */
    protected function getUserNew() {
        return array(
            'avatar' => '',
            'icon' => '',
            'id' => '',
            'ban' => false,
            'nick' => 'Новое сообщение'
        );
    }
}
