<?php
/*
	Module Name: Surface (Area) / Volume Calculator for Prestashop 1.5
	Module URI: Please contact with info@megventure.com
	Description: A utility to calculate quantity in area or volume units
	Version: 1.0
	Author: MEG Venture

	Copyright 2013, MEG Venture (info@megventure.com)

	This program is not a free software: you can't redistribute it and/or modify
	it. All rights reserved to MEG Venture.

	This copyright notice  and licence should be retained in all modules based on this framework.
	This does not affect your rights to assert copyright over your own original work.
*/

if (!defined('_PS_VERSION_'))
	exit;

class Squaremeter extends Module
{
	private $_html = '';
	private $_postErrors = array();
	public $context;
	public  $unittype;

	function __construct($dontTranslate = false)
	{
		$this->name = 'squaremeter';
		$this->tab = 'front_office_features';
		$this->version = '2.0';
		$this->author = 'MEG Venture';
		$this->need_instance = 0;
		$this->module_key = "0cc8078ba5105cf0b6a0a5626aaf134d";	
		$this->secure_key = Tools::encrypt($this->name);		

		$config = Configuration::getMultiple(array($this->name.'_unittype'));

		if (isset($config[$this->name.'_unittype']))
			$this->unittype = $config[$this->name.'_unittype'];


		parent::__construct();

		if (!$dontTranslate)
		{
		$this->displayName = $this->l('Surface (Area) / Volume Calculation Module');
$this->description = $this->l('A utility to calculate quantity in surface (area) or volume. <a href=../modules/squaremeter/readme_en.pdf>Read the Installation and User Guide</a>');
		if (!isset($this->unittype))
		$this->warning = $this->l('Measurement unit type must be configured in order to use this module correctly.');	
 		}

		$path = dirname(__FILE__);
		if (strpos(__FILE__, 'Module.php') !== false)
			$path .= '/../modules/'.$this->name;
		require_once(dirname(__FILE__) . '/classes/Squaremeter_Admin.php');	
	}

