<?php

/* DCMS Special
 * Дата последнего редактирования 18.01.2016
 * Модифицировал densnet
 */

foreach (array('start', 'compress', 'sess', 'settings', 'db_connect', 'ipua', 'fnc', 'adm_check', 'user', 'shif') as $inc) {
    require_once "../sys/inc/$inc.php";
}

access('user_prof_edit', null, 'index.php?' . SID);
adm_check();

if (isset($_GET['id'])) {
    $ank['id'] = intval($_GET['id']);
} else {
    header("Location: /index.php?" . SID);
    exit;
}


$us = $db->super_query("SELECT COUNT(*) as count FROM `user` WHERE `id` = '$ank[id]' LIMIT 1");
if ($us['count'] == 0) {
    header("Location: /index.php?" . SID);
    exit;
}

$ank = get_user($ank['id']);
if ($user['level'] <= $ank['level']) {
    header("Location: /index.php?" . SID);
    exit;
}

$set['title'] = 'Профиль пользователя ' . $ank['nick'];
require_once H . 'sys/inc/thead.php';

aut();
err();

if (isset($_POST['save'])) {

    if (isset($_POST['nick']) && $_POST['nick'] != $ank['nick']) {

        $ni = $db->super_query("SELECT COUNT(*) as count FROM `user` WHERE `nick` = '" . $db->safesql($_POST['nick']) . "'");
        if ($ni['count'] == 1) {
            $err[] = 'Логин &quot;' . $_POST['nick'] . '&quot; уже занят';
        } elseif (access('user_change_nick')) {
            $nick = $db->safesql($_POST['nick']);
            if (!preg_match("#^([A-z0-9\-\_\ ])+$#ui", $nick))
                $err[] = 'В логине присутствуют запрещенные символы';
            if (utf8_strlen($nick) < 3) {
                $err[] = 'Короткий логин';
            }
            if (utf8_strlen($nick) > 32) {
                $err[] = 'Длина логина превышает 32 символа';
            }
            if (!isset($err)) {
                admin_log('Пользователи', 'Изменение логина', "Логин '$ank[nick]' изменен на '[url=/id$ank[id]]" . $nick . "[/url]'");

                $db->query("INSERT INTO `history_nick` SET `nick_last` = '$ank[nick]', `nick_new` = '$nick', `user_id` = '$ank[id]', `who` = '$user[id]', `time` = '$time'");

                $ank['nick'] = $nick;

                $db->query("UPDATE `user` SET `nick` = '" . $db->safesql($ank['nick']) . "' WHERE `id` = '$ank[id]' LIMIT 1");

                $_SESSION['message'] = lang('Логин изменен');

                header("Location: /panel/user.php?id=$ank[id]");
                exit();
            }
        } else {
            $err[] = lang('У Вас нет привилегий на изменение логина пользователя');
        }
    }


    $ank['set_files'] = (isset($_POST['set_files']) && $_POST['set_files']) ? '1' : '0';
    $db->query("UPDATE `user` SET `set_files` = '$ank[set_files]' WHERE `id` = '$ank[id]' LIMIT 1");

    if (isset($_POST['set_p_str']) && ($_POST['set_p_str'] > 0 && $_POST['set_p_str'] <= 100)) {
        $ank['set_p_str'] = (int) $_POST['set_p_str'];
        $db->query("UPDATE `user` SET `set_p_str` = '$ank[set_p_str]' WHERE `id` = '$ank[id]' LIMIT 1");
    } else {
        $err[] = 'Неправильное количество пунктов на страницу';
    }

    if (isset($_POST['ank_name']) && utf8_strlen(esc(stripcslashes(htmlspecialchars($_POST['ank_name'])))) <= 32) {
        $ank['ank_name'] = esc(stripcslashes(htmlspecialchars($_POST['ank_name'])));
        $db->query("UPDATE `user` SET `ank_name` = '$ank[ank_name]' WHERE `id` = '$ank[id]' LIMIT 1");
    } else {
        $err[] = 'Имя не может быть длиннее 32 символов';
    }

    if (isset($_POST['ank_surname']) && utf8_strlen(esc(stripcslashes(htmlspecialchars($_POST['ank_surname'])))) <= 32) {
        $ank['ank_surname'] = esc(stripcslashes(htmlspecialchars($_POST['ank_surname'])));
        $db->query("UPDATE `user` SET `ank_surname` = '$ank[ank_surname]' WHERE `id` = '$ank[id]' LIMIT 1");
    } else {
        $err[] = 'Фамилия не может быть длиннее 32 символов';
    }

    if (isset($_POST['ank_patronymic']) && utf8_strlen(esc(stripcslashes(htmlspecialchars($_POST['ank_patronymic'])))) <= 32) {
        $ank['ank_patronymic'] = esc(stripcslashes(htmlspecialchars($_POST['ank_patronymic'])));
        $db->query("UPDATE `user` SET `ank_patronymic` = '$ank[ank_patronymic]' WHERE `id` = '$ank[id]' LIMIT 1");
    } else {
        $err[] = 'Отчество не может быть длиннее 32 символов';
    }

    if (isset($_POST['ank_d_r']) && (is_numeric($_POST['ank_d_r']) && $_POST['ank_d_r'] > 0 && $_POST['ank_d_r'] <= 31 || $_POST['ank_d_r'] == NULL)) {
        $ank['ank_d_r'] = $_POST['ank_d_r'];
        if ($ank['ank_d_r'] == null) {
            $ank['ank_d_r'] = 'null';
        }
        $db->query("UPDATE `user` SET `ank_d_r` = $ank[ank_d_r] WHERE `id` = '$ank[id]' LIMIT 1");
        if ($ank['ank_d_r'] == 'null') {
            $ank['ank_d_r'] = NULL;
        }
    } else {
        $err[] = 'Неверный формат дня рождения';
    }

    if (isset($_POST['ank_m_r']) && ($_POST['ank_m_r'] > 0 && $_POST['ank_m_r'] <= 12 || $_POST['ank_m_r'] == NULL)) {
        $ank['ank_m_r'] = (int) $_POST['ank_m_r'];
        if ($ank['ank_m_r'] == null) {
            $ank['ank_m_r'] = 'null';
        }
        $db->query("UPDATE `user` SET `ank_m_r` = $ank[ank_m_r] WHERE `id` = '$ank[id]' LIMIT 1");
        if ($ank['ank_m_r'] == 'null') {
            $ank['ank_m_r'] = NULL;
        }
    } else {
        $err[] = 'Неверный формат месяца рождения';
    }

    if (isset($_POST['ank_g_r']) && ($_POST['ank_g_r'] > 0 && $_POST['ank_g_r'] <= date('Y') || $_POST['ank_g_r'] == NULL)) {
        $ank['ank_g_r'] = (int) $_POST['ank_g_r'];
        if ($ank['ank_g_r'] == null) {
            $ank['ank_g_r'] = 'null';
        }
        $db->query("UPDATE `user` SET `ank_g_r` = $ank[ank_g_r] WHERE `id` = '$ank[id]' LIMIT 1");
        if ($ank['ank_g_r'] == 'null') {
            $ank['ank_g_r'] = NULL;
        }
    } else {
        $err[] = 'Неверный формат года рождения';
    }

    if (isset($_POST['ank_city']) && utf8_strlen(esc(stripcslashes(htmlspecialchars($_POST['ank_city'])))) <= 32) {
        $ank['ank_city'] = esc(stripcslashes(htmlspecialchars($_POST['ank_city'])));
        $db->query("UPDATE `user` SET `ank_city` = '$ank[ank_city]' WHERE `id` = '$ank[id]' LIMIT 1");
    } else {
        $err[] = 'Название города не может быть длиннее 32 символов';
    }

    if (isset($_POST['ank_icq']) && (strlen($_POST['ank_icq']) >= 5 && strlen($_POST['ank_icq']) <= 9 || $_POST['ank_icq'] == NULL)) {
        $ank['ank_icq'] = (int) $_POST['ank_icq'];
        if ($ank['ank_icq'] == null) {
            $ank['ank_icq'] = 'null';
        }
        $db->query("UPDATE `user` SET `ank_icq` = $ank[ank_icq] WHERE `id` = '$ank[id]' LIMIT 1");
        if ($ank['ank_icq'] == 'null') {
            $ank['ank_icq'] = NULL;
        }
    } else {
        $err[] = 'Неверный формат ICQ';
    }

    if (isset($_POST['ank_n_tel']) && (strlen($_POST['ank_n_tel']) >= 5 && strlen($_POST['ank_n_tel']) <= 11 || $_POST['ank_n_tel'] == NULL)) {
        $ank['ank_n_tel'] = (int) $_POST['ank_n_tel'];
        $db->query("UPDATE `user` SET `ank_n_tel` = '$ank[ank_n_tel]' WHERE `id` = '$ank[id]' LIMIT 1");
    } else {
        $err[] = 'Неверный формат номера телефона';
    }

    if (isset($_POST['ank_mail']) && (preg_match('#^[a-z0-9_\-\.]+\@[a-z0-9_\-\.]+$#iu', $_POST['ank_mail']) || $_POST['ank_mail'] == NULL)) {
        $ank['ank_mail'] = esc($_POST['ank_mail']);
        $db->query("UPDATE `user` SET `ank_mail` = '$ank[ank_mail]' WHERE `id` = '$ank[id]' LIMIT 1");
    } else {
        $err[] = 'Неверный E-mail';
    }

    if (isset($_POST['ank_about_me']) && utf8_strlen(esc(stripcslashes(htmlspecialchars($_POST['ank_about_me'])))) <= 512) {
        $ank['ank_about_me'] = esc(stripcslashes(htmlspecialchars($_POST['ank_about_me'])));
        $db->query("UPDATE `user` SET `ank_about_me` = '$ank[ank_about_me]' WHERE `id` = '$ank[id]' LIMIT 1");
    } else {
        $err[] = 'О себе нужно писать меньше :)';
    }

    if (isset($_POST['new_pass']) && utf8_strlen($_POST['new_pass']) > 5) {
        admin_log('Пользователи', 'Смена пароля', "Пользователю '$ank[nick]' установлен новый пароль");
        $db->query("UPDATE `user` SET `pass` = '" . shif($_POST['new_pass']) . "' WHERE `id` = '$ank[id]' LIMIT 1");
    }

    if (access('user_change_group') && isset($_POST['group_access'])) {
        $gr = $db->super_query("SELECT COUNT(*) as count FROM `user_group` WHERE `id` = '" . intval($_POST['group_access']) . "' AND `level` < '$user[level]'");
        if ($gr['count'] == 1) {
            if ($ank['group_access'] != intval($_POST['group_access'])) {
                $gr_name = $db->super_query("SELECT `name` as name FROM `user_group` WHERE `id` = '" . intval($_POST['group_access']) . "'");  ////////////// 

                admin_log('Пользователи', 'Изменение статуса', "Пользователь '$ank[nick]': Статус '$ank[group_name]' изменен на '" . $gr_name['name'] . "'");
                $ank['group_access'] = intval($_POST['group_access']);
                $db->query("UPDATE `user` SET `group_access` = '$ank[group_access]' WHERE `id` = '$ank[id]' LIMIT 1");
            }
        }
    }

    if (isset($_POST['money']) && is_numeric($_POST['money'])) {
        $ank['money'] = intval($_POST['money']);
        $db->query("UPDATE `user` SET `money` = '$ank[money]' WHERE `id` = '$ank[id]' LIMIT 1");
    }

    if (isset($_POST['rating']) && is_numeric($_POST['rating'])) {
        $ank['rating'] = intval($_POST['rating']);
        $db->query("UPDATE `user` SET `rating` = '$ank[rating]' WHERE `id` = '$ank[id]' LIMIT 1");
    }

    admin_log('Пользователи', 'Профиль', "Редактирование профиля '$ank[nick]' (id#$ank[id])");

    if (!isset($err)) {
        $_SESSION['message'] = lang('Изменения сохранены');

        header("Location: /panel/user.php?id=$ank[id]");
        exit();
    }
}

