<?php

class AdminCategoriesController extends AdminCategoriesControllerCore {

    public function renderForm() {
        require_once(_PS_ROOT_DIR_ . '/modules/belvg_backgroundpages/belvg_backgroundpages.php'); //BELVG
        $this->initToolbar();
        $obj = $this->loadObject(TRUE);
        $id_shop = Context::getContext()->shop->id;
        $selected_cat = array((isset($obj->id_parent) && $obj->isParentCategoryAvailable($id_shop)) ? (int) $obj->id_parent : (int) Tools::getValue('id_parent', Category::getRootCategory()->id));
        $unidentified = new Group(Configuration::get('PS_UNIDENTIFIED_GROUP'));
        $guest = new Group(Configuration::get('PS_GUEST_GROUP'));
        $default = new Group(Configuration::get('PS_CUSTOMER_GROUP'));

        $unidentified_group_information = sprintf($this->l('%s - All people without a validated customer account.'), '<b>' . $unidentified->name[$this->context->language->id] . '</b>');
        $guest_group_information = sprintf($this->l('%s - Customer who placed an order with the Guest Checkout.'), '<b>' . $guest->name[$this->context->language->id] . '</b>');
        $default_group_information = sprintf($this->l('%s - All people who have created an account on this site.'), '<b>' . $default->name[$this->context->language->id] . '</b>');
        $root_category = Category::getRootCategory();
        $root_category = array('id_category' => $root_category->id_category, 'name' => $root_category->name);
        $this->fields_form = array(
            'tinymce' => TRUE,
            'legend' => array(
                'title' => $this->l('Category'),
                'image' => '../img/admin/tab-categories.gif'
            ),
            'input' => array(
                array(
                    'type' => 'text',
                    'label' => $this->l('Name:'),
                    'name' => 'name',
                    'lang' => TRUE,
                    'size' => 48,
                    'required' => TRUE,
                    'class' => 'copy2friendlyUrl',
                    'hint' => $this->l('Invalid characters:') . ' <>;=#{}',
                ),
                array(
                    'type' => 'radio',
                    'label' => $this->l('Displayed:'),
                    'name' => 'active',
                    'required' => FALSE,
                    'class' => 't',
                    'is_bool' => TRUE,
                    'values' => array(
                        array(
                            'id' => 'active_on',
                            'value' => 1,
                            'label' => $this->l('Enabled')
                        ),
                        array(
                            'id' => 'active_off',
                            'value' => 0,
                            'label' => $this->l('Disabled')
                        )
                    )
                ),
                array(
                    'type' => 'categories',
                    'label' => $this->l('Parent category:'),
                    'name' => 'id_parent',
                    'values' => array(
                        'trads' => array(
                            'Root' => $root_category,
                            'selected' => $this->l('selected'),
                            'Collapse All' => $this->l('Collapse All'),
                            'Expand All' => $this->l('Expand All')
                        ),
                        'selected_cat' => $selected_cat,
                        'input_name' => 'id_parent',
                        'use_radio' => TRUE,
                        'use_search' => FALSE,
                        'disabled_categories' => array(4),
                        'top_category' => Category::getTopCategory(),
                        'use_context' => TRUE,
                    )
                ),
                array(
                    'type' => 'radio',
                    'label' => $this->l('Root Category:'),
                    'name' => 'is_root_category',
                    'required' => FALSE,
                    'is_bool' => TRUE,
                    'class' => 't',
                    'values' => array(
                        array(
                            'id' => 'is_root_on',
                            'value' => 1,
                            'label' => $this->l('Yes')
                        ),
                        array(
                            'id' => 'is_root_off',
                            'value' => 0,
                            'label' => $this->l('No')
                        )
                    )
                ),
                array(
                    'type' => 'textarea',
                    'label' => $this->l('Description:'),
                    'name' => 'description',
                    'lang' => TRUE,
                    'rows' => 10,
                    'cols' => 100,
                    'hint' => $this->l('Invalid characters:') . ' <>;=#{}'
                ),
                array(
                    'type' => 'file',
                    'label' => $this->l('Image:'),
                    'name' => 'image',
                    'display_image' => TRUE,
                    'desc' => $this->l('Upload category logo from your computer')
                ),
                array(
                    'type' => 'text',
                    'label' => $this->l('Meta title:'),
                    'name' => 'meta_title',
                    'lang' => TRUE,
                    'hint' => $this->l('Forbidden characters:') . ' <>;=#{}'
                ),
                array(
                    'type' => 'text',
                    'label' => $this->l('Meta description:'),
                    'name' => 'meta_description',
                    'lang' => TRUE,
                    'hint' => $this->l('Forbidden characters:') . ' <>;=#{}'
                ),
                array(
                    'type' => 'tags',
                    'label' => $this->l('Meta keywords:'),
                    'name' => 'meta_keywords',
                    'lang' => TRUE,
                    'hint' => $this->l('Forbidden characters:') . ' <>;=#{}',
                    'desc' => $this->l('To add "tags" click in the field, write something, then press "Enter"')
                ),
                array(
                    'type' => 'text',
                    'label' => $this->l('Friendly URL:'),
                    'name' => 'link_rewrite',
                    'lang' => TRUE,
                    'required' => TRUE,
                    'hint' => $this->l('Only letters and the minus (-) character are allowed')
                ),
                array(
                    'type' => 'group',
                    'label' => $this->l('Group access:'),
                    'name' => 'groupBox',
                    'values' => Group::getGroups(Context::getContext()->language->id),
                    'info_introduction' => $this->l('You now have three default customer groups.'),
                    'unidentified' => $unidentified_group_information,
                    'guest' => $guest_group_information,
                    'customer' => $default_group_information,
                    'desc' => $this->l('Mark all customer groups you want to give access to this category')
                ),
                array(
                    'type' => 'background_file',
                    'label' => $this->l('Image:'),
                    'name' => 'background_image',
                    'display_image' => TRUE,
                    'desc' => $this->l('Upload category background')
                ),
            ),
            'submit' => array(
                'title' => $this->l('Save'),
                'class' => 'button'
            )
        );

        $this->tpl_form_vars['shared_category'] = Validate::isLoadedObject($obj) && $obj->hasMultishopEntries();

        if (Shop::isFeatureActive()) {
            $this->fields_form['input'][] = array(
                'type' => 'shop',
                'label' => $this->l('Shop association:'),
                'name' => 'checkBoxShopAsso',
            );
        }
        
        // remove category tree and radio button "is_root_category" if this category has the root category as parent category to avoid any conflict
        if ($this->_category->id_parent == Category::getTopCategory()->id && Tools::isSubmit('updatecategory')) {
            foreach ($this->fields_form['input'] as $k => $input) {
                if (in_array($input['name'], array('id_parent', 'is_root_category'))) {
                    unset($this->fields_form['input'][$k]);
                }
            }
        }

        if (Tools::isSubmit('add' . $this->table . 'root')) {
            unset($this->fields_form['input'][2], $this->fields_form['input'][3]);
        }

        if (!($obj = $this->loadObject(TRUE))) {
            return;
        }

        $image = ImageManager::thumbnail(_PS_CAT_IMG_DIR_ . '/' . $obj->id . '.jpg', $this->table . '_' . (int) $obj->id . '.' . $this->imageType, 350, $this->imageType, TRUE);

        $this->fields_value = array(
            'image' => $image ? $image : FALSE,
            'size' => $image ? filesize(_PS_CAT_IMG_DIR_ . '/' . $obj->id . '.jpg') / 1000 : FALSE,
        );

        // Added values of object Group
        $category_groups_ids = $obj->getGroups();

        $groups = Group::getGroups($this->context->language->id);
        // if empty $carrier_groups_ids : object creation : we set the default groups
        if (empty($category_groups_ids)) {
            $preselected = array(Configuration::get('PS_UNIDENTIFIED_GROUP'), Configuration::get('PS_GUEST_GROUP'), Configuration::get('PS_CUSTOMER_GROUP'));
            $category_groups_ids = array_merge($category_groups_ids, $preselected);
        }
        
        foreach ($groups as $group) {
            $this->fields_value['groupBox_' . $group['id_group']] = Tools::getValue('groupBox_' . $group['id_group'], (in_array($group['id_group'], $category_groups_ids)));
        }

        if (!$this->default_form_language) {
            $this->getLanguages();
        }

        if (Tools::getValue('submitFormAjax')) {
            $this->content .= $this->context->smarty->fetch('form_submit_ajax.tpl');
        }
        
        if ($this->fields_form && is_array($this->fields_form)) {
            if (!$this->multiple_fieldsets) {
                $this->fields_form = array(array('form' => $this->fields_form));
            }

            // For add a fields via an override of $fields_form, use $fields_form_override
            if (is_array($this->fields_form_override) && !empty($this->fields_form_override)) {
                $this->fields_form[0]['form']['input'][] = $this->fields_form_override;
            }

            $helper = new HelperForm($this);
            //BELVG --begin
            $helper->module = new Belvg_BackgroundPages();
            $img = $helper->module->getBackgroundImgByCategoryId((int) $obj->id);
            if (!empty($img)) {
                $background_image_url = ImageManager::thumbnail(_PS_MODULE_DIR_ . '/belvg_backgroundpages/patterns/categories/' . $obj->id . '/' . $img, $this->table . 'background_' . (int) $obj->id . '.' . $this->imageType, 350, $this->imageType, TRUE);
                $background_image_dir = BBP_PATTERNS_DIR . 'categories/' . (int) $obj->id . '/' . $img;
                //$background_image_url = BBP_PATTERNS_URL . 'categories/' . (int)$obj->id . '/' . $img;

                $this->fields_value = array_merge(
                        $this->fields_value, array(
                            'background_image' => $background_image_url,
                            'background_image_size' => $background_image_dir ? filesize($background_image_dir) / 1000 : FALSE
                        )
                );
            }
            
            //BELVG --end

            $this->setHelperDisplay($helper);
            $helper->fields_value = $this->getFieldsValue($this->object);
            $helper->tpl_vars = $this->tpl_form_vars;
            !is_null($this->base_tpl_form) ? $helper->base_tpl = $this->base_tpl_form : '';
            if ($this->tabAccess['view']) {
                if (Tools::getValue('back')) {
                    $helper->tpl_vars['back'] = Tools::safeOutput(Tools::getValue('back'));
                } else {
                    $helper->tpl_vars['back'] = Tools::safeOutput(Tools::getValue(self::$currentIndex . '&token=' . $this->token));
                }
            }

            $helper->override_folder = 'override/'; //BELVG
            $form = $helper->generateForm($this->fields_form);

            return $form;
        }
    }

