<?php
/**
 * 2007-2022 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <contact@prestashop.com>
 * @copyright 2007-2022 PrestaShop SA
 * @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */

require_once dirname(__FILE__) . '/AdminEtsHDFormController.php';

class AdminEtsHDStaffsController extends AdminEtsHDFormController
{
    /**
     * @var Ets_helpdesk
     */
    public $module;

    /**
     * @var HDStaff
     */
    public $object;

    public function __construct()
    {
        $this->bootstrap = true;
        $this->table = 'ets_hd_staff';
        $this->list_id = 'ets_hd_staff';
        $this->identifier = 'id_ets_hd_staff';
        $this->className = 'HDStaff';
        $this->show_form_cancel_button = false;
        $this->list_no_link = true;
        $this->toolbar_btn = array();
        $this->show_toolbar = false;
        $this->list_simple_header = false;

        parent::__construct();

        $this->addRowAction('editstaff');

        $this->_select = '
            e.id_employee
            , if(a.nick_name="","--",a.nick_name) as nick_name
            , e.email
            , CONCAT(IFNULL(a.id_ets_hd_staff, 0), "-", e.id_employee) as `id_ets_hd_staff`
            , CONCAT (e.firstname, " ", e.lastname) `employee`
            , IF(e.id_employee is NULl OR e.id_employee <= 0, 0, a.active) active
            , pl.name as `profile`
            , IF(e.id_profile = ' . (int)_PS_ADMIN_PROFILE_ . ', 1, a.active) as active
            , if(a.signature="","--",a.signature) as signature
        ';
        $this->_join = '
            RIGHT JOIN `' . _DB_PREFIX_ . 'employee` e ON (e.id_employee = a.id_employee)
            LEFT JOIN `' . _DB_PREFIX_ . 'profile_lang` pl ON (pl.id_profile = e.id_profile AND pl.id_lang=' . (int)$this->context->language->id . ')
        ';
        $this->_where = 'AND a.id_customer is NULL OR a.id_customer <= 0';
        //$this->_group = ' GROUP BY e.id_employee';
        $this->_orderBy = 'e.id_employee';

        $this->fields_list = array(
            'id_employee' => array(
                'title' => $this->l('ID'),
                'type' => 'int',
                'filter_key' => 'e!id_employee',
                'class' => 'fixed-width-sm center hd_employee_id',
            ),
            'employee' => array(
                'title' => $this->l('Employee'),
                'type' => 'text',
                'align' => 'left',
                'filter_key' => 'employee',
                'havingFilter' => true,
            ),
            'nick_name' => array(
                'title' => $this->l('Nick name'),
                'type' => 'text',
                'align' => 'center',
            ),
            'profile' => array(
                'title' => $this->l('Profile'),
                'type' => 'text',
                'align' => 'left',
                'filter_key' => 'profile',
                'class' => 'fixed-width-lg',
                'havingFilter' => true,
            ),
            'email' => array(
                'title' => $this->l('Email'),
                'type' => 'text',
                'filter_key' => 'email',
                'class' => 'col_email',
                'havingFilter' => true,
            ),
            'avatar' => array(
                'title' => $this->l('Avatar'),
                'type' => 'text',
                'search' => false,
                'orderby' => false,
                'align' => 'center',
                'folder' => HDDefines::$avatar_upload,
                'callback' => 'displayAvatar',
            ),
            'signature' => array(
                'title' => $this->l('Signature'),
                'type' => 'text',
                'search' => false,
                'orderby' => false,
            ),
            'active' => array(
                'title' => $this->l('Status'),
                'type' => 'bool',
                'active' => 'status',
                'filter_key' => 'active',
                'class' => 'fixed-width-lg',
                'align' => 'center',
                'havingFilter' => true,
            )
        );
    }

    /**
     * Override button edit
     * @param $token
     * @param $id
     * @return false|string
     */
    public function displayEditStaffLink($token, $id)
    {
        if (!isset(self::$cache_lang['editstaff'])) {
            self::$cache_lang['editstaff'] = $this->l('Edit');
        }

        $this->context->smarty->assign(array(
            'href' => self::$currentIndex .
                '&' . $this->identifier . '=' . $id .
                '&update' . $this->table . '&token=' . ($token != null ? $token : $this->token),
            'action' => self::$cache_lang['editstaff'],
        ));

        return $this->createTemplate('helpers/list/list_action_edit.tpl')->fetch();
    }

    static $configs_field = array();
    static $options_field = array();

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

