<?php
/*
 * @component Calc Builder
* @copyright Copyright (C) January 2017.
* @license GPL 3.0
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* See <http://www.gnu.org/licenses/>.
* More info www.moonsoft.es
* gestion@moonsoft.es
*/
class hkpluginhelper extends JPlugin{
	function onBeforeCalculateProductPriceForQuantity(&$product){
		$newprice=$product->calculatedprice;		
		if($newprice==null) return;
		$newpricecontrol=$product->calculatedpricecontrol;
		$idp=$product->product_created;
		if($newpricecontrol!=md5($newprice."".$idp)){
			$product->product_name=$product->product_name."(invalid price)";
			$newprice=999999;
		}
		$calculatedparams=$product->calculatedparams;
		if($calculatedparams!=null && $calculatedparams!=""){
			$objparams=json_decode($calculatedparams);
			foreach($objparams as $key=>$value){			  
				$product->$key=$value;				
			}
		}		
		$product->calculatedprice=null;
		$product->calculatedpricecontrol=null;
		$product->calculatedparams=null;
		$currencyClass = hikashop_get('class.currency');
		if(empty($product->prices)){
			$price= new stdClass();
			$price->price_currency_id = hikashop_getCurrency();
			$price->price_min_quantity = 1;
			$product->prices = array($price);
		}
		foreach($product->prices as $k => $price){
			if($product->product_type=='variant' && empty($product->product_tax_id)){
				$productClass = hikashop_get('class.product');
				$main = $productClass->get($product->product_parent_id);
				$product->product_tax_id = $main->product_tax_id;
			}
			$pricecalculation=$newprice;
			$product->prices[$k]->price_value = $pricecalculation;
			$product->prices[$k]->price_value_with_tax = $currencyClass->getTaxedPrice($pricecalculation,hikashop_getZone(),$product->product_tax_id);
			$product->prices[$k]->taxes=$currencyClass->taxRates;
		}
	}
	function onHikashopBeforeDisplayView(&$view){
		$option = JRequest::getString('option');
		$ctrl = JRequest::getString('ctrl');
		$task = JRequest::getString('task');
		if ($option!='com_hikashop'||$ctrl!='product'||$task!='show') return;
		ob_start();
	}
	function onHikashopAfterDisplayView(&$view){
		$option = JRequest::getString('option');
		$ctrl = JRequest::getString('ctrl');
		$task = JRequest::getString('task');
		if ($option!='com_hikashop'||$ctrl!='product'||$task!='show') return;
		$config =& hikashop_config();
		$default_params = $config->get('default_params');
		$product_page = ob_get_clean();
		$product_page_parts = explode('class="hikashop_product_page"', $product_page);
		//var_dump ($view);
      //show_block_product_files
		if(($view->getLayout()=="listing_no" ||$view->getLayout()=="show_block_product_files"||$view->getLayout()=="quantity")&& is_a($view, 'ProductViewProduct')){
			$productid=JRequest::getVar("cid");
			$productClass = hikashop_get('class.product');
			$product=$productClass->get($productid);
			$idobj=$product->calculator;
         // var_dump ($idobj);
			if ($idobj && $idobj!=''):
			
			
			$show_btn=$this->params->get('show_btn',1);
			// $this->params->get('order',1);
			
			$showbtncode="";
			
			if($show_btn=="0"){
			
			$showbtncode.="jQuery('#btcalculator').hide();
											
			setChangeEvt();
			sendcalculation();
			";
			
			
			}
			
				echo '
				<script>
				 var cb_t;
                function setChangeEvt(){
                    jQuery("#hikashop_product_custom_item_info input,#hikashop_product_custom_item_info select,input[name=quantity],.hikashop_field_dropdown").each(function(index,elem){
                        jQuery(elem).change(function(){
                            if (cb_t!=null) clearTimeout(cb_t);
							cb_t=setTimeout("sendcalculation()",500);
                        });
                    });
					jQuery(".hikashop_product_quantity_field_change").each(function(index,elem){
                        jQuery(elem).click(function(){
                            if (cb_t!=null) clearTimeout(cb_t);
							cb_t=setTimeout("sendcalculation()",500);
                        });
                    });
                }

                var oldclick;
                var isAdd=false;
                jQuery(document).ready(function() {
					jQuery(".hikashop_item_calculatedprice_line").hide();
					jQuery(".hikashop_item_calculatedpricecontrol_line").hide();
					jQuery(".hikashop_item_calculatedparams_line").hide();
					//jQuery("#hikashop_product_price_main").hide();
					
					jQuery("#btcalculator").insertBefore(jQuery("#hikashop_product_quantity_main"));

                    '.$showbtncode.'

					//oldclick=jQuery("input[name=add]").prop("onclick");
                    oldclick=jQuery("input[name=add]").get(0).attributes.onclick.value;
                    jQuery("input[name=add]").off("click");
                    jQuery("input[name=add]").prop("onclick","");

					jQuery("input[name=add]").click(function(event){
	                    event.preventDefault();
	                    isAdd=true;
	                    sendcalculation();
                    });
                    //jQuery("input[name=add]").hide("fade");

                });

                function sendcalculation(){

                //jQuery("input[name=add]").hide("fade");

                var selects = jQuery("#hikashop_product_custom_item_info").find("select");
 				jQuery("form[name=calculatorform]").append(jQuery("#hikashop_product_custom_item_info").clone());




                //var selects = jQuery(".hikashop_product_custom_item_value").find("select");
                //console.log(selects);
                jQuery(selects).each(function(i) {
                    var select = this;
					jQuery("form[name=calculatorform]").find("select").eq(i).val(jQuery(select).val());
					jQuery("form[name=calculatorform]").find("select").eq(i).val();
                });
 				jQuery("form[name=calculatorform]").append(jQuery("#hikashop_product_quantity_main").clone());
                 jQuery.post("'.JRoute::_('index.php').'", jQuery("form[name=calculatorform]").serialize()).done(function(data){



                        if(data!=""){
                            jQuery("#calc_result").html(data);
							//console.log(jQuery("input[name=hiddencalculatedprice]").val());

                           // jQuery("#calculatedprice").removeAttr("value");
							/*jQuery("#hikashop_product_price_main").hide();
							jQuery(".hikashop_item_calculatedprice_line").hide();*/
							
							if(jQuery("input[name=hiddencalculatedprice]").val()!=""){
							//jQuery("#calculatedprice").val(jQuery("input[name=hiddencalculatedprice]").val());
							jQuery("input[name=\"data[item][calculatedprice]\"]").val(jQuery("input[name=hiddencalculatedprice]").val());
							
							jQuery(".hikashop_product_price").html(jQuery("input[name=hiddencalculatedpriceformat]").val());
							                            }
							
							
							if(jQuery("input[name=hiddencalculatedqty]").val()!="")                 		
							jQuery("input[name=quantity]").val(jQuery("input[name=hiddencalculatedqty]").val());
							
							
							jQuery("input[name=\"data[item][calculatedparams]\"]").val(jQuery("input[name=hiddencalculatedparams]").val());
							
							//jQuery(".hikashop_item_calculatedprice_line").show();
							//jQuery("#calculatedpricecontrol").val(jQuery("input[name=hiddencalculatedpricecontrol]").val());
							
							jQuery("input[name=\"data[item][calculatedpricecontrol]\"]").val(jQuery("input[name=hiddencalculatedpricecontrol]").val());
							jQuery("form[name=calculatorform]").find("#hikashop_product_custom_item_info").remove();
							jQuery("form[name=calculatorform]").find("#hikashop_product_quantity_main").remove();

                            if(isAdd){	
                 				var issubmit;
                            	oldclick=oldclick.replace(/return/g,"issubmit= ");
                            	eval(oldclick);
                                if(issubmit){
                                	jQuery("input[name=add]").closest("form").submit();                                   
                                }                                   
                            }
                        }

                        isAdd=false;
                    });
                }</script>';			
				echo '<form name="calculatorform" style="display:none;" >
				<input type="hidden" name="option" value="com_calcbuilder" />
				<input type="hidden" name="controller" value="calcbuilder" />
				<input type="hidden" name="format" value="raw" />
				<input type="hidden" name="task" value="hikaplugin" />
	            <input type="hidden" name="id" value="'.$idobj.'" />
				<input type="hidden" name="idhikaproduct" value="'.$productid.'" />';
				echo JHtml::_( 'form.token' ).'	</form>	';
				echo '<div id="btcalculator"><input type="button" class="btn button hikashop_cart_input_button" name="calculatepricebtn" value="'.$this->params->get('btn_text','Get Price').'" onclick="sendcalculation();"></div>';
				echo '<div style="display:block" id="calc_result"></div>';
			endif;
		}
		foreach($product_page_parts as $parts){
			echo $parts;
		}
	}
}