<?php
/**
* 2024 Anvanto
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
*
*  @author    Anvanto <anvantoco@gmail.com>
*  @copyright 2024 Anvanto
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*/

if (!defined('_PS_VERSION_')) {
    exit;
}
 
require_once _PS_MODULE_DIR_ . 'an_sizeguide/classes/AnSizeGuide.php';

class AdminAnsizeguideWidgetsController extends ModuleAdminController
{
    protected $_module = null;
    
    protected $position_identifier = 'id_widget';
    protected $bulk_actions = [];

    public function __construct()
    {
        $this->bootstrap = true;
        $this->context = Context::getContext();
        $this->table = 'an_size_guide_widgets';
        $this->identifier = 'id_widget';
        $this->className = 'AnSizeGuideWidgets';
        $this->lang = true;
        

        
        $this->addRowAction('edit');
        $this->addRowAction('delete');
 
        $this->name = 'AdminAnsizeguideWidgetsController';
        
        parent::__construct();
        
        $this->fields_list = array(
            'id_widget' => array(
                'title' => $this->l('ID'), 
                'width' => 25,
                'search'  => false
            ),

            'sizeguide_title' => array(
                'title' => $this->l('Title'), 
                'search'  => false
            ),        
            
            'relation' => array(
                'title' => $this->l('Relation'), 
                'search'  => false,
                'width' => 150
            ),        
            
            'show_on' => array(
                'title' => $this->l('Show on'), 
                'search'  => false
            ),        
    
            'active' => array(
                'title' => $this->l('Status'),
                'width' => 40,
                'active' => 'update',
                'align' => 'center',
                'type' => 'bool',
                'search'  => false,
                'orderby' => false
            )
            
        );

        if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_ALL) {
            $this->_where .= ' AND a.' . $this->identifier . ' IN (
                SELECT sa.' . $this->identifier . '
                FROM `' . _DB_PREFIX_ . $this->table . '_shop` sa
                WHERE sa.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
            )';
        }
    }
    
    public function l($string, $class = null, $addslashes = false, $htmlentities = true)
    {
        return parent::l($string, pathinfo(__FILE__, PATHINFO_FILENAME), $addslashes, $htmlentities);
    }    
    
    public function renderList()
    {
        return parent::renderList() . $this->module->topPromo();
    } 
    
    public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
    {
        parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
        
        foreach ($this->_list as &$list) {
            switch ($list['relation']){
                case 1:
                    $list['relation'] = $this->trans('Categories', [], 'Admin.Global');
                    break;        

                case 2:
                    $list['relation'] = $this->trans('Products', [], 'Admin.Global');
                    break;   

                case 3:
                    $list['relation'] = $this->trans('Brands', [], 'Admin.Global');
                    break;    
                    
                default:
                    $list['relation'] = $this->l('all');
            }
        }

        foreach ($this->_list as &$list) {
            switch ($list['show_on']){
                case 1:
                    $list['show_on'] = $this->l('Product Page and Catalog');
                    break;            
                    
                default:
                    $list['show_on'] = $this->l('Product Page');
            }
        }
    }        

    public function setMedia($isNewTheme = false)
    {
        parent::setMedia($isNewTheme);
        $this->addJquery();
        $this->js_files[] = _MODULE_DIR_ . 'an_sizeguide/views/js/back.js';
        $this->js_files[] = _MODULE_DIR_ . 'an_sizeguide/views/js/anSearchProducts.js';
        $this->css_files[_MODULE_DIR_ . 'an_sizeguide/views/css/anSearchProducts.css'] = 'all';
    }   

    public function initPageHeaderToolbar()
    {
        if (empty($this->display)) {
            $this->page_header_toolbar_btn['add_field'] = array(
                'href' => self::$currentIndex . '&addan_size_guide_widgets&token=' . $this->token,
                'desc' => $this->trans('Add new', array(), 'Admin.Actions'),
                'icon' => 'process-icon-new',
            );
        }
        
        parent::initPageHeaderToolbar();
    }    
    
    public function initToolBarTitle()
    {
        $this->toolbar_title[] = $this->l('Size Guide');
    }

    public function initHeader()
    {
        parent::initHeader();

        $id_lang = $this->context->language->id;
        $link = $this->context->link;
        $tabs = &$this->context->smarty->tpl_vars['tabs']->value;
       
        foreach ($tabs as &$tab0) {
            if ($tab0['class_name'] == 'IMPROVE') {
                foreach ($tab0['sub_tabs'] as &$tab1) {
                    if ($tab1['class_name'] == 'AdminParentModulesSf') {
                        
                        foreach ($tab1['sub_tabs'] as &$tab2) {
                            if ($tab2['class_name'] == 'AdminAnsizeguideWidgets') {
                                $sub_tabs = &$tab2['sub_tabs'];

                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminAnsizeguideWidgets'));
                                $tab['current'] = true;
                                $tab['href'] = $link->getAdminLink('AdminAnsizeguideWidgets');
                                $tab['active'] = true;
                                $tab['name'] = $this->l('Size Guide');
                                $sub_tabs[] = $tab;

                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminAnsizeguideStatistics'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminAnsizeguideStatistics');
                                $tab['active'] = true;
                                $tab['name'] = $this->l('Statistics');
                                $sub_tabs[] = $tab;

                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminAnsizeguideSettings'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminAnsizeguideSettings');
                                $tab['active'] = true;
                                $sub_tabs[] = $tab;
                                
                                break;
                            }
                        }
                    //    break;
                    }
                }
              //  break;
            }
        }
    }  
    
    public function initContent()
    {
        $this->context->smarty->assign('current_tab_level', 3);
        return parent::initContent();
    }     

    public function renderForm()
    {
        $this->initToolbar();
         if (!$this->loadObject(true)) {
            return;
        } 
        
        $this->fields_form = array(
            'tinymce' => false,
            'legend' => ['title' => $this->l('Size Guide')],
            'input' => [],
            'buttons' => [
                [
                    'type' => 'submit',
                    'title' => $this->l('Save'),
                    'icon' => 'process-icon-save',
                    'class' => 'pull-right',
                    'name' => 'submit'.$this->table
                ],
                [
                    'type' => 'submit',
                    'title' => $this->l('Save and stay'),
                    'icon' => 'process-icon-save',
                    'class' => 'pull-right',
                    'name' => 'submit'.$this->table.'AndStay'
                ],
            ],
        );

        $this->fields_form['input'][] = array(
            'type' => 'switch',
            'name' => 'active',
            'label' => $this->l('Active'),
            'values' => array(
                array(
                    'id' => 'active_on',
                    'value' => 1,
                    'label' => $this->l('Enabled')
                ),
                array(
                    'id' => 'active_off',
                    'value' => 0,
                    'label' => $this->l('Disabled')
                )
            ),
            
        );        
        
        $this->fields_form['input'][] = array(
            'col' => 6,
            'type' => 'text',
            'name' => 'sizeguide_title',
            'label' => $this->l('Title'),    
            'lang' => true,
        );    

        $this->fields_form['input'][] = array(
            'type' => 'textarea',
            'class' => 'autoload_rte',
            'name' => 'sizeguide_content',
            'label' => $this->l('Content'),
            'lang' => true        
        );        
        
        
        $this->fields_form['input'][] = [
            'type' => 'html',
            'name' => 'line1',
            'html_content' => 'hr',    
        ];    


        $this->fields_form['input'][] = [
            'type' => 'radio',
            'label' => 'Relation',
            'name' => 'relation',
            'class' => 'an-bi-type-view',
            'values' => [
                [
                    'id' => 'relation_all',
                    'value' => '0',
                    'label' => $this->l('All'),
                ], 
                [
                    'id' => 'relation_categories',
                    'value' => '1',
                    'label' => $this->l('Categories')
                ], 
                [
                    'id' => 'relation_products',
                    'value' => '2',
                    'label' => $this->l('Products')
                ],
                [
                    'id' => 'relation_brands',
                    'value' => '3',
                    'label' => $this->l('Brands')
                ]
            ]
        ];

        $this->fields_form['input'][] = array(
            'type' => 'anSearchProductsList',
            'ignore' => true,
            'name' => 'productIds[]',
            'class' => 'js-an_sizeguide_products js-an_productfields-searchProducts-components',
            'classSarchInput' => 'js-an_productfields-search-input',
            'label' => '',
            'col' => 6,
            'searchProdutsController' => $this->context->link->getAdminLink('AdminAnsizeguideAjax', true, [], ['ajax'=>1, 'action' =>'searchProducts']),
            'form_group_class' => 'js-sg-searchProducts-group'
        );

        $this->fields_form['input'][] = array(
            'type' => 'text',
            'anSearchProductsInput' => true,
            'ignore' => true,
            'label' => $this->trans('Products', [], 'Admin.Global'),
            'name' => 'products_input',
            'size' => 50,
            'maxlength' => 50,
            'col' => 6,
            'placeholder' => $this->l('Search and add a product'),
            'desc' => $this->l('Search for a product by typing the first letters of his name'),
            'class' => 'js-an_productfields-search-input',
            'form_group_class' => 'js-sg-searchProducts-group'
        );
        $this->fields_value['productIds[]'] = $this->getProducsByIdWidget(Tools::getValue('id_widget'));
          
        $this->fields_form['input'][] = [
            'type'  => 'categories',
            'label' => $this->l('Categories'),
            'name'  => 'id_categories',
            'class' => 'js-sz-block-categories',
            'form_group_class' => 'js-bi-categories-group',    
            'tree'  => [
                'id' => 'id_root_category',
                'use_checkbox' => true,
                'selected_categories' => $this->getRelationCategories(Tools::getValue('id_widget'))
            ]
        ];    

        $brandsOriginal = Manufacturer::getManufacturers();
        $brands = [];
        foreach ($brandsOriginal as $brand){
            $brands[$brand['id_manufacturer']] = $brand;
        }

        $this->fields_form['input'][] = [
            'type' => 'an_checkbox',
            'label' => $this->trans('Brands', [], 'Admin.Global'),                        
            'name' => 'brandsCheckbox',
            'values' => [
                'query' => $brands,
                'id' => 'id_manufacturer',
                'name' => 'name'
            ],
            'form_group_class' => 'js-sg-searchProducts-brands'
        ]; 
        $this->fields_value['brandsCheckbox'] = AnSizeGuideWidgets::getRelationsByIdWidget(Tools::getValue('id_widget'), 3, true);


        $this->fields_form['input'][] = [
            'type' => 'html',
            'name' => 'line1',
            'html_content' => 'hr',    
        ];    


        $this->fields_form['input'][] = [
            'type' => 'radio',
            'label' => 'Show on',
            'name' => 'show_on',
            'values' => [
                [
                    'id' => 'show_on_product_page',
                    'value' => '0',
                    'label' => $this->l('Product Page'),
                ], 
                [
                    'id' => 'show_on_produt_page_catalog',
                    'value' => '1',
                    'label' => $this->l('Product Page & catalog')
                ]
            ]
        ];        
        
    
        if (Shop::isFeatureActive()) {
            $this->fields_form['input'][] = [
                'required' => true,
                'type' => 'shop',
                'label' => $this->l('Shop association'),
                'name' => 'checkBoxShopAsso',
            ];
        }        
        
        return parent::renderForm() . $this->module->topPromo();
    }
  
    
    public function processSave()
    {
        
        if (!empty($this->errors)) {
            // if we have errors, we stay on the form instead of going back to the list
            $this->display = 'edit';
            return false;
        }

		if (_PS_MODE_DEMO_) {
			$this->errors[] = $this->module->demoModeMessage;
			return false;
		}	

        $object = parent::processSave();
        
        if (isset($object->id) && $object->id) {
            
            switch (Tools::getValue('relation')){
                
                case 1:
                    AnSizeGuideWidgets::updateCategoriesProducts(Tools::getValue('id_categories'), $object->id, 1);
                    break;
                    
                case 2:
                    AnSizeGuideWidgets::updateCategoriesProducts(Tools::getValue('productIds'), $object->id, 2);
                    break;    

                case 3:
                    AnSizeGuideWidgets::updateCategoriesProducts(Tools::getValue('brandsCheckbox'), $object->id, 3);
                    break;    

                default:
                AnSizeGuideWidgets::updateCategoriesProducts([], $object->id, 0);
            }
        }        
        
        if (Tools::getIsset('submit'.$this->table.'AndStay')) {
            $this->redirect_after = $this->context->link->getAdminLink($this->controller_name).'&conf=4&updatean_size_guide_widgets&token='.$this->token.'&id_widget='.$object->id;
        }
        
        return $object;
    }
    
    public function getRelationCategories($widget = 0)
    {
        if (!$widget){
            return [];
        }
        
        $sql = '
        SELECT `id_type`
        FROM `' . _DB_PREFIX_ . 'an_size_guide_widgets_relations` awl        
        WHERE awl.`widget` = ' . (int) $widget . ' AND awl.`type`="1"  ';
        
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql, true, false);
        
        $cats = [];
        if ($result) {
            foreach ($result as $item){
                $cats[] = $item['id_type'];
            }
        }
        
        return $cats;        
    }
        
    public function getProducsByIdWidget($widget = 0)
    {
        if (!$widget){
            return [];
        }
        
        $sql = '
        SELECT  *, p.*
        FROM `' . _DB_PREFIX_ . 'an_size_guide_widgets_relations` awl
        
        LEFT JOIN `' . _DB_PREFIX_ . 'product` p
            ON (p.`id_product` = awl.`id_type`)
        
        LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl
            ON (p.`id_product` = pl.`id_product`
            AND pl.`id_lang` = ' . (int) Context::getContext()->language->id . Shop::addSqlRestrictionOnLang('pl') . ')        
        
        WHERE awl.`widget` = ' . (int) $widget . '  AND awl.`type`="2" ';
        
        
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql, true, false);

		$products = Product::getProductsProperties(Context::getContext()->language->id, $result);

        foreach ($products as &$product){

            $coverPhoto = '';
            if (isset($product['cover_image_id'])){
                $coverPhoto = Context::getContext()->link->getImageLink(
                    $product['link_rewrite'],
                    $product['cover_image_id'], 
                    ImageType::getFormattedName('cart')
                );
            }
            
            $product['cover'] = $coverPhoto;
        }

        return $products;
    }

    public function processDelete()
    {
        if (_PS_MODE_DEMO_) {
			$this->errors[] = $this->module->demoModeMessage;
			return false;
		}             

        $object = parent::processDelete();
        
        if (isset($object->id) && $object->id) {
            Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute('DELETE FROM `'._DB_PREFIX_.'an_size_guide_widgets_relations` WHERE `widget`='.(int) $object->id.' ');
            Db::getInstance(_PS_USE_SQL_SLAVE_)->execute('DELETE FROM `' . _DB_PREFIX_ . 'an_size_guide_widgets_views`  WHERE `id_widget` = '.(int) $object->id.'');
        }
        
        return $object;
    }    
    
    
    
    protected function updateAssoShop($id_object)
    {
        if (!Shop::isFeatureActive()) {
            return;
        }

        $assos_data = $this->getSelectedAssoShop($this->table, $id_object);

        $exclude_ids = $assos_data;

        foreach (Db::getInstance()->executeS('SELECT id_shop FROM ' . _DB_PREFIX_ . 'shop') as $row) {
            if (!$this->context->employee->hasAuthOnShop($row['id_shop'])) {
                $exclude_ids[] = $row['id_shop'];
            }
        }

        Db::getInstance()->delete($this->table . '_shop', '`' . $this->identifier . '` = ' . (int) $id_object . ($exclude_ids ? ' AND id_shop NOT IN (' . implode(', ', $exclude_ids) . ')' : ''));

        $insert = array();

        foreach ($assos_data as $id_shop) {
            $insert[] = array(
                $this->identifier => $id_object,
                'id_shop' => (int) $id_shop,
            );
        }

        return Db::getInstance()->insert($this->table . '_shop', $insert, false, true, Db::INSERT_IGNORE);
    }

    protected function getSelectedAssoShop($table)
    {
        if (!Shop::isFeatureActive()) {
            return array();
        }

        $shops = Shop::getShops(true, null, true);

        if (count($shops) == 1 && isset($shops[0])) {
            return array($shops[0], 'shop');
        }

        $assos = array();

        if (Tools::isSubmit('checkBoxShopAsso_' . $table)) {
            foreach (Tools::getValue('checkBoxShopAsso_' . $table) as $id_shop => $value) {
                $assos[] = (int) $id_shop;
            }
        } else if (Shop::getTotalShops(false) == 1) {
            // if we do not have the checkBox multishop, we can have an admin with only one shop and being in multishop
            $assos[] = (int) Shop::getContextShopID();
        }

        return $assos;
    }    
}
