<?php

namespace Mnv\Admin\Controllers;

if (!defined('MNV_CMS')) {
    die('Hacking attempt!');
}

use Mnv\Core\AdminMnv;
use Mnv\Core\Helpers;

use Mnv\Models\Brands;
use Mnv\Models\Countries;
use Mnv\Models\Shop\Colors;
use Mnv\Models\Shop\Options;
use Mnv\Models\Variants;
use Mnv\Models\Shop\Product;
use Mnv\Models\Exceptions\NotUpdateContentException;
use Mnv\Models\Exceptions\NotInsertContentException;

/**
 * Class ProductAdmin
 * @package Mnv\Admin\Controllers
 */
class ProductAdmin extends AdminMnv
{

    public int $sectionId;
    public int $featureId;

    public function fetch()
    {
        global $SECTIONS;

        $content = new Product($this->request);
        $optionClass = new Options($this->request);

//        $productVariant = new Variants();
        $features = array();

        $this->smarty->assign('activeItem', 'products');
        $this->smarty->assign('title', lang('products:title'));
        /** generate url for type content */
        $this->smarty->assign('generate_url', $this->adminUrl . '/' . $this->module . 's');
        /** statuses */
        $statuses = lang('general:statuses');
        array_shift($statuses);
        array_pop($statuses);
        $this->smarty->assign('statuses', $statuses);
        /** страны */
        $this->smarty->assign('countryList', Countries::getSelectCountries());

        $this->smarty->assign('subtracts', $content->subtracts);
        $this->smarty->assign('specials', $content->specials);
        $this->smarty->assign('stock_status', $content->getStockStatuses());

        /** получить двигатели данной комплектации */
        $option = $optionClass->getOptions();
        $this->smarty->assign('option', $option);

        /** получение ID для удаления / изменение статуса / удаление и обновление основной картинки */
        $this->sectionId    = (int) $this->request->get('sectionId', '');
        $this->featureId    = (int) $this->request->get('featureId', '');

        /** варианты товара */
//        $variants = $this->request->get('variants', '');
        /** свойства товара */
        $feature_values         = $this->request->get('feature_values', '');
        $new_features_names       = $this->request->get('new_features_names', '');
        $new_features_values      = $this->request->get('new_features_values', '');
        /** опции */
        $product_option      = $this->request->get('product_option', '');

//        print_r($feature_values);

        /** работа с галереей */
        $image        = $this->request->get('image', '');
        $gallery      = $this->request->get('gallery', '');
        $imageIds     = $this->request->get('imageIds', '');
        $imageId      = (int) $this->request->get('imageId', '');
        $picture      = $this->request->get('picture', '');

        $colors   = $this->request->get('colors', '');


        $sections = Helpers::getSectionContent(0, 'products');
        if (count($sections) < 2) $this->errors['no_sections'] = true;
        $this->smarty->assign('sections', $sections);


        /** action добавление/редактирование */
        if ($this->action == 'add' || $this->action == 'edit') {

            $content->edit()->getFiles()->gettingInfoAboutUsers();

        }
        /** action сохранение */
        else if ($this->action == 'save' || $this->action == 'apply') {

            /** проверка полей */
            if (empty($content->data['title'])) $this->errors['title'] = true;
            /** проверка доступных разделов */
            if (empty($content->data['sectionId']) || empty($sections[$content->data['sectionId']])) $this->errors['sectionId'] = true;

            /** проверка fileName на совпадение / если пустой то fileName пропишется от последнего ID из таблицы + 1 */
            if ($fileName = $content->checkFileName($content->data['fileName'])) {
                if ($fileName == $content->data['fileName']) {
                    $this->errors['fileNameExists'] = true;
                } else {
                    $content->data['fileName'] = $fileName;
                }
            }

            /** основная картинка */
            $images['fileId'] = !empty($image) ? $image['fileId'] : null;

            /** включить / отключить галерею у данного контента */
            $content->data['enableGallery'] = isset($content->data['enableGallery']) ? 1 : 0;
            $images['gallery'] = !empty($gallery) ? $gallery : null;

            /** изменяем статус товара на складе */
//            if (!is_numeric($content->data['quantity'])) $this->errors['quantity'] = true;
//            if ($content->data['quantity'] == 0) {
//                if ($content->data['stock_status_id'] == 1) {
//                    $content->data['stock_status_id']  = 2;
//                }
//            } else {
//                $content->data['stock_status_id'] = 1;
//            }


            /** если ошибок нет то можно продолжить дальше */
            if (empty($this->errors)) {
                /** построение url из полученного url раздела/fileName статьи . расширение файла из настроек  (html / htm)  */
                $content->data['url'] = $SECTIONS[$content->data['sectionId']]['path'] . '/' . $content->data['fileName'].'.'.$this->config['file_extension'];

                try {
                    $content->prepare($content->data, $this->manager['userId']);

                    /** опции */
//                    $content->setOptions($product_option, $content->data['quantity']);

                    $content->setProductRelated();

                    if (!empty($images['fileId'])) $content->addMainImage($content->id, $images);
                    if (!empty($images['gallery'])) $content->addGalleryAndDocuments($content->id, $images, 'gallery');

                    /** Характеристики продукта */

                    /** Удалим все характеристики из продукта */
                    $productOptions = $content->getProductFeatureValues($content->id);
                    if (!empty($productOptions)) {
                        collect($productOptions)->each(function ($item) use ($content) {
                            $content->deleteFeatureValue($content->id, $item['featureId']);
                        });
                    }
                    /** получение свойств для продукта */
                    if (is_array($feature_values)) {
                        $sectionFeatureIds = $content->getAllProductFeatureIds($content->data['sectionId']);
                        collect($feature_values)->each(function ($feature_value, int $feature_value_id) use ($content, $sectionFeatureIds) {
                            if (in_array($feature_value_id, $sectionFeatureIds)) {
                                $content->updateFeatureValueNew(array('productId' => $content->id, 'featureId' => $feature_value_id, 'value' => $feature_value['value']));
                            }
                        });
                    }

                    /** Новые характеристики */
                    if (is_array($new_features_names) && is_array($new_features_values)) {
                        foreach ($new_features_names as $i => $name) {
                            $value = trim($new_features_values[$i]);
                            if (!empty($name)) {
                                $featureId = $content->existsFeature(trim($name));
                                if (empty($featureId)) {
                                    $featureId = $content->addFeature(['sectionIds' => json_encode([$content->data['sectionId']], JSON_THROW_ON_ERROR), 'name' => trim($name)]);
                                }
                                $content->updateFeatureValue($content->id, $featureId, $value);
                            }
                        }
                        /** возвращаем характеристики продукта */
                        $feature_values = $content->getProductFeatureValues($content->id);
                        $this->smarty->assign('feature_values', $feature_values);
                    }


                    $this->messages['saved'] = true;

                } catch (NotInsertContentException | NotUpdateContentException $e) {
                    $this->errors['not_saved'] = true;
                }
            }

            $content->edit()->getFiles()->gettingInfoAboutUsers();

            if (empty($this->errors) && $this->action == 'save') {
                redirect($this->adminUrl . "/" . $this->module . "s?" . $this->buildQueryString(['page' => $this->page]));
            }

        }
//        else if ($this->action == 'option_autocomplete') {
//            $optionClass->filter = array(
//                'query' =>  $this->request->get('filter_name'),
//                'start'       => 0,
//                'limit'       => 5
//            );
//
////            print_r($optionClass->filter);
//
//
//            $option = $optionClass->getSelectOptions();
//
//
//            response()->json($option, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
//            exit();
//        }

        else if ($this->action == 'related_autocomplete') {
            $content->filter = array(
                'query' =>  $this->request->get('filter_name'),
                'start'       => 0,
                'limit'       => 5
            );

            $option = $content->getSelectProducts();

//            print_r($option);

            response()->json($option, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }
        else if ($this->action == 'deleteImage') {
            $result = $content->deleteFile($imageId)
                ? array('status' => 200, 'message' => lang('javascript:deletingImage'), 'type' => 'success')
                : array('status' => 500, 'message' => lang('javascript:deletingImageError'), 'type' => 'error');

            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }

        else if ($this->action == 'editPictureInfo') {

            $response = $content->editPictureInfo($imageId, $picture)
                ? array('status' => 200, 'title' => $content->result['title'], 'alias' => $content->result['alias'], 'description' => $content->result['description'], 'link' => $content->result['link'], 'position' => $content->result['position'])
                : array('status' => 400, 'title' => '', 'alias' => '', 'description' => '', 'link' => '', 'position' => '');
            
            response()->json($response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
        }

        else if ($this->action == 'sortPictures') {

            $i = 0;
            foreach ($imageIds as  $imageId) {
                $i++;
                $content->sortPictures($imageId, $i);
            }

            response()->json(array('status' => 200, 'type' => 'success'), \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }

        else if ($this->action == 'deletePicture') {
            $result = $content->deleteFile($imageId)
                ? array('status' => 200, 'message' => lang('javascript:deletingImage'), 'type' => 'success')
                : array('status' => 500, 'message' => lang('javascript:deletingImageError'), 'type' => 'error');

            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }
        /** получить свойства товара от выбранного раздела */
        else if ($this->action == 'features') {
            $features = $content->getAllProductFeatures($content->id ?? null, $this->sectionId);
            if (!empty($content->id)) $featureOptions = $content->getProductFeatureValues($content->id);
            $features = collect($features)->map(function ($item) use (&$featureOptions) {
                $item['value'] = isset($featureOptions[$item['id']]) ? $featureOptions[$item['id']]['value'] : '';

                return $item;
            })->all();

            response()->json($features, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }
//        /** удаление картинки из галереи */
//        else if ($this->action == 'deleteColors') {
//
//            $result = $content->deleteColor($imageId) ? array('status' => 200, 'message' => 'Цвет удален', 'type' => 'success') :  array('status' => 400, 'message' => 'Цвет не удален, обновить страницу и повторите удаление', 'type' => 'error');
//
//            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
//            exit();
//        }
//        /** сортировка цвета (салона и кузова) */
//        else if ($this->action == 'sortByColors') {
//            $i = 0;
//            foreach ($imageIds as  $imageId) {
//                $i++;
//                $content->sortByColors($imageId, $i);
//            }
//
//            response()->json(array('status' => 200, 'type' => 'success'), \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
//            exit();
//        }


        // получить свойства товара от выбранного раздела
        else if ($this->action == 'featureId') {

            $featureValue = $content->getProductFeatureValue($this->featureId);
            response()->json($featureValue, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
        }


        /** вывод свойств продукта `variants` (название свойств) */
        if (isset($content->data['sectionId'])) {
            $features = $content->getAllProductFeatures($content->id, $content->data['sectionId']);
        }
        $this->smarty->assign('features', $features);

        /** вывод характеристик продукта `options` (название характеристик, значение характеристик ) */
        $this->smarty->assign('feature_values', $content->getProductFeatureValues($content->id ?? 0));

        /** связанные товары */
        $this->smarty->assign('product_relateds', $content->getProductRelated());

//        print_r($product->content);


//        if (!empty($content->id)) {
//            $content->data['product_options'] = $content->getProductOptions($content->id);
//            $content->data['option_values'] = array();
//
//            foreach ($content->data['product_options'] as $product_option) {
//                if ($product_option['type'] == 'select' || $product_option['type'] == 'radio' || $product_option['type'] == 'checkbox' || $product_option['type'] == 'image') {
//                    if (!isset($content->data['option_values'][$product_option['option_id']])) {
//                        $content->data['option_values'][$product_option['option_id']] = $content->getOptionValues($product_option['option_id']);
//                    }
//                }
//            }
//        }

        $this->smarty->assign('product', $content->data);

        if (!empty($this->errors)) {
            $this->smarty->assign('errors', $this->errors);
        }
        if (!empty($this->messages)) {
            $this->smarty->assign('messages', $this->messages);
        }

        if ($this->permissions('products')) {
            return $this->smarty->fetch('views/shop/product.tpl');
        }

        $this->smarty->assign('title', 'Access Denied');
        return $this->smarty->fetch('accessIsDenied.tpl');
    }



}