<?php

/**
 * 2007-2017 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * @author    Innovadeluxe SL
 * @copyright 2017 Innovadeluxe SL

 * @license   INNOVADELUXE
 */
class IdxrcustomproductAjaxModuleFrontController extends ModuleFrontController
{

    public function initContent()
    {
        parent::initContent();
        $this->ajaxProcessFront();
    }

    public function ajaxProcessFront()
    {
        if (Tools::getValue('action') == 'savefav') {
            $this->ajaxProcessSavefav();
        }

        if (Tools::getValue('action') == 'deletefav') {
            $this->ajaxProcessDeletefav();
        }

        if (Tools::getValue('action') == 'customfile') {
            $this->ajaxProcessCustomfile();
        }

        if (Tools::getValue('action') == 'createproduct') {
            $this->ajaxProcessCreateproduct();
        }

        if (Tools::getValue('action') == 'setCart') {
            $this->ajaxProcessSetCart();
        }
        
        if (Tools::getValue('action') == 'isCustomized') {
            $this->ajaxProcessIsCustomized();
        }
        
        if (Tools::getValue('action') == 'getCustomizedData') {
            $this->ajaxProcessGetCustomizedData();
        }
        
        if (Tools::getValue('action') == 'saveimgstatus') {
            $this->ajaxProcessSaveimgstatus();
        }
        
        if (Tools::getValue('action') == 'getimgstatus') {
            $this->ajaxProcessGetimgstatus();
        }
        
        if (Tools::getValue('action') == 'formatprice') {
            $this->ajaxProcessFormatPrice();
        }
    }

    public function ajaxProcessSavefav()
    {
        $product_id = Tools::getValue('product');
        $attribute_id = Tools::getValue('attribute');
        $customization = explode(',', Tools::getValue('custom'));
        $extra_values = explode('3x7r4', Tools::getValue('extra'));
        $result = $this->module->saveFavorite($product_id, $attribute_id, $customization, $extra_values);
        if ($result == 1) {
            die($this->module->l('Customization saved in you favorite zone', 'ajax'));
        } elseif ($result == 2) {
            die($this->module->l('This customization is already in you favorite zone', 'ajax'));
        } else {
            die($this->module->l('There was any error saving your customization, please try again later', 'ajax'));
        }
    }

    public function ajaxProcessDeletefav()
    {
        $fav_id = Tools::getValue('favid');
        die($this->module->delFavorite($fav_id));
    }

    public function ajaxProcessCustomfile()
    {
        $fileName = $_FILES['file']['name'];
        $fileType = pathinfo($fileName, PATHINFO_EXTENSION);
        $fileSize = ($_FILES['file']['size'] / 1024) / 1024;
        $id_component = Tools::getValue('component');
        $id_product = Tools::getValue('product');

        $file_rules_query = 'Select * from ' . _DB_PREFIX_ . 'idxrcustomproduct_components_lang  where id_component = ' . (int) $id_component;
        $file_rules = Tools::jsonDecode(Db::getInstance()->getRow($file_rules_query)['json_values']);

        if ($fileSize > $file_rules->size) {
            die('Archivo demasiado grande');
        }
        if (!in_array($fileType, $file_rules->allowed_extension)) {
            die('Formato no valido');
        }

        $md5filename = md5('idxrcustomproduct_' . $id_product . '_' . $id_component . '_' . (int) Context::getContext()->cart->id . '_' . $fileName);
        $fileTarget = _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . $md5filename;

        if (move_uploaded_file($_FILES["file"]["tmp_name"], $fileTarget)) {
            $exist_q = 'Select id_file from ' . _DB_PREFIX_ . 'idxrcustomproduct_files where target_name = "' . pSQL($md5filename) . '"';
            $exist = Db::getInstance()->getRow($exist_q);
            if (!$exist) {
                $data = array(
                    'id_cart' => (int) Context::getContext()->cart->id,
                    'id_product' => (int) $id_product,
                    'id_component' => (int) $id_component,
                    'original_name' => pSQL($fileName),
                    'target_name' => pSQL($md5filename),
                );
                Db::getInstance()->insert('idxrcustomproduct_files', $data);
            }
            die('ok');
        } else {
            die('problemas al subir el archivo de ' . $_FILES["file"]["tmp_name"] . ' a ' . $fileTarget . print_r($_FILES));
        }
    }

    public function ajaxProcessCreateproduct()
    {
        $product_id = Tools::getValue('product');
        $attribute_id = Tools::getValue('attribute');
        $customization = explode(',', Tools::getValue('custom'));
        $extra = explode('3x7r4', Tools::getValue('extra'));
        foreach ($customization as &$option) {
            $option = explode('_', $option);
            $option['id_component'] = $option[0];
            $option['id_option'] = $option[1];
            unset($option[0]);
            unset($option[1]);
        }
        die($this->module->createProduct($product_id, $attribute_id, $customization, $extra));
    }

    public function ajaxProcessSetCart()
    {
        $context = Context::getContext();
        if (!$context->cart->id) {
            $cart = $context->cart;
            try {
                $cart->save();
                $context->cart = $cart;
                $context->cookie->id_cart = $cart->id;
                $context->cookie->write();
            } catch (Exception $e) {
                PrestashopLogger::addLog($e->getMessage());
            }
        }
    }
    
    public function ajaxProcessIsCustomized()
    {
        $product_id = Tools::getValue('product_id');
        $product = new IdxCustomizedProduct($product_id);
        if ($product->isCustomized()) {
            die(true);
        } else {
            die(false);
        }
    }
    
    public function ajaxProcessGetCustomizedData()
    {        
        $clean = Tools::isSubmit('clean');
        $extra_info = $this->module->getExtraByContext($clean);
        die(json_encode($extra_info));
    }

    public function ajaxProcessSaveimgstatus()
    {
        $image_id = Tools::getValue('id_image');
        $status_string = Tools::getValue('status');
        $result = IdxConfiguration::saveConfigurationImageStatus($image_id, $status_string);
        die(json_encode('ok'));
    }
    
    public function ajaxProcessGetimgstatus()
    {
        $id_configuration = Tools::getValue('id_configuration');
        $status_string = Tools::getValue('status');
        if (!$status_string) {
            die(json_encode('ko'));
        }
        $image = IdxConfiguration::getImageidFromStatus($id_configuration, $status_string);
        if ($image) {
            $device = Context::getContext()->getDevice();
            switch ($device) {
                case Context::DEVICE_COMPUTER:
                    $type = Configuration::get(Tools::strtoupper($this->module->name .'_PCIMGTYPE'));
                    break;
                case Context::DEVICE_MOBILE:
                    $type = Configuration::get(Tools::strtoupper($this->module->name .'_MIMGTYPE'));
                    break;
                case Context::DEVICE_TABLET:
                    $type = Configuration::get(Tools::strtoupper($this->module->name .'_TIMGTYPE'));
                    break;
                default:
                    $type = Configuration::get(Tools::strtoupper($this->module->name .'_PCIMGTYPE'));
                    break;
            }
            $image_src = IdxConfiguration::getImage($image, 'src', $type);
            die(json_encode($image_src));
        }
        die(json_encode($image));
    }
    
    public function ajaxProcessFormatPrice()
    {
        $price = Tools::getValue('price');
        $price_formated = Idxrcustomproduct::formatPrice($price);
        die(json_encode($price_formated));
    }
}
