<?php

$_actionUrlHtml = ($_actionGetId === -1 ?
    '/stickers/?tab=admin&amp;func=edit' :
    '/stickers/?tab=admin&amp;func=edit&amp;id=' . $_actionGetId);
$_actionUrl = str_replace('&amp;', '&', $_actionUrlHtml);

$_actionNameTab = $_actionGetId === -1 ? 'Добавить' : 'Редактирование';
$_actionNameButton = $_actionGetId === -1 ? 'Создать категорию' : 'Сохранить изменения';

$_getDataStickers = [
    'title' => '',
    'price' => '',
    'cover' => '',
    'description' => '',
    'is_show' => 0,
];

if ($_actionGetId !== -1 && ($_getDataStickers = DB::$pdo->queryFetch("SELECT * FROM `stickers_cat` WHERE `id` = :id LIMIT 1",
        [':id' => $_actionGetId])) === false) {
    system:: redirect("Ошибка...<br/>Этой категории не существует", "/stickers/?tab=admin");
}

if (filter_has_var(INPUT_POST, 'cfms')) {
    $args = filter_input_array(INPUT_POST, [
        'title' => [
            'filter' => FILTER_CALLBACK,
            'options' => 'system::check'
        ], 'price' => [
            'filter' => FILTER_VALIDATE_INT,
            'options' => [
                'default' => 0,
                'min_range' => 0
            ]
        ], 'is_show' => [
            'filter' => FILTER_CALLBACK,
            'options' => function($args) {
                return (string)$args === 'on' ? 1 : 0;
            }
        ], 'description' => [
            'filter' => FILTER_CALLBACK,
            'options' => 'system::check'
        ], 'selected_stickers' => [
            'filter' => FILTER_CALLBACK,
            'options' => function ($args) {
                return (int)$args;
            }
        ]
    ]);

    if ($args['selected_stickers'] === null)
        $args['selected_stickers'] = [];

    if (empty($args['is_show']))
        $args['is_show'] = 0;

    $args = array_map(function ($value) {
        return (is_string($value) ? (system::utf_strlen($value) > 4 ? $value : null) : $value);
    }, $args);

    if ((in_array(null, $args, true) || in_array("", $args, true)) === true) {
        system::redirect("Ошибка...<br/>Все поля обязательны", $_actionUrl);
    }

    if ($_getDataStickers['title'] != $args['title'] && (int)DB::$pdo->querySingle("SELECT COUNT(id) FROM `stickers_cat` WHERE `title` = :title LIMIT 1",
            [':title' => $args['title']]) === 1) {
        system:: redirect("Ошибка...<br/>Эта категория уже существует", $_actionUrl);
    }

    system::fixFilesMultiple($_FILES);
    $coverName = $_getDataStickers['cover'];

    if ($_actionGetId === -1 && (empty($_FILES['stick_cover']['tmp_name']) || $_FILES['stick_cover']['error'] !== UPLOAD_ERR_OK)) {
        system:: redirect("Ошибка...<br/>Обложка для раздела обязательна", $_actionUrl);
    }

    if (empty($_FILES['stick_cover']['tmp_name']) === false) {
        /**
         * Получаем тип файла
         */
        $fileCoverType = mime_content_type($_FILES['stick_cover']['tmp_name']);
        $fileCoverType = explode('/', $fileCoverType);
        $fileType = array_shift($fileCoverType);
        $fileExtension = array_shift($fileCoverType);
        if ($fileType !== 'image' || $_FILES['stick_cover']['error'] !== UPLOAD_ERR_OK) {
            system:: redirect("Ошибка...<br/>При загрузки обложки произошла ошибка №" . $_FILES['stick_cover']['error'], $_actionUrl);
        }
        $coverName = md5($_FILES['stick_cover']['tmp_name'] . time()) . '.' . $fileExtension;

        if (empty($coverName) || !copy($_FILES['stick_cover']['tmp_name'], filesPathStickers . $coverName)) {
            system:: redirect("Ошибка...<br/>При загрузки обложки произошла ошибка №8", $_actionUrl);
        }

        if ($_actionGetId !== -1 && is_file(filesPathStickers . $_getDataStickers['cover'])) {
            unlink(filesPathStickers . $_getDataStickers['cover']);
        }
    }

    if ($_actionGetId === -1) {
        DB::$pdo->query("INSERT INTO `stickers_cat` (`id_user`, `time`, `price`, `cover`, `title`, `description`, `is_show`) values(?, ?, ?, ?, ?, ?, ?)", [
            $user['id'], time(), $args['price'], $coverName, $args['title'], $args['description'], $args['is_show']
        ]);
        $_actionGetId = DB::$pdo->lastInsertId();
        $_actionUrl = "/stickers/?tab=admin&func=edit&id=" . $_actionGetId;
        $_actionText = "Успешно...<br/>Новая категория успешно добавлена";
    } else {
        DB::$pdo->query("UPDATE `stickers_cat` SET `price` = ?, `cover` = ?, `title` = ?, `description` = ?, `is_show` = ? WHERE `id` = ?", [
            $args['price'], $coverName, $args['title'], $args['description'], $args['is_show'], $_actionGetId
        ]);
        $_actionText = "Успешно...<br/>Все изменения успешно сохранены";
    }

    if ($_actionGetId !== -1) {

        if (count($args['selected_stickers']) > 0) {
            $fetchQuery = (array)DB::$pdo->query(
                "SELECT id, image FROM `stickers` WHERE `id` IN(" . implode(',', $args['selected_stickers']) . ") AND `id_cat` = ?", [
                $_actionGetId
            ])->fetchAll();
            DB::$pdo->query(
                "DELETE FROM `stickers` WHERE `id` IN(" . implode(',', $args['selected_stickers']) . ") AND `id_cat` = ?", [
                $_actionGetId
            ]);
            foreach ($fetchQuery as $selected_sticker)
                is_file(filesPathStickers . $selected_sticker['image']) && unlink(filesPathStickers . $selected_sticker['image']);
        }
        $prepareInsertQuery = DB::$pdo->prepare("INSERT INTO `stickers` (`id_cat`, `code`, `image`) values(?, ?, ?)");

        foreach ($_FILES['stick_list'] as $key => $item) {
            if ($item['error'] !== UPLOAD_ERR_OK) continue;
            $fileStickType = mime_content_type($item['tmp_name']);
            $fileStickType = explode('/', $fileStickType);
            $fileType = array_shift($fileStickType);
            $fileExtension = array_shift($fileStickType);
            if ($fileType !== 'image') continue;
            $codeStick = md5($item['tmp_name'] . time());
            if (copy($item['tmp_name'], filesPathStickers . $codeStick . '.' . $fileExtension)) {
                $prepareInsertQuery->execute([
                    $_actionGetId, $codeStick, $codeStick . '.' . $fileExtension
                ]);
            }
        }
    }
    system:: redirect($_actionText, $_actionUrl);
}