#Навигация
echo "<div class='list-group-item-null list-group-item-grey'><small>";
echo "<a href='/' class='hint--right' data-hint='" . lang('На главную') . "'><i class='fa fa-home fa-lg'></i></a> <i class='fa fa-angle-right fa-fw'></i> ";
echo "<a href='/id$ank[id]'>$ank[nick]</a> <i class='fa fa-angle-right fa-fw'></i> ";
echo lang('Редактирование');
echo "</small></div><br />";

echo "<form method = 'post' class = 'list-group-item-null' action = 'user.php?id=$ank[id]'>\n";

echo "Логин<br />";
echo "<input" . (access('user_change_nick') ? null : ' disabled="disabled"') . " class='form-control' type='text' name='nick' value='$ank[nick]' maxlength='32' />";
echo "Имя<br />";
echo "<input class='form-control' type='text' name='ank_name' value='$ank[ank_name]' maxlength='32' />";
echo "Фамилия<br />";
echo "<input class='form-control' type='text' name='ank_surname' value='$ank[ank_surname]' maxlength='32' />";
echo "Отчество<br />";
echo "<input class='form-control' type='text' name='ank_patronymic' value='$ank[ank_patronymic]' maxlength='32' />";
echo "Дата рождения<br />\n";
echo "<div class='col-xs-4'><input class='form-control' type='text' name='ank_d_r' value='$ank[ank_d_r]' maxlength='2' /></div>";
echo "<div class='col-xs-4'><input class='form-control' type='text' name='ank_m_r' value='$ank[ank_m_r]' maxlength='2' /></div>";
echo "<div class='col-xs-4'><input class='form-control' type='text' name='ank_g_r' value='$ank[ank_g_r]' maxlength='4' /></div><br /><br />";
echo "Город<br />";
echo "<input class='form-control' type='text' name='ank_city' value='$ank[ank_city]' maxlength='32' />";
echo "ICQ<br />";
echo "<input class='form-control' type='text' name='ank_icq' value='$ank[ank_icq]' maxlength='9' />";
echo "E-mail<br />";
echo "<input class='form-control' type='text' name='ank_mail' value='$ank[ank_mail]' maxlength='32' />";
echo "Номер телефона<br />";
echo "<input class='form-control' type='text' name='ank_n_tel' value='$ank[ank_n_tel]' maxlength='11' />";
echo "О себе<br />";
echo "<input class='form-control' type='text' name='ank_about_me' value='$ank[ank_about_me]' maxlength='512' />";
echo "Пунктов на страницу<br />";
echo "<input class='form-control' type='text' name='set_p_str' value='$ank[set_p_str]' maxlength='3' />";
echo "Выгрузка файлов<br />";
echo "<select class='form-control' name='set_files'>";
if ($ank['set_files'] == 1) {
    $sel = ' selected = "selected"';
} else {
    $sel = NULL;
}
echo "<option value = \"1\"$sel>Показывать поле</option>\n";
if ($ank['set_files'] == 0) {
    $sel = ' selected = "selected"';
} else {
    $sel = NULL;
}
echo "<option value = '0'$sel>Не использовать выгрузку</option>\n";
echo "</select>\n";

if ($user['level'] < 3) {
    $dis = ' disabled = "disabled"';
} else {
    $dis = NULL;
}
echo "Рубли<br />";
echo "<input class='form-control' type='text'$dis name='money' value='$ank[money]' />\n";
echo "Рейтинг<br /><input class='form-control' type='text'$dis name='rating' value='$ank[rating]' />\n";
echo "Группа<br /><select class='form-control' name='group_access'" . (access('user_change_group') ? null : ' disabled="disabled"') . ">\n";

$q = $db->query("SELECT * FROM `user_group` ORDER BY `level`,`id` ASC");
while ($post = $db->get_row($q)) {
    echo "<option value = '$post[id]'" . ($post['level'] >= $user['level'] ? " disabled = 'disabled'" : null) . "" . ($post['id'] == $ank['group_access'] ? " selected = 'selected'" : null) . ">" . $post['name'] . "</option>\n";
}

echo "</select><br />";

echo "Новый пароль<br />";
echo "<input class='form-control' type='text' name='new_pass' value='' /><br />\n";

$doc->Button('btn btn-success btn-sm', 'save', 'save', 'Сохранить');
echo "</form>";

require_once H . 'sys/inc/tfoot.php';