    public function postProcess() {
        if (!in_array($this->display, array('edit', 'add'))) {
            $this->multishop_context_group = FALSE;
        }

        if (Tools::isSubmit('forcedeleteImage') || !empty($_FILES['image']['tmp_name'])) {
            $this->processForceDeleteImage();
            if (Tools::isSubmit('forcedeleteImage')) {
                Tools::redirectAdmin(self::$currentIndex . '&token=' . Tools::getAdminTokenLite('AdminCategories') . '&conf=7');
            }
        }

        $return = AdminController::postProcess();
        $id_category = Tools::getValue('id_category', (isset($return->id) ? $return->id : NULL));
        $dir = BBP_PATTERNS_DIR . 'categories/' . $id_category;

        //BELVG --begin
        $delete_current_img = Tools::getValue('deleteBackgroundImage');
        //$errors = array();
        /* delete image */
        if ($delete_current_img || !empty($_FILES['background_image']['tmp_name'])) {
            if (!file_exists($dir)) {
                mkdir($dir, 0777);
            }

            $this->deleteImgByCategoryId($id_category);
        }
            
        /* upload the image */
        if (isset($_FILES['background_image']) && isset($_FILES['background_image']['tmp_name']) && !empty($_FILES['background_image']['tmp_name'])) {
            $extension = substr($_FILES['background_image']['name'], strrpos($_FILES['background_image']['name'], "."));
            $new_name = $id_category;
            $unic_filename = preg_replace("/[^\p{L}\p{N}]/u", '-', pSQL($new_name)) . $extension;
            
            if ($error = ImageManager::validateUpload($_FILES['background_image'])) {
                $this->errors[] = Tools::displayError($error);
            } elseif (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($_FILES['background_image']['tmp_name'], $tmpName) || !$this->deleteImgByCategoryId($id_category)) {
                return FALSE;
            } elseif (!ImageManager::resize($tmpName, BBP_PATTERNS_DIR . 'categories/' . $id_category . '/' . $unic_filename)) {
                $this->errors[] = Tools::displayError('An error occurred during the image upload.');
            }
            
            if (!empty($this->errors)) {
                $this->redirect_after = '';
                return FALSE;
            }

            if (isset($tmpName)) {
                unlink($tmpName);
            }
        }
        
        //BELVG --end

        return $return;
    }

    private function deleteImgByCategoryId($id_category) {
        $dir = BBP_PATTERNS_DIR . 'categories/' . $id_category;
        $imgs = array_diff(scandir($dir), array('..', '.', 'products', 'categories', 'default'));
        $tmp_file = _PS_TMP_IMG_DIR_ . $this->table . 'background_' . (int) $id_category . '.' . $this->imageType;
        if (file_exists($tmp_file)) {
            unlink($tmp_file);
        }

        foreach ($imgs as $img) {
            if (!unlink($dir . '/' . $img)) {
                return FALSE;
            }
        }

        return TRUE;
    }

}

