<?php
/**
 * NOTICE OF LICENSE
 *
 * This file is licenced under the Software License Agreement.
 * With the purchase or the installation of the software in your application
 * you accept the licence agreement.
 *
 * You must not modify, adapt or create derivative works of this source code
 *
 *  @author    Geo Burlibasa
 *  @copyright 2016 Geo Burlibasa
 *  @license   stickyrst
 */

class LinkToCart extends Module
{
    public function __construct()
    {
        $this->name = 'linktocart';
        $this->tab = 'front_office_features';
        $this->version = '1.1.1';
        $this->author = 'Geo Burlibasa';
        $this->need_instance = 0;
        $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
        $this->bootstrap = true;
        $this->module_key = 'd3c1f065aedc7c98d2907b47d1947b44';
        
        if(Tools::getValue("qty") !== false) {
            $_POST["qty"] = Tools::getValue("qty");
        }
     
        parent::__construct();
     
        $this->displayName = $this->l('Link to cart - Voucher by link');
        $this->description = $this->l('Allows you to create a link to a product for your customers. If they access the link, that product will be automatically added to customer`s cart.');
     
        $this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
    }
    
    public function install()
    {
        if (Shop::isFeatureActive())
            Shop::setContext(Shop::CONTEXT_ALL);
       
        if (!parent::install() ||
            !$this->registerHook('header') ||
            !$this->registerHook('displayAdminProductsExtra')
        )
            return false;
        return true;
    }
    
    public function uninstall()
    {
        if (!parent::uninstall())
            return false;
        return true;
    }
    
    public function hookDisplayHeader()
    {
        if ($this->context->controller->php_self == "product" && Tools::getValue("linktocart") !== false) {
            if(Tools::getValue("cart_rule")) {
                $cartRuleUrl = $this->context->link->getPageLink('cart');
                $static_token = Tools::getToken(false);
                $params = 'discount_name='.Tools::getValue('cart_rule').'&submitDiscount=&submitAddDiscount=&ajax=true';
                if(Tools::version_compare(_PS_VERSION_, '1.7', '<'))
                {
                    if(Configuration::get('PS_ORDER_PROCESS_TYPE') == 1)
                    {
                        $cartRuleUrl = $this->context->link->getPageLink('order-opc');
                    }
                    else
                    {
                        $cartRuleUrl = $this->context->link->getPageLink('order');
                    }
                }
                else
                {
                    $params .= '&action=update&token='.$static_token.'&addDiscount=1';
                }
                Media::addJsDef(array("linktocart_cart_rule" => Tools::getValue("cart_rule"),
                                      "linkToCart_cartRuleUrl" => $cartRuleUrl,
                                      "linkToCart_params" => $params,
                                ));
            }
            $this->context->controller->addJS($this->_path.'views/js/linktocart.js');
        }
    }
    
    public function hookDisplayAdminProductsExtra($params)
    {
        $id_product = isset($params['id_product']) ? (int)$params['id_product'] : (int)Tools::getValue('id_product');
        $product = new Product($id_product);
        if($id_product && Validate::isLoadedObject($product)) {
            $link = new Link;
            $languages = Language::getLanguages();
            $data = array();
            $cartrule = new CartRule;
            $cartrules = $cartrule->getCustomerCartRules($this->context->cookie->id_lang, $this->context->cookie->id_customer);
            $validcr = array();
            foreach($cartrules as $cr) {
                if(strtotime($cr['date_to']) > time() && strtotime($cr['date_from']) < time() && $cr['active']) {
                    $validcr[$cr["code"]] = $cr["name"];
                }
            }
            foreach ($languages as $l) {
                $direct = $this->context->link->getModuleLink('linktocart', 'direct', array(), null, $l["id_lang"]);
                $combinations = $product->getAttributeCombinations($l["id_lang"]);
                $data[$l["id_lang"]]["name"] = $l["name"];
                $linktocart_url = $link->getProductLink($id_product, null, null, null, $l["id_lang"]);
                $linktocart_url_array = parse_url($linktocart_url);
                if (!isset($linktocart_url_array["query"])) {
                    $linktocart_url .= "?linktocart";
                } else {
                    $linktocart_url .= "&linktocart";
                }
                $data[$l["id_lang"]]["link"] = $linktocart_url;
                $data[$l["id_lang"]]["directlink"] = $direct."?id_product=".$id_product."&qty=1";
                if (is_array($combinations) && sizeof($combinations) > 0) {
                    foreach ($combinations as $comb) {
                        foreach ($comb as &$c) {
                            $c = str_replace(Configuration::get('PS_ATTRIBUTE_ANCHOR_SEPARATOR'), '_', Tools::link_rewrite(str_replace(array(',', '.'), '-', $c)));
                        }
                        if (!isset($data[$l["id_lang"]]['combs'][$comb["id_product_attribute"]]['link'])) {
                            $data[$l["id_lang"]]['combs'][$comb["id_product_attribute"]]['name'] = $comb["group_name"].": ".$comb["attribute_name"];
                            $data[$l["id_lang"]]['combs'][$comb["id_product_attribute"]]['link'][] = "/".Tools::strtolower($comb["id_attribute"]."-".$comb["group_name"]."-".$comb["attribute_name"]);
                        } else {
                            $data[$l["id_lang"]]['combs'][$comb["id_product_attribute"]]['name'] .= ", ".$comb["group_name"].": ".$comb["attribute_name"];
                            $data[$l["id_lang"]]['combs'][$comb["id_product_attribute"]]['link'][] = "/".Tools::strtolower($comb["id_attribute"]."-".$comb["group_name"]."-".$comb["attribute_name"]);
                        }
                        $data[$l["id_lang"]]['combs'][$comb["id_product_attribute"]]['directlink'] = $direct."?id_product=".$id_product."&ipa=".$comb["id_product_attribute"]."&qty=1";
                    }
                    foreach ($combinations as $comb) {
                        asort($data[$l["id_lang"]]['combs'][$comb["id_product_attribute"]]['link']);
                    }
                }
            }
            $this->context->smarty->assign("cartrules", $validcr);
            $this->context->smarty->assign("direct", $direct);
            $this->context->smarty->assign("data", $data);
        }
        else
        {
            $this->context->smarty->assign('newproduct', true);
        }
        return $this->display(__FILE__, "views/templates/admin/linktocart.tpl");
    }
}
