<?php

include_once('../../sys/inc/core.php');
include_once('inc/configs.php');
only_reg();
if ($user['group_access'] < 7 && !in_array($user['id'], $ny_settings['array_ny_admins'])) {
    header("Location: /index.php?");
    exit();
}
$set['title'] = 'Обложки - Админка';
include_once(HEAD);

aut();

switch (@$_GET['action']):
    case 'addCover':
        if (!isset($_GET['category_id']) || !mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversCategories` WHERE `id` = '" . intval(@$_GET['category_id']) . "'"), 0)) {
            $_SESSION['err'] = lang('Категория не найдена');
            header("Location: ?");
            exit();
        }
        $category = mysql_fetch_array(mysql_query("SELECT * FROM `profileCoversCategories` WHERE `id` = '" . intval($_GET['category_id']) . "'"));
        if (isset($_POST['submit']) && isset($_POST['price']) && isset($_FILES['cover'])) {
            $price = abs($_POST['price']);
            $coverFile = $_FILES['cover'];
            @$image = imagecreatefromstring(file_get_contents($coverFile['tmp_name']));
            if (!strstr($coverFile['type'], 'image/')) {
                $err[] = lang('Это не картинка');
            } elseif ($coverFile['size'] < 1) {
                $err[] = lang('Загружен файл нулевого размера');
            } elseif (imageSX($image) < $cover_sizes['width'] || imageSY($image) < $cover_sizes['height']) {
                $err[] = lang('Разрешено загружать картинки c разрешением') . ' ' . $cover_sizes['width'] . 'x ' . $cover_sizes['height'];
            } else {
                mysql_query("INSERT INTO `profileCoversList` (`id_category`, `price`) VALUES ('$category[id]', '$price')");
                $cid = mysql_insert_id();

                crop_cover($coverFile['tmp_name'], $cid);
                @unlink($coverFile['tmp_name']);

                imageDestroy($image);
                $_SESSION['message'] = lang('Обложка успешно загружена');
                header("Location: ?action=category&category_id=$category[id]");
                exit();
            }
        }
        err();

        echo "<form method='POST' class='list-group-item' action='' enctype='multipart/form-data'>\n";
        echo "<input type='file' name='cover' class='list-group-item'/><br />\n";
        $doc->Input('price', 'Цена в валюте сайта');
        echo "<br />";
        $doc->Button('btn btn-primary-outline btn-sm', 'submit', 'plus', 'Добавить');
        $doc->Link('btn btn-secondary-outline btn-sm', "?action=category&category_id=$category[id]", null, 'Отмена');
        echo "</form>\n";

        break;
    case 'addCategory':
        if (isset($_POST['submit']) && isset($_POST['name'])) {
            $name = $_POST['name'];
            if (utf8_strlen(trim($name)) < 1) {
                $err[] = lang('Введите название');
            } elseif (utf8_strlen($name) > 100) {
                $err[] = lang('Название слишком длинное');
            } elseif (mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversCategories` WHERE `name` = '" . mysql_real_escape_string($name) . "'"), 0)) {
                $err[] = lang('Категория с таким названием уже существует');
            } else {
                mysql_query("INSERT INTO `profileCoversCategories` (`name`) VALUES ('" . mysql_real_escape_string($name) . "')");
                $_SESSION['message'] = lang('Категория успешно добавлена');
                header("Location: ?");
                exit();
            }
        }
        err();
        echo "<form method='POST' class='list-group-item' action=''>\n";
        $doc->Input('name', 'Название');
        echo "<br />";
        $doc->Button('btn btn-success btn-sm', 'submit', 'plus', 'Добавить');
        $doc->Link('btn btn-secondary btn-sm', '?', null, 'Отмена');
        echo "</form>\n";
        break;
    case 'editCover':
        if (!isset($_GET['cover_id']) || !mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversList` WHERE `id` = '" . intval(@$_GET['cover_id']) . "'"), 0)) {
            $_SESSION['err'] = lang('Обложка не найдена');
            header("Location: ?");
            exit();
        }
        $cover = mysql_fetch_array(mysql_query("SELECT * FROM `profileCoversList` WHERE `id` = '" . intval($_GET['cover_id']) . "'"));
        $category = mysql_fetch_array(mysql_query("SELECT * FROM `profileCoversCategories` WHERE `id` = '$cover[id_category]'"));
        if (isset($_POST['submit']) && isset($_POST['price'])) {
            $price = abs($_POST['price']);
            mysql_query("UPDATE `profileCoversList` SET `price` = '$price' WHERE `id` = '$cover[id]'");
            header("Location: ?action=category&category_id=$category[id]");
            exit();
        }
        err();
        echo "<form method='POST' class='list-group-item' action=''>\n";

        $doc->Input('price', 'Цена', 5, "$cover[price]");
        echo "<br />";
        $doc->Button('btn btn-success btn-sm', 'submit', 'save', 'Сохранить');
        $doc->Link('btn btn-secondary btn-sm', "?action=category&amp;category_id=$category[id]", null, 'Отмена');
        echo "</form>\n";

        echo "<a href='?action=image&amp;cover_id=$cover[id]' class='list-group-item'>Заменить изображение</a>\n";

        break;
    case 'editCategory':
        if (!isset($_GET['category_id']) || !mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversCategories` WHERE `id` = '" . intval(@$_GET['category_id']) . "'"), 0)) {
            $_SESSION['err'] = lang('Категория не найдена');
            header("Location: ?");
            exit();
        }
        $category = mysql_fetch_array(mysql_query("SELECT * FROM `profileCoversCategories` WHERE `id` = '" . intval($_GET['category_id']) . "'"));
        if (isset($_POST['submit']) && isset($_POST['name'])) {
            $name = $_POST['name'];
            if (utf8_strlen(trim($name)) < 1) {
                $err[] = lang('Введите название');
            } elseif (utf8_strlen($name) > 100) {
                $err[] = lang('Название слишком длинное');
            } elseif (mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversCategories` WHERE `name` = '" . mysql_real_escape_string($name) . "' AND `id` <> '$category[id]'"), 0)) {
                $err[] = lang('Категория с таким названием уже существует');
            } else {
                mysql_query("UPDATE `profileCoversCategories` SET `name` = '" . mysql_real_escape_string($name) . "' WHERE `id` = '$category[id]'");
                $_SESSION['message'] = lang('Изменения сохранены');
                header("Location: ?");
                exit();
            }
        }
        err();
        echo "<form method='POST' class='list-group-item' action=''>\n";
        $doc->Input('name', 'Название', 100, "$category[name]");
        echo "<br />";
        $doc->Button('btn btn-success btn-sm', 'submit', 'save', 'Сохранить');
        $doc->Link('btn btn-secondary btn-sm', '?', null, 'Отмена');
        echo "</form>\n";
        break;
    case 'image':
        if (!isset($_GET['cover_id']) || !mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversList` WHERE `id` = '" . intval(@$_GET['cover_id']) . "'"), 0)) {
            $_SESSION['err'] = lang('Обложка не найдена');
            header("Location: ?");
            exit();
        }
        $cover = mysql_fetch_array(mysql_query("SELECT * FROM `profileCoversList` WHERE `id` = '" . intval($_GET['cover_id']) . "'"));
        $category = mysql_fetch_array(mysql_query("SELECT * FROM `profileCoversCategories` WHERE `id` = '$cover[id_category]'"));
        if (isset($_POST['submit']) && isset($_FILES['cover'])) {
            $coverFile = $_FILES['cover'];
            @$image = imagecreatefromstring(file_get_contents($coverFile['tmp_name']));
            if (!strstr($coverFile['type'], 'image/')) {
                $err[] = lang('Это не картинка');
            } elseif ($coverFile['size'] < 1) {
                $err[] = lang('Загружен файл нулевого размера');
            } elseif (imageSX($image) < $cover_sizes['width'] || imageSY($image) < $cover_sizes['height']) {
                $err[] = lang('Разрешено загружать картинки c разрешением') . ' ' . $cover_sizes['width'] . 'x ' . $cover_sizes['height'];
            } else {
                @unlink($covers_images_dir_path . $cover['id'] . '.jpg');
                foreach ($preview_sizes as $preview_size)
                    @unlink($covers_images_dir_path . $cover['id'] . '_' . $preview_size . '.jpg');

                crop_cover($coverFile['tmp_name'], $cover['id']);
                @unlink($coverFile['tmp_name']);

                imageDestroy($image);
                header("Location: ?action=category&category_id=$category[id]");
                exit();
            }
        }
        err();
        echo "<form method='POST' action='' class='list-group-item' enctype='multipart/form-data'>\n";
        echo "<input type='file' name='cover' class='list-group-item'/><br />\n";

        $doc->Button('btn btn-success btn-sm', 'submit', null, 'Заменить');
        $doc->Link('btn btn-secondary btn-sm', "?action=category&amp;category_id=$category[id]", null, 'Отмена');
        echo "</form>\n";

        break;
    case 'deleteCover':
        if (!isset($_GET['cover_id']) || !mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversList` WHERE `id` = '" . intval(@$_GET['cover_id']) . "'"), 0)) {
            $_SESSION['err'] = lang('Обложка не найдена');
            header("Location: ?");
            exit();
        }
        $cover = mysql_fetch_array(mysql_query("SELECT * FROM `profileCoversList` WHERE `id` = '" . intval($_GET['cover_id']) . "'"));
        $category = mysql_fetch_array(mysql_query("SELECT * FROM `profileCoversCategories` WHERE `id` = '$cover[id_category]'"));
        if (isset($_POST['submit'])) {

            @unlink($covers_images_dir_path . $cover['id'] . '.jpg');
            foreach ($preview_sizes as $preview_size) {
                @unlink($covers_images_dir_path . $cover['id'] . '_' . $preview_size . '.jpg');
            }

            mysql_query("DELETE FROM `profileCoversList` WHERE `id` = '$cover[id]'");
            mysql_query("UPDATE `user` SET `profileCover` = '0' WHERE `profileCover` = '$cover[id]'");
            $_SESSION['message'] = lang('Обложка удалена');
            header("Location: ?action=category&category_id=$category[id]");
            exit();
        }
        err();
        echo "<form method='POST' class='list-group-item' action=''>\n";
        echo lang('Удалить обложку') . "? <br /><br /><input class='btn btn-primary-outline btn-sm' type='submit' name='submit' value='" . lang('Удалить') . "' /> \n";
        echo "<a class='btn btn-secondary-outline btn-sm' href='?action=category&amp;category_id=$category[id]'>" . lang('Отмена') . "</a>\n";
        echo "</form>\n";

        break;
    case 'deleteCategory':
        if (!isset($_GET['category_id']) || !mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversCategories` WHERE `id` = '" . intval(@$_GET['category_id']) . "'"), 0)) {
            $_SESSION['err'] = lang('Категория не найдена');
            header("Location: ?");
            exit();
        }
        $category = mysql_fetch_array(mysql_query("SELECT * FROM `profileCoversCategories` WHERE `id` = '" . intval($_GET['category_id']) . "'"));
        if (isset($_POST['submit'])) {
            $qcovers = mysql_query("SELECT * FROM `profileCoversList` WHERE `id_category` = '$category[id]'");
            while ($cover = mysql_fetch_array($qcovers)):

                @unlink($covers_images_dir_path . $cover['id'] . '.jpg');
                foreach ($preview_sizes as $preview_size)
                    @unlink($covers_images_dir_path . $cover['id'] . '_' . $preview_size . '.jpg');

                mysql_query("DELETE FROM `profileCoversList` WHERE `id` = '$cover[id]'");
                mysql_query("UPDATE `user` SET `profileCover` = '0' WHERE `profileCover` = '$cover[id]'");
            endwhile;
            $_SESSION['message'] = lang('Категория удалена');
            mysql_query("DELETE FROM `profileCoversCategories` WHERE `id` = '$category[id]'");
            header("Location: ?");
            exit();
        }
        err();
        echo "<form method='POST' class='list-group-item' action=''>\n";
        echo lang('Удалить категорию') . "? <br /><br /><input class='btn btn-primary-outline btn-sm' type='submit' name='submit' value='" . lang('Удалить') . "' /> \n";
        echo "<a class='btn btn-secondary-outline btn-sm' href='?'>" . lang('Отмена') . "</a>\n";
        echo "</form>\n";
        break;
    case 'category':
        if (!isset($_GET['category_id']) || !mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversCategories` WHERE `id` = '" . intval(@$_GET['category_id']) . "'"), 0)) {
            $_SESSION['err'] = lang('Категория не найдена');
            header("Location: ?");
            exit();
        }
        $category = mysql_fetch_array(mysql_query("SELECT * FROM `profileCoversCategories` WHERE `id` = '" . intval($_GET['category_id']) . "'"));
        $k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversList` WHERE `id_category` = '$category[id]'"), 0);
        if (!$k_post) {
            $doc->NoResult();
        }
        $k_page = k_page($k_post, $set['p_str']);
        $page = page($k_page);
        $start = $set['p_str'] * $page - $set['p_str'];
        $q = mysql_query("SELECT * FROM `profileCoversList` WHERE `id_category` = '$category[id]' ORDER BY `price` ASC LIMIT $start, $set[p_str]");
        while ($post = mysql_fetch_assoc($q)) {
            echo "<table class='list-group-item-komm'><tr><td class='icon14'>";
            show_cover_preview($post['id'], $preview_sizes['small']);
            echo "</td><td class='null'>";
            echo "<b>" . lang('Цена') . ":</b> " . sklon_text($post['price'], $sklon_balance_array) . "<br />\n";
            echo "<a href='?action=editCover&amp;cover_id=$post[id]'>" . lang('Редактировать') . "</a> <a href='?action=deleteCover&cover_id=$post[id]'>" . lang('Удалить') . "</a><br />\n";
            echo "</td></tr></table>";
        }
        if ($k_page > 1) {
            str("?action=category&category_id=$category[id]&", $k_page, $page);
        }

        echo "<a href='?action=addCover&category_id=$category[id]' class='list-group-item'><i class='fa fa-image fa-fw'></i> " . lang('Добавить обложку') . "</a>\n";

        break;
    default:
        $q = mysql_query("SELECT * FROM `profileCoversCategories` ORDER BY `name` DESC");
        while ($post = mysql_fetch_assoc($q)) {
            echo "<div class='list-group-item'>\n";
            echo "<span style='float: right;'><a href='?action=editCategory&category_id=$post[id]' class='hint--left' data-hint='" . lang('Редактировать') . "'><i class='fa fa-edit fa-fw'></i></a> <a href='?action=deleteCategory&category_id=$post[id]' class='hint--left' data-hint='" . lang('Удалить') . "'><i class='fa fa-trash-o'></i></a></span>";
            echo "<i class='fa fa-folder fa-fw'></i> <a href='?action=category&category_id=$post[id]'>" . htmlspecialchars($post['name']) . "</a> <span class='label label-default'>" . mysql_result(mysql_query("SELECT COUNT(*) FROM `profileCoversList` WHERE `id_category` = '$post[id]'"), 0) . "</span>";
            echo "</div>\n";
        }

        echo "<a href='?action=addCategory' class='list-group-item'><i class='fa fa-plus fa-fw'></i> Добавить категорию</a>\n";

        break;
endswitch;
include_once(FOOT);