$title = 'Админка стикеров';
require(CORE . 'head.php');

?>
    <div class="app-block">
    <div class="list" style="border-bottom: 0">
        <div class="sw-block_">
            <div class="sw-cont sw-4">
                <div class="list tab">
                    <a href="/stickers/?tab=admin">Админка</a>
                    <a class="tab_active" href="<?= $_actionUrlHtml ?>"><?= $_actionNameTab ?></a>
                    <?php if ($_actionGetId !== -1) { ?>
                        <a href="/stickers/?tab=admin&amp;func=show&amp;id=<?= $_actionGetId ?>">Просмотр</a>
                        <a href="/stickers/?tab=admin&amp;func=delete&amp;id=<?= $_actionGetId ?>">Удалить</a>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
    <div class="list">
        <div class="app-block-w">

            <form method="post" action="<?= $_actionUrlHtml ?>" enctype="multipart/form-data">

                <label class="_gray _dbl" for="stickers-title">Название:</label>
                <input type="text" class="main-input _w-100" name="title" value="<?= $_getDataStickers['title'] ?>"
                       id="stickers-title">

                <label class="_gray _dbl" for="stickers-title" style="margin: 5px 0">Отоброжать в магазине стикеров:
                    <input type="checkbox" name="is_show"
                           <?= ((int)$_getDataStickers['is_show'] === 1 ? ' checked ' : '') ?>id="stickers-is_show">
                </label>
                <label class="_gray _dbl" for="stickers-price">Цена стикеров:</label>
                <input type="text" class="main-input _w-100" name="price" value="<?= $_getDataStickers['price'] ?>"
                       id="stickers-price">
                <?php if ($_actionGetId === -1) { ?>
                    <label class="_gray _dbl" for="stickers-cover">Обложка:</label>
                    <input name="stick_cover" type="file" id="stickers-cover" accept="image/*" multiple>
                <?php } else { ?>
                    <div class="_gray _dbl">
                        <div class="stickers_item" style="border-bottom: 0; padding: 7px 0">
                            <div class="stickers_thumb">
                                <img src="<?= filesServerStickers . $_getDataStickers['cover'] ?>" class="th_img">
                            </div>
                            <div class="stickers_body">
                                Обложка:<br/>
                                <input name="stick_cover" type="file" id="stick-cover" accept="image/*">
                            </div>
                        </div>
                    </div>
                <?php } ?>
                <label class="_gray _dbl" for="stickers-description">Описание:</label>
                <textarea name="description"
                          id="stickers-description"><?= $_getDataStickers['description'] ?></textarea>

                <label class="_gray _dbl" for="stickers-list">Стикеры:</label>
                <input name="stick_list[]" type="file" id="stickers-list" accept="image/*" multiple>
                <?php
                if ($_actionGetId !== -1) {
                    $query = (array)DB::$pdo->query("SELECT id, image FROM `stickers` WHERE `id_cat` = ? ORDER BY `id` DESC", [
                        $_actionGetId
                    ])->fetchAll();
                    if (count($query) > 0) {
                        ?>
                        <div class="stickers_tt_wrap">
                            <div class="stickers_block_cont">
                                <div class="stickers_list_cont">
                                    <div class="stickers_list_scroll">
                                        <div class="stickers__row">
                                            <?php foreach ($query as $item) { ?>
                                                <div class="sticker_item">
                                                    <label class="sticker_thumb">
                                                        <input class="stickers_checkbox" type="checkbox"
                                                               name="selected_stickers[]" value="<?= $item['id'] ?>"
                                                               data-nostyle/>
                                                        <span class="stickers_control_ui">
                                                        <i class="stickers_control_ui_icon"></i>
                                                    </span>
                                                        <img src="<?= filesServerStickers . $item['image'] ?>"
                                                             class="th_img">
                                                    </label>
                                                </div>
                                            <?php } ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php }
                } ?>
                <div class="_btn-up">
                    <input type="submit" name="cfms" class="main-btn _w-100" value="<?= $_actionNameButton ?>">
                </div>
            </form>
        </div>
    </div>
<?
