<?php

class ControllerAffiliateCategory extends Controller {
	public function index()
	{

        $category_id = 7326;

		if (isset($this->request->get['category_id'])) {
			$category_id = (int)$this->request->get['category_id'];
		}


        if (isset($this->request->get['tracking'])) {
			$tracking_code = $this->request->get['tracking'];
            $affiliate_info =$this->db->query("SELECT * FROM ". DB_PREFIX."affiliate WHERE code = '". $tracking_code."' LIMIT 1 ")->row; 
            $affiliate_id = $affiliate_info['affiliate_id'];
        } else {
			$affiliate_id = 0;
		}

	    $createCache = false;
	    $cacheDir = 'affiliate/'.$affiliate_id;

        if (file_exists(DIR_CACHE . $cacheDir.'/category_' . $category_id . '.tpl') && $_SERVER['REMOTE_ADDR']!="182.187.60.173") {
            $this->response->setOutput($this->load->view( DIR_CACHE . $cacheDir.'/category_' . $category_id));
            return;
        }
        else {
            $createCache = true;
        }

        $data['category_id'] = $category_id;

        if($this->config->get('config_cdn_link')){
            $config_url = $this->config->get('config_cdn_link') . 'image/';
        }else{
            if ($this->request->server['HTTPS']) {
                $config_url = $this->config->get('config_ssl') . 'image/';
            } else {
                $config_url = $this->config->get('config_url') . 'image/';
            }
        }

        //dataLayer
        if (isset($this->session->data['customer_id']) && !empty($this->session->data['customer_id'])) {
            $data['dataLayer']['customer_id'] = $this->session->data['customer_id'];
            $data['dataLayer']['userType'] = 'member';

            $this->load->model('account/customer');

            $customerData = $this->model_account_customer->getCustomer($data['dataLayer']['customer_id']);
            $data['dataLayer']['emailHash'] = sha1($customerData['email']);

        }
        else {
            if (isset($_COOKIE['guest_id']) && !empty($_COOKIE['guest_id'])) {
                $guestId = $_COOKIE['guest_id'];
            }
            else {
                $guestId = rand(500000,999999);
                setcookie('guest_id', $guestId,time()+60*60*24*30, '/');
            }
			
            $data['dataLayer']['customer_id'] = $guestId;
            $data['dataLayer']['userType'] = 'guest';
            $data['dataLayer']['emailHash'] = '';
        }
        //dataLayer End

		$this->load->language('product/category');
		$this->load->model('catalog/category');
		$this->load->model('catalog/product');
		$this->load->model('tool/image');
		$this->load->model('affiliate/affiliate');

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        if (isset($this->request->get['limit'])) {
            $limit = (int)$this->request->get['limit'];
        } else {
            $limit = 60;
        }

        if (isset($this->request->get['filter'])) {
            $filter = $this->request->get['filter'];
        } else {
            $filter = '';
        }
        
        //breadcrumbs data
        $this->load->language('common/header');

        if ($this->request->server['HTTPS']) {
        $server = $this->config->get('config_ssl');
        } else {
        $server = $this->config->get('config_url');
        }
        $data['base'] = $server;
        $data['text_home'] = $this->language->get('text_home');
        
		$data['breadcrumbs'] = array();
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => ''
		);

        $data['tracking_code'] = $affiliate_info['code'];

		$data['sub_category_id'] = '';
		$data['sub_category_id2'] = '';

        $data['all_categories'] = array();
        $data['sub_categories'] = array();
        $data['sub_categories2'] = array();


         //  get categoties list for breadcrumbs

            $getCategoryPaths = $this->model_catalog_category->getCategoryPath($category_id);

            $json_bread=array();
            //Main Category
            if(isset($getCategoryPaths[0])){
                $json_bread[] = array(
                    'text' => $getCategoryPaths[0]['name'],
                    'href' => $getCategoryPaths[0]['href'],
                );
            }

            //Sub Category
            if(isset($getCategoryPaths[1])){
                $json_bread[] = array(
                    'text' => $getCategoryPaths[1]['name'],
                    'href' => $getCategoryPaths[1]['href'],
                );
            }

            //Sub Category 2
            if(isset($getCategoryPaths[2])){
                $json_bread[] = array(
                    'text' => $getCategoryPaths[2]['name'],
                    'href' => $getCategoryPaths[2]['href'],
                );

             }

            $breadcumb_new[]=array("@type"=> "ListItem",
                 "position"=> 1,
                 "name"=> 'Anasayfa',
                 "item"=> $server);