	public function install()
	{
        $sql = array();

        $sql[] = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'squaremeteradmin` (
                  `id_squaremeteradmin` int(10) unsigned NOT NULL AUTO_INCREMENT,
                  `id_product` INT( 11 ) UNSIGNED NOT NULL,
                  `displaycalculator` varchar(10) NOT NULL,
                  `calculationtype` varchar(10) NOT NULL,
				  `additionalquantity` varchar(10) NOT NULL,
				  `displayquantity` varchar(20) NOT NULL,	
				  `displayprice` varchar(20) NOT NULL,			  
				  `conversion` varchar(15) NOT NULL,
				  `conversionunit` varchar(15) NOT NULL,
				  `maxwidth` varchar(15) NOT NULL,
				  `maxwidthunit` varchar(15) NOT NULL,
				  `minwidth` varchar(15) NOT NULL,
				  `minwidthunit` varchar(15) NOT NULL,				  
				  `maxheight` varchar(15) NOT NULL,
				  `maxheightunit` varchar(15) NOT NULL,
				  `minheight` varchar(15) NOT NULL,
				  `minheightunit` varchar(15) NOT NULL,
				  `maxdepth` varchar(15) NOT NULL,
				  `maxdepthunit` varchar(15) NOT NULL,
				  `mindepth` varchar(15) NOT NULL,
				  `mindepthunit` varchar(15) NOT NULL,				  
                  PRIMARY KEY (`id_squaremeteradmin`),
                  UNIQUE  `REDIRECTPRODUCT_ADMIN_UNIQ` (  `id_product` )
                ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8';	
		
		Db::getInstance()->Execute('ALTER TABLE '._DB_PREFIX_.'order_detail ADD(square varchar(255) DEFAULT NULL)');
		
		rename("../pdf/invoice.tpl", "../pdf/invoice_old.tpl");	
		rename("../pdf/invoice-b2b.tpl", "../pdf/invoice-b2b_old.tpl");	
		rename("../pdf/order-return.tpl", "../pdf/order-return_old.tpl");	
		copy("../modules/squaremeter/pdf/invoice.tpl", "../pdf/invoice.tpl");	
		copy("../modules/squaremeter/pdf/invoice-b2b.tpl", "../pdf/invoice-b2b.tpl");	
		copy("../modules/squaremeter/pdf/order-return.tpl", "../pdf/order-return.tpl");
		rename("../modules/blockcart/ajax-cart.js", "../modules/blockcart/ajax-cart_old.js");
		rename("../modules/blockcart/blockcart-json.tpl", "../modules/blockcart/blockcart-json_old.tpl");				
		copy("../modules/squaremeter/modules/blockcart/ajax-cart.js", "../modules/blockcart/ajax-cart.js");		
		copy("../modules/squaremeter/modules/blockcart/blockcart-json.tpl", "../modules/blockcart/blockcart-json.tpl");		
		rename("../modules/mailalerts/mailalerts.php", "../modules/mailalerts/mailalerts_old.php");		
		copy("../modules/squaremeter/modules/mailalerts/mailalerts.php", "../modules/mailalerts/mailalerts.php");
		rename("../themes/default/modules/blockcart/blockcart.tpl", "../themes/default/modules/blockcart/blockcart_old.tpl");				
		rename("../themes/default/order-detail.tpl", "../themes/default/order-detail_old.tpl");	
		rename("../themes/default/product.tpl", "../themes/default/product_old.tpl");	
		rename("../themes/default/shopping-cart-product-line.tpl", "../themes/default/shopping-cart-product-line_old.tpl");	
		copy("../modules/squaremeter/themes/default/modules/blockcart/blockcart.tpl", "../themes/default/modules/blockcart/blockcart.tpl");
		copy("../modules/squaremeter/themes/default/order-detail.tpl", "../themes/default/order-detail.tpl");
		copy("../modules/squaremeter/themes/default/product.tpl", "../themes/default/product.tpl");			
		copy("../modules/squaremeter/themes/default/shopping-cart-product-line.tpl", "../themes/default/shopping-cart-product-line.tpl");				
		
		if (!unlink('../cache/class_index.php') || !parent::install() || !$this->registerHook('displayHeader') || !$this->registerHook('productActions') || !$this->registerHook('displayAdminProductsExtra') || !$this->registerHook('actionProductUpdate') || !$this->runSql($sql))
			return false;
			
		if (!Db::getInstance()->Execute('
		INSERT INTO `'._DB_PREFIX_.'configuration`(`id_configuration`, `name`, `value`, `date_add`, `date_upd`) 
		VALUES("","squaremeter_unittype", "metric", "2012-03-29 00:08:22", "2012-04-02 12:42:16")'))
			return false;
			
		return true;
	}

	public function uninstall()
	{
		$sql = array();
        $sql[] = 'DROP TABLE IF EXISTS `'._DB_PREFIX_.'squaremeteradmin`';
		Db::getInstance()->Execute('ALTER TABLE '._DB_PREFIX_.'order_detail DROP square');
		
		if (!Configuration::deleteByName($this->name.'_unittype') || !parent::uninstall()  || !$this->runSql($sql))
			return false;
		unlink('../override/classes/PaymentModule.php');
		unlink('../override/controllers/front/OrderConfirmationController.php');
		unlink('../override/controllers/front/OrderReturnController.php');	
		unlink('../override/controllers/front/CartController.php');	
		unlink('../pdf/invoice.tpl');	
		unlink('../pdf/invoice-b2b.tpl');	
		unlink('../pdf/order-return.tpl');	
		rename("../pdf/invoice_old.tpl", "../pdf/invoice.tpl");	
		rename("../pdf/invoice-b2b_old.tpl", "../pdf/invoice-b2b.tpl");	
		rename("../pdf/order-return_old.tpl", "../pdf/order-return.tpl");		
		unlink('../modules/blockcart/ajax-cart.js');	
		rename("../modules/blockcart/ajax-cart_old.js", "../modules/blockcart/ajax-cart.js");
		unlink('../modules/blockcart/blockcart-json.tpl');	
		rename("../modules/blockcart/blockcart-json.tpl_old.js", "../modules/blockcart/blockcart-json.tpl.js");			
		unlink('../modules/mailalerts/mailalerts.php');				
		rename("../modules/mailalerts/mailalerts_old.php","../modules/mailalerts/mailalerts.php");
		unlink('../themes/default/modules/blockcart/blockcart.tpl');
		unlink('../themes/default/order-detail.tpl');	
		unlink('../themes/default/product.tpl');
		unlink('../themes/default/shopping-cart-product-line.tpl');
		rename("../themes/default/modules/blockcart/blockcart_old.tpl", "../themes/default/modules/blockcart/blockcart.tpl");				
		rename("../themes/default/order-detail_old.tpl","../themes/default/order-detail.tpl");			
		rename("../themes/default/product_old.tpl","../themes/default/product.tpl");
		rename("../themes/default/shopping-cart-product-line_old.tpl", "../themes/default/shopping-cart-product-line.tpl");		
		unlink('../cache/class_index.php');	
			
		return true;
	}

    public function runSql($sql) {
        foreach ($sql as $s) {
			if (!Db::getInstance()->Execute($s)){
				return FALSE;
			}
        }

        return TRUE;
    }

	private function _postValidation()
	{
		if (Tools::isSubmit('submit'))
		{
			if (!Tools::getValue('unittypeA'))
				$this->_postErrors[] = $this->l('Changes are not saved. Unit measurement type is required.');
		}
	}

	public function getContent()
	{
		global $cookie;
		if (Tools::isSubmit('submit'))
		{	
			$this->_postValidation();
			if (!sizeof($this->_postErrors))
				$this->_postProcess();
			else
				foreach ($this->_postErrors AS $err)
					$this->_html .= '<div class="alert error">'. $err .'</div>';
		}	
	
	$this->_displayForm();

	return $this->_html;
	}
	
	private function _postProcess()
	{
	
		Configuration::updateValue($this->name.'_unittype', Tools::getValue('unittypeA'));
		
		$this->_html .= '<div class="conf confirm"><img src="'.__PS_BASE_URI__.'img/admin/ok.gif" alt="'.$this->l('ok').'" /> '.$this->l('Settings updated').'</div>';
	}


private function _displayForm()
{
	global $cookie;
		
	$this->_html .= '
	<h2>'.$this->displayName.'</h2>
	<form name="configuration_form" action="'.htmlentities($_SERVER['REQUEST_URI']).'" method="post">
			<font size="2">'.$this->l('Thanks for using Linear / Area (Surface) / Volume Calculator Module designed by').' MEG Venture. '.$this->l('Please fill out all the fields below to function the module properly.').'</font><br><br><hr>
<br>
			<fieldset>
			<legend><img src="'.__PS_BASE_URI__.'img/admin/prefs.gif" />'.$this->l('Options').'</legend>
			<label>'.$this->l('Measurement Unit Type').'</label>
			<input type="radio" name="unittypeA" value="english" '.(Configuration::get('squaremeter_unittype')=="english" ? ' checked="checked"' : '').'/>'.$this->l('English (Standard)').'&nbsp;&nbsp;<input type="radio" name="unittypeA" value="metric" '.(Configuration::get('squaremeter_unittype')=="metric" ? ' checked="checked"' : '').'/>'.$this->l('Metric').'			
			<div class="margin-form">
			<br><p class="clear">'.$this->l('The module allows two types of measurement unit system: English (standard) and Metric unit systems. One of them should be selected in order to use the module correctly.').'</p>
			<p class="clear"><a href="'.__PS_BASE_URI__.'modules/squaremeter/img/admin.png" target="_blank"><img src="'.__PS_BASE_URI__.'modules/squaremeter/img/admin_s.png" width="40" height="22" /></a> '.$this->l('Note that calculator settings are adjusted through each product\'s edit page. Once you go to the regarding product editing page, you need to use the bottom tab for those settings:').'</p>
			</div>
			</fieldset>
			
			<br>			

			<input type="submit" name="submit" value="'.$this->l('Update').'" class="button" />
			<br><hr><img border="0" src="'.$this->_path.'img/Help.png" width="16" height="16">'.$this->l('Please contact for further suggestions, feedback, update and support at').' <a href="https://addons.prestashop.com/contact-form.php">Addons Contact Form</a>
	</form>';
}


    public function hookDisplayAdminProductsExtra($params) {
        $id_product = Tools::getValue('id_product');
        $sampleObj = Squaremeter_Admin::loadByIdProduct($id_product);
        if(!empty($sampleObj) && isset($sampleObj->id)){
            $this->context->smarty->assign(array(
                'admintab_display' => $sampleObj->displaycalculator,
                'admintab_type' => $sampleObj->calculationtype,		
				'admintab_addquan' => $sampleObj->additionalquantity,
				'admintab_dispquan' => $sampleObj->displayquantity,		
				'admintab_dispprice' => $sampleObj->displayprice,					
				'admintab_conversion' => $sampleObj->conversion,
				'admintab_conversion_unit' => $sampleObj->conversionunit,
				'admintab_maxheight' => $sampleObj->maxheight,
				'admintab_maxheight_unit' => $sampleObj->maxheightunit,
				'admintab_minheight' => $sampleObj->minheight,
				'admintab_minheight_unit' => $sampleObj->minheightunit,
				'admintab_maxdepth' => $sampleObj->maxdepth,
				'admintab_maxdepth_unit' => $sampleObj->maxdepthunit,
				'admintab_mindepth' => $sampleObj->mindepth,
				'admintab_mindepth_unit' => $sampleObj->mindepthunit,				
				'admintab_maxwidth' => $sampleObj->maxwidth,
				'admintab_maxwidth_unit' => $sampleObj->maxwidthunit,
				'admintab_minwidth' => $sampleObj->minwidth,
				'admintab_minwidth_unit' => $sampleObj->minwidthunit,
            ));
        }
	if(Configuration::get('squaremeter_unittype')=="metric") {
        return $this->display(__FILE__, 'views/admin/admintab.tpl');
		}
	else
	{
        return $this->display(__FILE__, 'views/admin/admintab_e.tpl');		
		}
    }	

    public function hookActionProductUpdate($params) {
        $id_product = Tools::getValue('id_product');
        $sampleObj = Squaremeter_Admin::loadByIdProduct($id_product);
        $sampleObj->displaycalculator = Tools::getValue('squaremeter_display');
        $sampleObj->calculationtype = Tools::getValue('calculation_type');		
        $sampleObj->additionalquantity = Tools::getValue('additional_quantity');	
        $sampleObj->displayquantity = Tools::getValue('display_quantity');	
		$sampleObj->displayprice = Tools::getValue('display_price');				
		$sampleObj->conversion = Tools::getValue('conversion');
		$sampleObj->conversionunit = Tools::getValue('conversion_unit');
        $sampleObj->maxheight = Tools::getValue('maximum_height');
		$sampleObj->maxheightunit = Tools::getValue('maximum_height_unit');
        $sampleObj->minheight = Tools::getValue('minimum_height');	
		$sampleObj->minheightunit = Tools::getValue('minimum_height_unit');	
        $sampleObj->maxdepth = Tools::getValue('maximum_depth');
		$sampleObj->maxdepthunit = Tools::getValue('maximum_depth_unit');
        $sampleObj->mindepth = Tools::getValue('minimum_depth');	
		$sampleObj->mindepthunit = Tools::getValue('minimum_depth_unit');					
		$sampleObj->maxwidth = Tools::getValue('maximum_width');	
		$sampleObj->maxwidthunit = Tools::getValue('maximum_width_unit');
		$sampleObj->minwidth = Tools::getValue('minimum_width');	
		$sampleObj->minwidthunit = Tools::getValue('minimum_width_unit');						
        $sampleObj->id_product = $id_product;

        if(!empty($sampleObj) && isset($sampleObj->id)){
            $sampleObj->update();
        } else {
            $sampleObj->add();
        }
    }

	public function hookDisplayHeader()
	{
		global $smarty, $cookie;
        $id_product = Tools::getValue('id_product');
        $sampleObj = Squaremeter_Admin::loadByIdProduct($id_product);
        if(!empty($sampleObj) && isset($sampleObj->id)){
		$this->smarty->assign(array(
				'default_lang' => (int)$this->context->language->id,
				'id_lang' => $this->context->language->id,
                'admintab_display' => $sampleObj->displaycalculator,
                'admintab_type' => $sampleObj->calculationtype,		
				'admintab_addquan' => $sampleObj->additionalquantity,	
				'admintab_dispquan' => $sampleObj->displayquantity,	
				'admintab_dispprice' => $sampleObj->displayprice,					
				'admintab_conversion' => $sampleObj->conversion,
				'admintab_conversion_unit' => $sampleObj->conversionunit,
				'admintab_maxheight' => $sampleObj->maxheight,
				'admintab_maxheight_unit' => $sampleObj->maxheightunit,
				'admintab_minheight' => $sampleObj->minheight,
				'admintab_minheight_unit' => $sampleObj->minheightunit,
				'admintab_maxdepth' => $sampleObj->maxdepth,
				'admintab_maxdepth_unit' => $sampleObj->maxdepthunit,
				'admintab_mindepth' => $sampleObj->mindepth,
				'admintab_mindepth_unit' => $sampleObj->mindepthunit,				
				'admintab_maxwidth' => $sampleObj->maxwidth,
				'admintab_maxwidth_unit' => $sampleObj->maxwidthunit,
				'admintab_minwidth' => $sampleObj->minwidth,
				'admintab_minwidth_unit' => $sampleObj->minwidthunit,
			));
        }
		if(Configuration::get('squaremeter_unittype')=="metric") {
			if($sampleObj->calculationtype=="surface"){
				$this->context->controller->addCSS(($this->_path).'css/squaremeter.css', 'all');
				return $this->display(__FILE__, 'views/frontend/header.tpl');			
			}
			else if ($sampleObj->calculationtype=="volume")
			{
				$this->context->controller->addCSS(($this->_path).'css/squaremeterv.css', 'all');
				return $this->display(__FILE__, 'views/frontend/headerv.tpl');			
			}
		}
		else
		{
			if($sampleObj->calculationtype=="surface"){
				$this->context->controller->addCSS(($this->_path).'css/squaremeter.css', 'all');
				return $this->display(__FILE__, 'views/frontend/header_e.tpl');			
			}
			else if ($sampleObj->calculationtype=="volume")
			{
				$this->context->controller->addCSS(($this->_path).'css/squaremeterv.css', 'all');
				return $this->display(__FILE__, 'views/frontend/headerv_e.tpl');			
			}
		}
	}

	function hookproductActions($params)
	{
		global $smarty, $cookie;
        $id_product = Tools::getValue('id_product');
        $sampleObj = Squaremeter_Admin::loadByIdProduct($id_product);
        if(!empty($sampleObj) && isset($sampleObj->id)){
		$this->smarty->assign(array(
				'default_lang' => (int)$this->context->language->id,
				'id_lang' => $this->context->language->id,
                'admintab_display' => $sampleObj->displaycalculator,
                'admintab_type' => $sampleObj->calculationtype,	
				'admintab_addquan' => $sampleObj->additionalquantity,
				'admintab_dispquan' => $sampleObj->displayquantity,	
				'admintab_dispprice' => $sampleObj->displayprice,															
				'admintab_conversion' => $sampleObj->conversion,
				'admintab_conversion_unit' => $sampleObj->conversionunit,
				'admintab_maxheight' => $sampleObj->maxheight,
				'admintab_maxheight_unit' => $sampleObj->maxheightunit,
				'admintab_minheight' => $sampleObj->minheight,
				'admintab_minheight_unit' => $sampleObj->minheightunit,
				'admintab_maxdepth' => $sampleObj->maxdepth,
				'admintab_maxdepth_unit' => $sampleObj->maxdepthunit,
				'admintab_mindepth' => $sampleObj->mindepth,
				'admintab_mindepth_unit' => $sampleObj->mindepthunit,				
				'admintab_maxwidth' => $sampleObj->maxwidth,
				'admintab_maxwidth_unit' => $sampleObj->maxwidthunit,
				'admintab_minwidth' => $sampleObj->minwidth,
				'admintab_minwidth_unit' => $sampleObj->minwidthunit,
			));
        }

		if (Configuration::get('PS_CATALOG_MODE'))
			return ;

		if (($sampleObj->displaycalculator == "yes") AND ($sampleObj->calculationtype == "surface"))
		{
				return $this->display(__FILE__, 'views/frontend/product_page.tpl');
			}
		elseif (($sampleObj->displaycalculator == "yes") AND ($sampleObj->calculationtype == "volume"))
		{
				return $this->display(__FILE__, 'views/frontend/product_pagev.tpl');			
			}
		else
		{}
	}
}