<?php
/**
 * 2007-2020 ETS-Soft
 *
 * NOTICE OF LICENSE
 *
 * This file is not open source! Each license that you purchased is only available for 1 web site only.
 * If you want to use this file on more web sites (or projects), you need to purchase additional licenses.
 * You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
 *
 * 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 contact us for extra customization service at an affordable price
 *
 * @author ETS-Soft <etssoft.jsc@gmail.com>
 * @copyright  2007-2020 ETS-Soft
 * @license    Valid for 1 web site (or project) for each purchase of license
 *  International Registered Trademark & Property of ETS-Soft
 */

class Ets_helpdeskUploadModuleFrontController extends ModuleFrontController
{
    /**
     * @var $module Ets_helpdesk
     */
    public $module;

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

    public function postProcess()
    {
        if (Tools::getValue('ajax') && ($action = Tools::getValue('action')) && Validate::isCleanHtml($action)) {
            $action = 'ajaxProcess' . Tools::ucfirst($action);
            $this->{$action}();
        }
    }

    static $default_field = 'ets_hd_avatar';

    public function ajaxProcessUploadProfileImage()
    {
        $key = self::$default_field;
        $customer = new HDCustomer($this->context->customer->id);
        $this->module->validateUploadFile($key,
            array(
                'name' => $key,
                'folder' => HDDefines::$avatar_upload,
                'required' => false
            )
            , $customer->id_customer
            , Ets_helpdesk::$ext_image_files
            , $this->errors
        );
        if (!$this->errors) {
            $salt = Tools::strtolower(Tools::passwdGen(20)) . Tools::substr(md5($this->context->customer->id), 0, 5);
            $type = Tools::strtolower(Tools::substr(strrchr($_FILES[$key]['name'], '.'), 1));
            $image = $salt . '.' . $type;
            $file_name = HDDefines::$avatar_upload . $image;

            if (@file_exists($file_name)) {
                $this->errors[] = $this->module->l('File name already exists. Try to rename the file and upload again', 'upload');
            } else {
                $image_size = @getimagesize($_FILES[$key]['tmp_name']);
                if (isset($_FILES[$key]) && !empty($_FILES[$key]['tmp_name']) && !empty($image_size) && in_array($type, Ets_helpdesk::$ext_image_files)) {
                    if (!($temp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !@move_uploaded_file($_FILES[$key]['tmp_name'], $temp_name)) {
                        $this->errors[] = $this->module->l('An error occurred while uploading the image.', 'upload');
                    } elseif (!ImageManager::resize($temp_name, $file_name, null, null, $type))
                        $this->errors[] = sprintf($this->module->l('An error occurred while copying this image: %s', 'upload'), Tools::stripslashes($image));
                }
                if (isset($temp_name))
                    @unlink($temp_name);
            }
            if (!$this->errors) {
                $oldImage = $customer->id && $customer->avatar ? HDDefines::$avatar_upload . $customer->avatar : '';
                $customer->avatar = $image;
                if (!$customer->save()) {
                    if (@file_exists($file_name)) {
                        @unlink($file_name);
                    }
                    $this->errors[] = sprintf($this->module->l('An error occurred while adding this image: %s', 'upload'), Tools::stripslashes($image));
                } elseif (@file_exists($oldImage)) {
                    @unlink($oldImage);
                }
            }
        }
        $hasError = count($this->errors) ? 1 : 0;
        die(json_encode([
            'errors' => $hasError ? implode('<br>', $this->errors) : false,
            'msg' => !$hasError ? $this->module->l('Upload image successful', 'upload') : '',
        ]));
    }

    public function viewAccess()
    {
        if (!isset($this->context->customer->id) || !$this->context->customer->id) {
            die(json_encode([
                'errors' => true,
                'msg' => $this->module->l('Customer does not exist.', 'upload'),
            ]));
        }
    }

    public function ajaxProcessDeleteProfileImage()
    {
        $customer = new HDCustomer($this->context->customer->id);
        $avatar_file = HDDefines::$avatar_upload . $customer->avatar;
        $customer->avatar = '';
        if ($customer->update()) {
            if (!@file_exists($avatar_file)) {
                $this->errors[] = $this->module->l('File avatar is does\'t exist.', 'upload');
            } elseif (!is_writeable($avatar_file) || !@unlink($avatar_file)) {
                $this->errors[] = $this->module->l('File avatar is writeable.', 'upload');
            }
        } else
            $this->errors[] = $this->module->l('Cannot delete avatar.', 'upload');

        $hasError = count($this->errors) ? 1 : 0;
        die(json_encode([
            'errors' => $hasError ? implode('<br>', $this->errors) : false,
            'msg' => !$hasError ? $this->module->l('Image deleted', 'upload') : '',
        ]));
    }
}
