<?php
class ControllerCatalogCostChangeByCategory extends Controller {
	
private $error = array();


public function index() {
	$this->document->setTitle('Kategori Bazlı Fiyat Etkilemesi');
	$this->getForm();
}


public function getMainCategories (){ 
	$categories = $this->db->query("
	SELECT
	cd.`name`, 
	c.parent_id, 
	c.category_id,
	c.sort_order,
	c.status
	FROM
	" . DB_PREFIX . "category c
	INNER JOIN
	" . DB_PREFIX . "category_description cd
	ON 
	c.category_id = cd.category_id
	WHERE 	c.parent_id = 0	 AND  c.status = 1  AND cd.language_id = '".(int)$this->config->get('config_language_id') ."'
	ORDER BY c.sort_order ASC
	");

	return $categories->rows;
}

 
public function getParentCategories ($category_id){
	$categories = $this->db->query("
	SELECT
		cd.`name`, 
		c.parent_id, 
		c.category_id,
		c.sort_order,
		c.status
	FROM
		" . DB_PREFIX . "category c
	INNER JOIN
		" . DB_PREFIX . "category_description cd
	ON 
			c.category_id = cd.category_id
	WHERE 	c.parent_id = '".$category_id."' AND  c.status = 1 AND cd.language_id = '".(int)$this->config->get('config_language_id') ."'
	ORDER BY c.sort_order ASC

	");
	return $categories->rows;
}

 
	public function add() {
		
  if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {

	$clean_spacial      = (isset($this->request->post['clean_spacial'])) ? $this->request->post['clean_spacial'] : null;
	$cat_list           = $this->request->post['cat_list'];
	$normal_price       = $this->request->post['normal_price'];
	$percent_price      = $this->request->post['percent_price'];
	$normal_spacial     = $this->request->post['normal_spacial'];
	$percent_spacial    = $this->request->post['percent_spacial'];

	$list_of_price_and_spacial = array();

	$products                 = array();
	$cat_list_ids             = join(",",$cat_list);
	$cat_list_products_query  = "SELECT ptc.product_id FROM ".DB_PREFIX."product_to_category ptc";

	if(isset($this->request->post['attribute'])) {
		$cat_list_products_query.= " LEFT JOIN " . DB_PREFIX . "product_attribute pa ON (ptc.product_id = pa.product_id)";
	}

	$cat_list_products_query .=  "WHERE ptc.category_id IN (".$cat_list_ids.")";

	if(isset($this->request->post['attribute'])) {
		$attribute = $this->request->post['attribute'];
		$attribute = implode(',', $attribute);

		$cat_list_products_query.= " AND pa.attribute_id IN (".$attribute.")";
	}


	$cat_list_products_query = $this->db->query($cat_list_products_query);

	$cat_list_products        = $cat_list_products_query->rows;

	foreach($cat_list_products as $cat_list_product){

		$products[] = $cat_list_product['product_id'];

	}

	$last_products = array_unique($products);
 
	$list_of_price_and_spacial['normal_price']          = $normal_price;
	$list_of_price_and_spacial['percent_price']         = $percent_price;
	$list_of_price_and_spacial['normal_spacial']        = $normal_spacial;
	$list_of_price_and_spacial['percent_spacial']       = $percent_spacial;
	$list_of_price_and_spacial['category_list']         = $cat_list;
	
	
	if($clean_spacial){

		foreach($last_products as $product){
	
			
			$this->db->query("DELETE FROM " . DB_PREFIX . "product_special WHERE product_id='".$product."'");
	
		}
	
		$list_of_price_and_spacial['clean'] = $last_products;
	
		$date     = date('Y-m-d');
				
		$this->db->query("
			
			INSERT IGNORE INTO " . DB_PREFIX . "product_price_change 
			
			SET 
			data              = '".json_encode($list_of_price_and_spacial)."',
			date              = '".$date."'
			
		");
	
		$product_price_change_id = $this->db->getLastId();
	
		$this->response->redirect($this->url->link('catalog/cost_change_by_category', 'token=' . $this->session->data['token'] .'&product_price_change_id='.$product_price_change_id.'  ', true));
	
	
		}else{



    foreach($last_products as $last_product){
		
	   
		$get_product_query        = $this->db->query("SELECT p.product_id,p.price FROM ".DB_PREFIX."product p WHERE p.product_id = '".$last_product."' ");
		$get_product_data         = $get_product_query->row ;
		$product_price            = $get_product_data['price'] ;
		$product_product_id       = $get_product_data['product_id'] ;

		$current_price = 0;
 
		if( $normal_price ){

			if (  (strpos($normal_price, '+') !== false)  ||  (strpos($normal_price, '-') !== false)) {
				
					
				$current_price = $product_price + ($normal_price);
 
			}else{

				$current_price = $normal_price  ;
			}
 
		}


		if( $percent_price ){

	 
			if (  (strpos($normal_price, '+') !== false)  &&  (strpos($normal_price, '-') !== false)) {


			}else{

				$current_price = $product_price + ($product_price * abs($percent_price) / 100);

			}	
			 
					
			if (  (strpos($percent_price, '+') !== false)) {
				
					
				$current_price = $product_price + ($product_price * abs($percent_price) / 100);
 
			}

			if (  (strpos($percent_price, '-') !== false)) {
				
					
				$current_price = $product_price - ($product_price * abs($percent_price) / 100);
 
			}
			

			
		}

		if($current_price > 0){
			
		   $this->db->query(" UPDATE " . DB_PREFIX . "product  SET price = '".$current_price."' WHERE product_id = '".$product_product_id."' ");
		
		   //fiyati güncellenen ürünler için log
	
		   $list_of_price_and_spacial['price'][] = array('product_id' => ''.$product_product_id.'' , 'new_price' => ''.$current_price  , 'old_price' => ''.$product_price.'' );
		   
		}	
 

		$current_spacial_price = 0;

		$customer_group_id = $this->config->get('config_customer_group_id');


		if( $normal_spacial ){
			
			$current_spacial_price = $normal_spacial;

		}
 
		if( $percent_spacial ){

			$current_spacial_price = $product_price - ($product_price * abs($percent_spacial) / 100);
		}

		if($current_spacial_price > 0 ){

			$timeonedayago     = date('Y-m-d', strtotime("-1 day"));
			$timeoneyearslater = date('Y-m-d', strtotime("+365 day"));

			$this->db->query("DELETE FROM " . DB_PREFIX . "product_special WHERE product_id='".$product_product_id."'");
			$this->db->query("
				
				INSERT IGNORE INTO " . DB_PREFIX . "product_special 
				
				SET 
				product_id        = '".$product_product_id."',
				customer_group_id = '".$customer_group_id."',
				priority          = 0 ,
				price             = '".$current_spacial_price."',
				date_start        = '".$timeonedayago."',
				date_end          = '".$timeoneyearslater."'
 
			");
			
			// indirimli eklenenler için log
			$list_of_price_and_spacial['special'][] = array('product_id' => ''.$product_product_id.'' , 'price' => ''.$current_spacial_price );
		}
 
  
		
		 
	}   
	
			$date     = date('Y-m-d');
			
			$this->db->query("
				
				INSERT IGNORE INTO " . DB_PREFIX . "product_price_change 
				
				SET 
				data              = '".json_encode($list_of_price_and_spacial)."',
				date              = '".$date."'
				
 
			");
			$product_price_change_id = $this->db->getLastId();
	
	$this->response->redirect($this->url->link('catalog/cost_change_by_category', 'token=' . $this->session->data['token'] .'&product_price_change_id='.$product_price_change_id.'  ', true));
	
    }
    }
	 
	$this->getForm();
	
    }



public function tax() {
		
	$json       = array();
			
	$price_value   = $this->request->post['price_value'];
	$tax           = $this->request->post['tax_value'];
	$tax_type      = $this->request->post['tax_type'];

	if($tax_type == 'with_tax'){
		
	$result          = $price_value  / ( 1 + ($tax / 100));


	}else{
		
	$result          = $price_value + ($price_value * ($tax / 100));

	}

	$json['value']  = number_format($result , 2);

	$this->response->addHeader('Content-Type: application/json');
	$this->response->setOutput(json_encode($json));



}

	
		
    public function getForm() {
 
		
		$data['heading_title'] = 'Kategori Bazlı Fiyat Etkilemesi';
		$data['text_list']     = 'Kategori Bazlı Değişim';
        $data['token']         = $this->session->data['token'];
		$data['header']        = $this->load->controller('common/header');
		$data['column_left']   = $this->load->controller('common/column_left');
		$data['footer']        = $this->load->controller('common/footer');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

//tüm kategorileri getir
 
		$data['NewCategories'] = array();
  
		foreach ($this->getMainCategories () as $getMainCategori) {
 
			$children_data = array();
			
			$children      = $this->getParentCategories ($getMainCategori['category_id']);

			foreach ($children as $child) {
			 
				$children_child_data = array();
				
				$children_childs     = $this->getParentCategories ($child['category_id']);

					foreach ($children_childs as $children_child) {

							
						$children_child_data[] = array( 'catname'  => $child['name'], 'name'  => $children_child['name'], 'category_id' => $children_child['category_id']  );
					}

				
				$children_data[]       = array( 'catname'  => $getMainCategori['name'] , 'name'  => $child['name'] , 'category_id' => $child['category_id'] , 'children' =>  $children_child_data);
			}
			
		
			$data['NewCategories'][] = array( 'name' => $getMainCategori['name'] , 'category_id' => $getMainCategori['category_id'] , 'children' =>  $children_data);
 
		}


		$config_language_id = (int)$this->config->get('config_language_id'); 
		$data['attributes'] = $this->db->query("select attribute_id,name from ".DB_PREFIX."attribute_description WHERE language_id = $config_language_id")->rows;



		if (isset($this->request->get['filter_attribute'])) {
			$filter_attribute = $this->request->get['filter_attribute'];
		} else {
			$filter_attribute = "";
		}
		
		$filter_attribute_data = array();
		if (strpos($filter_attribute, ',') !== false) {
			$filter_attribute_data = explode( ',' , $filter_attribute);
		}else{
			$filter_attribute_data = array($filter_attribute);
		}

		$data['filter_attribute']    = $filter_attribute_data;

        $data['action'] = $this->url->link('catalog/cost_change_by_category/add', 'token=' . $this->session->data['token'].'', true);

		$data['product_price_change'] = '';

		if(isset($this->request->get['product_price_change_id'])){
			
			$product_price_change_id   = $this->request->get['product_price_change_id'];  
			$product_price_change_data = $this->db->query("SELECT * FROM ".DB_PREFIX."product_price_change  WHERE  id = '".$product_price_change_id."'");
			$product_price_change      = $product_price_change_data->row;
			$product_price_change      = json_decode($product_price_change['data'],true);
			
			$data['product_price_change'] = $product_price_change;
			
		}

        if(file_exists(DIR_LOCAL_TEMPLATE .'catalog/cost_change_by_category_form.tpl')){
            $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'catalog/cost_change_by_category_form', $data));
        }else{ 
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'catalog/cost_change_by_category_form', $data));
        }
		
		
	}


	protected function validateForm() {
		
		
		if (!$this->user->hasPermission('modify', 'catalog/cost_change_by_category')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		$clean_spacial      = (isset($this->request->post['clean_spacial'])) ? $this->request->post['clean_spacial'] : null;;
		$cat_list           = $this->request->post['cat_list'];
		$normal_price       = $this->request->post['normal_price'];
		$percent_price      = $this->request->post['percent_price'];
		$normal_spacial     = $this->request->post['normal_spacial'];
		$percent_spacial    = $this->request->post['percent_spacial'];
 

		if ( !$clean_spacial ) {
			 
			if (  utf8_strlen($normal_price == 0) &&  utf8_strlen($percent_price == 0) && utf8_strlen($normal_spacial == 0)  && utf8_strlen($percent_spacial == 0) ) {
				$this->error['warning'] = 'Lütfen! Boş Bırakmayınız.';
			}


		}

		if ( !is_array($cat_list) && empty($cat_list) && count($cat_list) == 0 ) {
			$this->error['warning'] = 'Lütfen! Kategori seçimi yapınız.';
		}

		if (  utf8_strlen($normal_price > 0) &&  utf8_strlen($percent_price > 0)   ) {
			$this->error['warning'] = 'Lütfen! Aynı anda hem normal fiyat hemde yüzde fiyat girmeyiniz.';
		}

		if (  utf8_strlen($normal_spacial > 0)  && utf8_strlen($percent_spacial > 0)   ) {
			$this->error['warning'] = 'Lütfen! Aynı anda hem indirimli normal değer  hemde indirimli yüzde değer girmeyiniz.';
		}

		if ($this->error && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_warning');
		}
		
		return !$this->error;
	}


}