            $count=2;
            foreach($json_bread as $bread){
                $breadcumb_new[] = array(
                 "@type"=> "ListItem",
                 "position"=> $count,
                 "name"=> $bread['text'],
                 "item"=> $server.$bread['href']);
                $count++;
            }

        $data['breadcumb_encoded']=  json_encode($breadcumb_new);

        //  get categoties list for breadcrumbs

		$route = 'product/category';
		//$path = 'path=' . $this->request->get['path'];

        $campaig_not_include_ids =  explode(',', $this->config->get('promotion')['exclude_campaign_product_ids']);


        $data['campaign_text'] = false;
        if(isset($this->session->data['campaign'])){
            $data['campaign_text'] = true;
        }


            $data['category_list'] = array();
		    if($data['sub_category_id2'] == ''){
                $category_list = $this->model_catalog_category->getCategories($category_id);
                foreach ($category_list as $list_item){

                    if ($list_item['image']) {
                        $thumb = $this->model_tool_image->resize($list_item['image'], $this->config->get($this->config->get('config_theme') . '_image_category_width'), $this->config->get($this->config->get('config_theme') . '_image_category_height'));
                    } else {
                        $thumb = '';
                    }

                    if ($list_item['banner']) {
                        $banner = $this->model_tool_image->resize($list_item['banner'], 550, 393);
                    } else {
                        $banner = '';
                    }

                    $bs_products = $this->model_catalog_category->getBestSellerProductsByCategory($list_item['category_id']);

                    foreach ($bs_products as $bs_product){
                        
                        
                         $color=$bs_product['attribute_groups'][1]['attribute'][0]['name'];
                        $collection=$bs_product['attribute_groups'][0]['attribute'][0]['name'];
                        
                        
                        if ($bs_product['image']) {
                            $bs_image = $this->model_tool_image->resize($bs_product['image'], $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height'), 'product_list');
                        } else {
                            $bs_image = $this->model_tool_image->resize('placeholder.png', $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height'));
                        }

                        if ($bs_product['image_vitrin']) {
                            $bs_image = $config_url . $bs_product['image_vitrin'];
                        }

                        if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                            $bs_price = $this->currency->format($this->tax->calculate($bs_product['price'], $bs_product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                        } else {
                            $bs_price = false;
                        }

                        if ((float)$bs_product['special']) {
                            $bs_special = $this->currency->format($this->tax->calculate($bs_product['special'], $bs_product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                        } else {
                            $bs_special = false;
                        }
                        
                        
                        $categorti_id_info = $this->model_catalog_product->getCategoryByProductId($bs_product['product_id']);

                        $campaig_not_include = false;
                        if(in_array($bs_product['product_id'], $campaig_not_include_ids)){
                            $campaig_not_include = true;
                        }

                        $best_seller_products[] = array(
                            'product_id' => $bs_product['product_id'],
                            'model' => $bs_product['model'],
                            'product_type' => $bs_product['product_type'],
                            'thumb' => $bs_image,
                            'quantity' => $bs_product['quantity'],
                            'name' => $bs_product['name'],
                            'price' => $bs_price,
                            'special' => $bs_special,
                            'percentsaving' => $bs_product['special'] ? round((($bs_product['price'] - $bs_product['special']) / $bs_product['price']) * 100, 0) : '',
                            'href' => $bs_product['href'],
                            'currency' => $this->session->data['currency'],
                            'color'=>$color,
                            'collection'=>$collection,
                            'campaig_not_include' => $campaig_not_include
                        );
                    }

                    $data['category_list'][] = array(
                        'thumb' => $thumb,
                        'banner' => $banner,
                        'name' => $list_item['name'],
                        'description' => html_entity_decode($list_item['description'], ENT_QUOTES, 'UTF-8'),
                        'href' => $list_item['href'],
                        'products' => $best_seller_products
                    );
                }
            }
			
            $affiliate_content = $this->db->query("SELECT * FROM ". DB_PREFIX ."affiliate_content WHERE affiliate_id = '". (int)$affiliate_id."'")->row;
        
            if(!empty($affiliate_content)) {
                $data['affiliate_content']['show'] = true;
            } else {
                $data['affiliate_content']['show'] = false;
            }
            
            $data['affiliate_content']['media'] = (isset($affiliate_content['content_media'])) ? $affiliate_content['content_media'] : "";
            $data['affiliate_content']['title'] = (isset($affiliate_content['content_title'])) ? $affiliate_content['content_title'] : "";
            $data['affiliate_content']['text']  = (isset($affiliate_content['content_text']))  ? $affiliate_content['content_text']  : "";
    
    
            if($data['affiliate_content']['media']!=="") {
                $data['affiliate_content']['media'] = 'image/affiliate/media/' . $data['affiliate_content']['media'];
            }

            
            $this->document->setTitle( $affiliate_info['firstname'] . ' ' . $affiliate_info['lastname'] . ' Seçimleri');
			
            //$this->document->setDescription($category_info['meta_description']);
			
            //$this->document->setKeywords($category_info['meta_keyword']);

			$data['heading_title'] = $affiliate_info['firstname'] . ' ' . $affiliate_info['lastname'] . ' Seçimleri';

			$data['text_refine'] = $this->language->get('text_refine');
			$data['text_empty'] = $this->language->get('text_empty');
			$data['text_quantity'] = $this->language->get('text_quantity');
			$data['text_manufacturer'] = $this->language->get('text_manufacturer');
			$data['text_model'] = $this->language->get('text_model');
			$data['text_price'] = $this->language->get('text_price');
			$data['text_tax'] = $this->language->get('text_tax');
			$data['text_points'] = $this->language->get('text_points');
			$data['text_compare'] = '';
			$data['text_sort'] = $this->language->get('text_sort');
			$data['text_default'] = $this->language->get('text_default');
			$data['text_limit'] = $this->language->get('text_limit');
			$data['text_filter'] = $this->language->get('text_filter');

			$data['text_order_private'] = $this->language->get('text_order_private');
			$data['text_order_critical'] = $this->language->get('text_order_critical');
			$data['text_bestsaller'] = $this->language->get('text_bestsaller');
			$data['text_bestview'] = $this->language->get('text_bestview');
			$data['text_in_stock'] = $this->language->get('text_in_stock');
			$data['text_order_in_stock'] = $this->language->get('text_order_in_stock');

			$data['button_cart'] = $this->language->get('button_cart');
			$data['button_wishlist'] = $this->language->get('button_wishlist');
			$data['button_compare'] = $this->language->get('button_compare');
			$data['button_continue'] = $this->language->get('button_continue');
			$data['button_list'] = $this->language->get('button_list');
			$data['button_grid'] = $this->language->get('button_grid');
			$data['quick_view'] = $this->language->get('quick_view');

            $data['text_discount'] = $this->language->get('text_discount');
            $data['text_view'] = $this->language->get('text_view');
            $data['text_quick_view'] = $this->language->get('text_quick_view');
            $data['text_no_stock'] = $this->language->get('text_no_stock');
            $data['text_product_done'] = $this->language->get('text_product_done');

/*
			if ($category_info['image']) {
				$data['thumb'] = $this->model_tool_image->resize($category_info['image'], $this->config->get($this->config->get('config_theme') . '_image_category_width'), $this->config->get($this->config->get('config_theme') . '_image_category_height'));
			} else {
				$data['thumb'] = '';
			}

            if ($category_info['banner']) {
                $data['banner'] = $this->model_tool_image->resize($category_info['banner'], $this->config->get($this->config->get('config_theme') . '_image_category_width'), $this->config->get($this->config->get('config_theme') . '_image_category_height'));
            } else {
                $data['banner'] = '';
            }
*/
            $data['show_products'] = 1;
/*
			$this->document->setFBog($data['thumb']);
*/
            //$data['description'] = html_entity_decode($category_info['description'], ENT_QUOTES, 'UTF-8');
			$data['compare'] = '';

			$url = '';

			$data['categories'] = array();

			$data['products'] = array();

            $sort = 'p.sort_order';
            $order = 'ASC';

            $data['filters'] = array();

            /*$filters = $this->model_catalog_category->getProductToCategoryFilters($category_id, $category_info['filter_group_id']);

            foreach ($filters as $filter_row){
                $data['filters'][] = array(
                    'filter_id' => $filter_row['filter_id'],
                    'filter_image' => $this->model_tool_image->resize($filter_row['image'],500,500),
                    'filter_sub_image' => $this->model_tool_image->resize($filter_row['sub_image'],500,500),
                    'filter_name' => $filter_row['name'],
                    'filter_href' => $this->url->link('product/category' , 'path=' . $category_id . '&filter=' . $filter_row['filter_id']),
                );
            }*/

            /*
            if($data['filters']){


                foreach ($this->model_catalog_category->getPreviewFilters($category_info['filter_group_id']) as $filter_id){
                    $get_preview_filters[] = $filter_id['filter_id'];
                }

                $filter = $filter ? $filter : implode(',', $get_preview_filters);
                $get_filter_info = $this->model_catalog_category->getFilterInfo($filter);
                $data['filter_info'] = array(
                    'filter_id' => $get_filter_info['filter_id'],
                    'name' => $get_filter_info['name'],
                    'image' => $config_url . $get_filter_info['sub_image'],
                    'html_code' => $get_filter_info['html_code'],
                );
            }


			$filter_data = array(
				'filter_category_id' => $category_id,
				'filter_sub_category' => $this->config->get('config_subcategory_show'),
				'filter_filter' => $filter,
				'sort' => $sort,
				'order' => $order,
				'start' => ($page - 1) * $limit,
				'limit' => $limit,
				'product_showcase' => 1,
			);
*/
            //********
            //ddd($filter_data);


            // if ürün sayısı > 0 yap
            $product_total = 0;
            //$results = $this->model_catalog_product->getProducts($filter_data);
            
            $category = $this->model_catalog_category->getCategory($category_id);
            $parent_category = $this->model_catalog_category->getCategory($category['parent_id']);

            $data['page_build']  = 'model';
    
            $model_categories = [
                '1177', #Apple
                '1257', #Samsung
                '1404', #Huawei
                '1662', #Xiaomi
                '3406', #Oppo
                '4792', #Realme
            ];

            if(!in_array($category['parent_id'], $model_categories)) {
                $data['page_build'] = 'product';
            }

            $filter_data = array(
				'filter_category_id' => $category_id,
                'filter_affiliate' => $affiliate_id,
                'filter_build' => $data['page_build'],
				//'filter_sub_category' => $this->config->get('config_subcategory_show'),
				//'filter_filter' => $filter,
				//'sort' => $sort,
				//'order' => $order,
				//'start' => ($page - 1) * $limit,
				//'limit' => $limit,
				'product_showcase' => 1,
			);
            $results = $this->model_affiliate_affiliate->getProducts($filter_data);
            
            $show_color_attribute = true;
                
			foreach ($results as $result) {
			               
			    $color=$result['attribute_groups'][1]['attribute'][0]['name'];
			    $collection=$result['attribute_groups'][0]['attribute'][0]['name'];

                    if ($result['image']) {
                        $image = $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height'), 'product_list');
                    } else {
                        $image = $this->model_tool_image->resize('placeholder.png', $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height'));
                    }

                    if ($result['image_vitrin']) {
                        $image = $config_url . $result['image_vitrin'];
                    }

                    $images = $this->model_catalog_product->getProductImages($result['product_id']);
                    $data['images'] = array();
                    foreach ($images as $img) {
                        $data['images'][] = array(
                            'popup' => $this->model_tool_image->resize($img['image'], $this->config->get($this->config->get('config_theme') . '_image_popup_width'), $this->config->get($this->config->get('config_theme') . '_image_popup_height'),'product_list'),
                            'popup1' => $this->model_tool_image->resize($img['image'], $this->config->get($this->config->get('config_theme') . '_image_thumb_width'), $this->config->get($this->config->get('config_theme') . '_image_thumb_height'),'product_list'),
                            'thumb' => $this->model_tool_image->resize($img['image'], $this->config->get($this->config->get('config_theme') . '_image_additional_width'), $this->config->get($this->config->get('config_theme') . '_image_additional_height'),'product_list')
                        );
                    }

                    if (isset($images[0]['image']) && !empty($images)) {
                        $images = $images[0]['image'];
                    } else {
                        $images = $image;
                    }

                    if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                        $soft_price = $this->currency->format($result['price'], $this->session->data['currency']);
                    } else {
                        $soft_price = false;
                    }

                    if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                        $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                    } else {
                        $price = false;
                    }

                    if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                        if ($result['currency_id'] == 1) {
                            $soft_currency_price = $this->currency->format($result['price'], 'TRY');
                        } else {
                            $soft_currency_price = $this->currency->format($result['price'], 'USD');
                        }
                    } else {
                        $soft_currency_price = false;
                    }

                    if ((float)$result['special']) {
                        $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
                        if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                            if ($result['currency_id'] == 1) {
                                $soft_currency_special = $this->currency->format($result['special'], 'TRY');
                            } else {
                                $soft_currency_special = $this->currency->format($result['special'], 'USD');
                            }
                        } else {
                            $soft_currency_special = false;
                        }
                    } else {
                        $special = false;
                        $soft_currency_special = false;
                    }

                    if ($this->config->get('config_tax')) {
                        $tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price'], $this->session->data['currency']);
                    } else {
                        $tax = false;
                    }

                    if ($this->config->get('config_review_status')) {
                        $rating = (int)$result['rating'];
                    } else {
                        $rating = false;
                    }

                    $options = array();

                    //$p_related = $this->model_catalog_product->getProductRelated($result['product_id']);

                    $product_related = array();

                    $collection_color = $this->model_catalog_product->getCollectionColor($result['product_id'], $result['model'], $category_id, $show_color_attribute);

                    for ($i=0; $i < count($collection_color); $i++) { 
                        $collection_color[$i]['href'] = $collection_color[$i]['href'] . '&tracking='.$affiliate_info['code']; 
                    }

                $campaig_not_include = false;
                if(in_array($result['product_id'], $campaig_not_include_ids)){
                    $campaig_not_include = true;
                }
                   
                    $data['products'][] = array(
                        'product_id' => $result['product_id'],
                        'model' => $result['model'],
                        'product_type' => $result['product_type'],
                        'thumb' => $image,
                        'no_cache_image' => $config_url . $result['image'],
                        'quantity' => $result['quantity'],
                        'manufacturer' => $result['manufacturer'],
                        'images' => $data['images'],
                        'thumb_swap' => '',
                        'name' => $result['name'],
                        'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get($this->config->get('config_theme') . '_product_description_length')) . '..',
                        'price' => $price,
                        'special' => $special,
                        'soft_currency_price' => $soft_currency_price,
                        'soft_currency_special' => $soft_currency_special,
                        'percentsaving' => '',
                        'tax' => $tax,
                        'minimum' => $result['minimum'] > 0 ? $result['minimum'] : 1,
                        'rating' => $result['rating'],
                        'quick' => '',
                        'href' => $result['href'],
                        'options' => $options,
                        'product_related' => $product_related,
                        'collection_color' => $collection_color,
                        'currency'=>$this->session->data['currency'],
                        'color'=>$color,
                        'collection'=>$collection,
                        'campaig_not_include' => $campaig_not_include,
                    );
                }

            $lang_id = $this->config->get('config_language_id');
            if($this->config->get('digitcart_load_products_custom_html_status')){
                $dc_loading_icon = $this->config->get('digitcart_load_products_loading_icon');
                if(!empty($dc_loading_icon[$lang_id])){
                    $dc_loading_icon = html_entity_decode($dc_loading_icon[$lang_id], ENT_QUOTES, 'utf-8');
                } else {
                    $dc_loading_icon = '';
                }
            } else {
                $dc_loading_icon = '<div style="text-align:center;font-size:40px;margin:20px 0;clear:both"><i class="fa fa-spin fa-spinner" style="font-size:40px;"></i></div>';
            }

            $data['dc_loading_icon'] = $dc_loading_icon;


			$data['pagination'] = '';
			$data['results'] = 0;

		/*	if ($page == 1) {
				$this->document->addLink(HTTPS_SERVER . $category_info['href'], 'canonical');
			} elseif ($page == 2) {
				$this->document->addLink(HTTPS_SERVER . $category_info['href'], 'prev');
			} else {
				$this->document->addLink(HTTPS_SERVER . $category_info['href'] . '&page=' . ($page - 1) , 'prev');
			}*/
        /*
			if ($limit && ceil($product_total / $limit) > $page) {
				$this->document->addLink($category_info['href'] . '&page=' . ($page + 1), 'next');
			}
*/

			$data['order'] = $order;

			$data['continue'] = '';

			$data['column_left'] = $this->load->controller('common/column_left');
			$data['column_right'] = $this->load->controller('common/column_right');
			$data['content_top'] = $this->load->controller('common/content_top');
			$data['content_bottom'] = $this->load->controller('common/content_bottom');

            $data['footer'] = $this->load->controller('common/footer');

            $data['header'] = $this->load->controller('common/header');

			/*$data['header'] = $this->cache->cache_get('category_header' . $category_id, 'category_header/');
			if (!$data['header']) {
			    $data['header'] = $this->load->controller('common/header');
			    $this->cache->cache_set('category_header' . $category_id, $data['header'], 'category_header/');
			}*/


            $data['show_color_attribute'] = $show_color_attribute;

	        $data['CretioOneTag_status'] = $this->config->get('CretioOneTag_status');
            $data['CretioOneTag_id'] = $this->config->get('CretioOneTag_id');
               
            if ($createCache) {

                if (!file_exists(DIR_CACHE . 'affiliate')) {
                    mkdir(DIR_CACHE . 'affiliate');
                }

                if (!file_exists(DIR_CACHE . $cacheDir)) {
                    mkdir(DIR_CACHE . $cacheDir);
                }

                file_put_contents(DIR_CACHE . $cacheDir.'/category_' . $category_id . '.tpl',
                $this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/affiliate_category' , $data));
            }


            if (file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/affiliate_category'. '.tpl')) {
                $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/product/affiliate_category', $data));
            } else {
                $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/product/affiliate_category', $data));
            }


	}
}

?>