        self::$options_field = array(
            'id_customer' => array(
                'type' => 'text',
                'name' => 'id_customer',
                'label' => $this->l('Search customer'),
                'autocomplete' => true,
                'placeholder' => $this->l('Search customer by id, firstname, lastname, email.'),
                'col' => 9,
            )
        );

        $this->fields_options = array(
            'title' => $this->l('Staffs'),
            'fields' => self::$options_field,
        );

        self::$configs_field = array(
            'id_ets_hd_staff' => array(
                'name' => 'id_ets_hd_staff',
                'label' => $this->l('ID'),
                'type' => 'hidden',
            ),
            'id_employee' => array(
                'name' => 'id_employee',
                'label' => $this->l('Employee ID'),
                'type' => 'hidden',
            ),
            'email' => array(
                'name' => 'email',
                'label' => $this->l('Email'),
                'type' => 'text',
                'readonly' => true,
                'validate' => 'isEmail'
            ),
            'nick_name' => array(
                'name' => 'nick_name',
                'label' => $this->l('Nick name'),
                'type' => 'text',
                'validate' => 'isCleanHtml',
                'desc' => $this->l('If you do not enter a specific nick name, employee name will become nick name'),
            ),
            'avatar' => array(
                'name' => 'avatar',
                'label' => $this->l('Avatar'),
                'type' => 'file',
                'folder' => HDDefines::$avatar_upload,
                'base_uri' => HDDefines::$avatar_base_uri,
                'reader' => true,
            ),
            'signature' => array(
                'name' => 'signature',
                'label' => $this->l('Signature'),
                'type' => 'textarea',
                'validate' => 'isCleanHtml'
            ),
            'active' => array(
                'name' => 'active',
                'label' => $this->l('Enabled'),
                'type' => 'switch',
                'values' => array(
                    array(
                        'id' => 'active_on',
                        'value' => 1,
                        'label' => $this->l('Enabled'),
                    ),
                    array(
                        'id' => 'active_off',
                        'value' => 0,
                        'label' => $this->l('Disabled'),
                    ),
                ),
            )
        );
        if(Tools::isSubmit('updateets_hd_staff'))
        {
            if(($ids = array_map('intval',explode('-',Tools::getValue('id_ets_hd_staff')))) && isset($ids[0]) && ($id_ets_hd_staff = (int)$ids[0]) )
            {
                $staff = new HDStaff($id_ets_hd_staff);
                if($staff->nick_name)
                    $staff_name = $staff->nick_name;
                elseif($staff->id_employee)
                {
                    $employee = new Employee($staff->id_employee);
                    $staff_name = $employee->firstname.' '.$employee->lastname;
                }
                elseif($staff->id_customer)
                {
                    $customer = new Customer($staff->id_customer);
                    $staff_name = $employee->firstname.' '.$customer->lastname;
                }
            }
        }
        $this->fields_form = array(
            'legend' => array(
                'title' => Tools::isSubmit('updateets_hd_staff') && isset($id_ets_hd_staff) && $id_ets_hd_staff ? $this->l('Edit').' - '.$staff_name : $this->l('Add'),
            ),
            'submit' => array(
                'title' => $this->l('Save'),
            ),
            'input' => self::$configs_field,
            'buttons' => array(
                'back' => array(
                    'href' => self::$currentIndex . '&token=' . $this->token,
                    'title' => $this->l('Cancel'),
                    'icon' => 'process-icon-cancel',
                    'class' => 'ets_hd_staff_cancel'
                ),
            )
        );
    }

    public function initContent()
    {
        if (!$this->viewAccess()) {
            $this->errors[] = $this->l('You do not have permission to view this.');

            return '';
        }
        $form = '';
        if ($this->display == 'edit' || $this->display == 'add') {
            if (!$this->loadObject(true)) {
                return '';
            }
            $form = $this->renderForm();
        } elseif (!$this->ajax) {
            $form = $this->renderList();
        }
        $current_staff = Tools::getValue('current_staff');
        if (trim($current_staff) == '' ||
            !Validate::isCleanHtml($current_staff)
        ) {
            $current_staff = 'employee';
        }
        $this->context->smarty->assign(array(
            'menu' => $this->initMenus(true),
            'staffs' => array(
                'employee' => $form,
                'customer' => $this->renderOptions(true),
            ),
            'tabs_staff' => array(
                'employee' => $this->l('Employee'),
                'customer' => $this->l('Customer')
            ),
            'current_staff' => $current_staff
        ));

        return $this->createTemplate('content.tpl')->fetch();
    }

    public function renderForm()
    {
        if ($this->loadObject()) {
            $employee = new Employee($this->object->id_employee);
            if ((int)$employee->id_profile === (int)_PS_ADMIN_PROFILE_) {
                unset($this->fields_form['input']['active']);
            }
        }
        return parent::renderForm();
    }

    public function getConfigFieldsValue($submit_action)
    {
        $fields = array();
        if (!Tools::isSubmit($submit_action)) {
            $customers = HDStaff::getCustomers(true);
            $ids_customer = array();
            if (is_array($customers) && count($customers) > 0) {
                foreach ($customers as $customer) {
                    $ids_customer[] = (int)$customer['id_customer'];
                }
            }
            $fields['id_customer'] = count($ids_customer) > 0 ? implode(',', $ids_customer) : '';
        } else {
            $fields = parent::getConfigFieldsValue($submit_action);
        }

        return $fields;
    }

    public function renderOptions($ret = false)
    {
        $customers = HDStaff::getCustomers();
        $this->tpl_option_vars['customers'] = $customers;

        return parent::renderOptions($ret);
    }

    public function ajaxProcessPostConfig()
    {
        $customerIds = Tools::getValue('id_customer');
        $res = false;
        if (trim($customerIds) !== ''
            && is_array(($customers_array_id = explode(',', $customerIds)))
            && Validate::isArrayWithIds($customers_array_id)
        ) {
            try {
                $res = HDStaff::addCustomer($customers_array_id);
                if (!$res) {
                    $this->errors[] = $this->l('Add customers to staff error.');
                }
            } catch (Exception $exception) {
                $this->errors[] = $exception->getMessage();
            }
        } else {
            $res = HDStaff::deleteAllCustomer();
        }
        $this->ajaxJson(array(
            'errors' => $res ? false : implode(PHP_EOL, $this->errors),
            'msg' => $res ? $this->l('Saved') : ''
        ));
    }

    public function displayAvatar($avatar)
    {
        if (trim($avatar) !== '') {
            $this->context->smarty->assign(array(
                'avatar' => HDDefines::$avatar_base_uri . $avatar,
            ));

            return $this->createTemplate('avatar.tpl')->fetch();
        }
    }

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

        if (Tools::isSubmit('update' . $this->table)) {
            if (!(int)Tools::getValue($this->identifier)) {
                $this->display = 'add';
            } else
                $this->display = 'edit';
        }
    }

    public $id_ets_hd_staff = 0;
    public $id_employee = 0;

    public function processAdd()
    {
        $id = Tools::getValue($this->identifier);
        $this->module->validateFields(self::$configs_field, $id);

        if (!count($this->errors)) {
            $this->object = new $this->className($id);
            $this->copyFromPost($this->object, $this->table);
            $employee = new Employee($this->object->id_employee);
            if ($employee->id_profile == _PS_ADMIN_PROFILE_) {
                $this->object->active = 1;
            }
            if (!$this->object->save()) {
                $file_name = HDDefines::$avatar_upload . $this->object->avatar;
                if (!@file_exists($file_name))
                    @unlink($file_name);
                $this->errors[] = sprintf($this->l('An error occurred while adding this image: %s'), Tools::stripslashes($this->object->avatar));
            } elseif (@file_exists($this->object->avatar_old)) {
                @unlink($this->object->avatar_old);
            }
        }
    }

    /**
     * @param HDStaff $object
     * @param string $table
     * @throws PrestaShopException
     */
    public function copyFromPost(&$object, $table)
    {
        if (is_array(self::$configs_field) && count(self::$configs_field) > 0 && $table !== '') {
            foreach (self::$configs_field as $key => $config) {
                if ($config['type'] == 'switch') {
                    $object->$key = (int)Tools::getValue($key) ? 1 : 0;
                } elseif ($config['type'] !== 'file') {
                    if (isset($config['validate']) && $config['validate'] == 'isUnsignedInt' || $config['type'] == 'hidden') {
                        $object->$key = (int)Tools::getValue($key);
                    } else {
                        $object->$key = trim(Tools::getValue($key));
                    }
                } else {
                    $upload_folder = isset($config['folder']) && trim($config['folder']) !== '' ? $config['folder'] : HDDefines::$avatar_upload;
                    $image = '';
                    if (isset($_FILES[$key]) && !empty($_FILES[$key]['name'])) {
                        $type = Tools::strtolower(Tools::substr(strrchr($_FILES[$key]['name'], '.'), 1));
                        $image = Tools::strtolower(Tools::passwdGen(20)) . '.' . $type;
                        $file_name = $upload_folder . $image;
                        if (@file_exists($file_name)) {
                            $this->errors[] = $this->l('File name already exists. Try to rename the file and upload again');
                        } else {
                            $image_size = @getimagesize($_FILES[$key]['tmp_name']);
                            if (isset($_FILES[$key]) && !empty($_FILES[$key]['tmp_name']) && !empty($image_size) && in_array($type, array('jpg', 'gif', 'jpeg', 'png'))) {
                                if (!($temp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !@move_uploaded_file($_FILES[$key]['tmp_name'], $temp_name)) {
                                    $this->errors[] = $this->l('An error occurred while uploading the image.');
                                } elseif (!ImageManager::resize($temp_name, $file_name, null, null, $type))
                                    $this->errors[] = sprintf($this->l('An error occurred while copying this image: %s'), Tools::stripslashes($image));
                            }
                            if (isset($temp_name))
                                @unlink($temp_name);
                        }
                    }
                    if ($object->id > 0 && $image) {
                        $prop = $key . '_old';
                        $object->$prop = $upload_folder . $object->$key;
                    }
                    if($image)
                        $object->$key = $image;
                }
            }
        }

        return $object;
    }

    public function processUpdate()
    {
        $this->processAdd();
        if (!count($this->errors))
            Tools::redirectAdmin(self::$currentIndex . '&conf=4&token=' . $this->token);
    }

    public function ajaxProcessUpdateStatus()
    {
        if ($this->loadObject()) {
            $employee = new Employee($this->object->id_employee);
            if ((int)$employee->id_profile === (int)_PS_ADMIN_PROFILE_) {
                $this->errors[] = $this->l('Supper admin is staff default.');
            } else {
                $this->object->active = (int)Tools::getValue('active') ? 1 : 0;
                if ($this->object->id <= 0 && !$this->object->add() || $this->object->id > 0 && !$this->object->update()) {
                    $this->errors[] = $this->l('Error: Change status fail.');
                }
            }
        } else
            $this->errors[] = $this->l('Error: Cannot loaded object.');
        $has_error = count($this->errors);
        $this->ajaxJson(array(
            'errors' => $has_error ? implode(PHP_EOL, $this->errors) : false,
            'msg' => !$has_error ? $this->l('Change status updated.') : false,
            'link' => self::$currentIndex . '&id_ets_hd_staff=' . $this->object->id . '-' . $this->object->id_employee . '&status' . $this->table . '&token=' . $this->token
        ));
    }

    public function loadObject($opt = false)
    {
        if ($opt) {
            if (!$this->object) {
                $this->object = new $this->className();
            }

            return $this->object;
        }
        $this->getIdentity();
        $this->object = new $this->className($this->id_ets_hd_staff);
        $this->object->id_employee = $this->id_employee;
        $employee = new Employee($this->id_employee);
        $this->object->email = $employee->email;

        return $this->object;
    }

    public function getIdentity()
    {
        $identifier = Tools::getValue($this->identifier);
        $id_staff_employee = trim($identifier) !== '' ? explode('-', $identifier) : array();
        if (!is_array($id_staff_employee) || count($id_staff_employee) < 2) {
            return;
        }
        if (Validate::isUnsignedInt($id_staff_employee[0]) || preg_match('#(\d+)#', $id_staff_employee[0])) {
            $this->id_ets_hd_staff = (int)$id_staff_employee[0];
        }
        if (Validate::isUnsignedInt($id_staff_employee[1]) || preg_match('#(\d+)#', $id_staff_employee[1])) {
            $this->id_employee = (int)$id_staff_employee[1];
        }
    }

    public function getFieldsValue($obj)
    {
        parent::getFieldsValue($obj);

        $this->fields_value['id_ets_hd_staff'] = $obj->id;

        return $this->fields_value;
    }

    public function setMedia($isNewTheme = false)
    {
        parent::setMedia($isNewTheme);

        $this->addJqueryPlugin('autocomplete');
    }

    public function getTemplateFormVars()
    {
        $this->tpl_form_vars['PS_ATTACHMENT_MAXIMUM_SIZE'] = HDTools::formatBytes(HDTools::getPostMaxSizeBytes());

        return parent::getTemplateFormVars();
    }

    public function getTemplateListVars()
    {
        $this->tpl_list_vars['icon'] = 'icon-AdminAdmin';

        return parent::getTemplateListVars();
    }

    public function setHelperDisplay(Helper $helper)
    {
        $this->toolbar_btn = array();
        $this->bulk_actions = array();

        parent::setHelperDisplay($helper);
    }
}