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

	//////////////////////////////////////////////////////////////////////////////
	//                                                                          //
	//      Set up the Default Values                                           //
	//                                                                          //
	//////////////////////////////////////////////////////////////////////////////

	public function index() {

		$ssl = $this->config->get('config_secure');
		
		$this->load->language('extension/feed/google_product_feed');
		$this->load->model('setting/setting');
		$this->load->model('extension/feed/google_product_feed');

		$this->document->setTitle($this->language->get('heading_title'));

		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];		
			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}
		
		if (isset($this->session->data['error_warning'])) {
			$data['error_warning'] = $this->session->data['error_warning'];		
			unset($this->session->data['error_warning']);
		} else {
			$data['error_warning'] = '';
		}

		$this->model_extension_feed_google_product_feed->checkGPFTable();

		if(isset($this->request->files['import'])) {
			if (is_uploaded_file($this->request->files['import']['tmp_name']) && $this->user->hasPermission('modify', 'extension/feed/google_product_feed')) {
//				$csv_errors = $this->model_extension_feed_google_product_feed->validateCsv($this->request->files['import']['tmp_name']);
				$csv_errors = false;
				
				if($csv_errors) {
					// Copy File
					copy($this->request->files['import']['tmp_name'], DIR_LOGS . 'csv_import.csv');
					// Add errors to session data
					$this->session->data['csv_errors'] = $csv_errors;
					// Call 'choose whether to update' function / page
					$this->response->redirect($this->url->link('extension/feed/google_product_feed/csvErrors', 'user_token=' . $this->session->data['user_token'], true));
				} else {
					$this->model_extension_feed_google_product_feed->importXlsx($this->request->files['import']['tmp_name']);
					$this->session->data['success'] = $this->language->get('text_success');
					$this->response->redirect($this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], true));
				}
			} elseif(!$this->user->hasPermission('modify', 'extension/feed/google_product_feed')) {
				$this->session->data['error_warning'] = $this->language->get('error_permission');
				$this->response->redirect($this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], true));
			} else {
				$this->session->data['error_warning'] = $this->language->get('error_empty');
				$this->response->redirect($this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], true));
			}
		}
		
		if(isset($this->request->get['validate_csv'])) {
			$this->model_extension_feed_google_product_feed->importCsv(DIR_LOGS . 'csv_import.csv');
			unlink(DIR_LOGS . 'csv_import.csv');
			$this->session->data['success'] = $this->language->get('text_success');
			$this->response->redirect($this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], true));
		}
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && ($this->validate())) {
			$sorted_array = array();
			foreach($this->request->post['gpf_custom_labels'] as $custom_labels) {
				$sorted_array[] = $this->sortCustomLabels($custom_labels);
			}
			$this->request->post['custom_labels'] = $sorted_array;

			$this->load->model('setting/setting');
			$this->model_setting_setting->editSetting('gpf', $this->request->post);
			$this->load->model('extension/feed/google_product_feed');
			$this->model_extension_feed_google_product_feed->editSetting($this->request->post['gpf_status']);

			if ($this->request->post['enable_all_products'] == "1") {
					$this->model_extension_feed_google_product_feed->enableAllProducts();
					$data['success'] = 'All products have been enabled for Google Shopping';
			} 
			
			if ($this->request->post['enable_all_products'] == "2") {
					$this->model_extension_feed_google_product_feed->disableAllProducts();
					$data['success'] = 'All products have been disabled for Google Shopping';
			} 
			
			if ($this->request->post['copy_data'] == "0" && $this->request->post['enable_all_products'] == "0" && $this->request->post['generate_product_variants'] == "0" && $this->request->post['split_feed'] == "0") {
				$this->session->data['success'] = $this->language->get('text_success');
				$this->response->redirect($this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'], true));
				
			} elseif ($this->request->post['copy_data'] == "1") {
				if(isset($this->request->post['copy_field'])) {
					if(in_array('Default Google Category', $this->request->post['copy_field'])) {
						$this->model_extension_feed_google_product_feed->copyProductCategory($this->request->post['gpf_copy_to']);
					}
					if(in_array('Condition', $this->request->post['copy_field'])) {
						$this->model_extension_feed_google_product_feed->copyCondition($this->request->post['gpf_copy_to']);
					}
					if(in_array('Out of Stock Status', $this->request->post['copy_field'])) {
						$this->model_extension_feed_google_product_feed->copyOosStatus($this->request->post['gpf_copy_to']);
					}
					if(in_array('Identifier Exists', $this->request->post['copy_field'])) {
						$this->model_extension_feed_google_product_feed->copyIdentifierExists($this->request->post['gpf_copy_to']);
					}
					if(in_array('Size System', $this->request->post['copy_field'])) {
						$this->model_extension_feed_google_product_feed->copySizeSystem($this->request->post['gpf_copy_to']);
					}
					if(in_array('Brand', $this->request->post['copy_field'])) {
						$this->model_extension_feed_google_product_feed->copyManufacturer($this->request->post['gpf_copy_to']);
					}
				}
				if(isset($this->request->post['replace_av_for_order']) && $this->request->post['replace_av_for_order'] == '1') {
					$this->model_extension_feed_google_product_feed->replaceAvForOrder();
				}
				if($this->request->post['gpf_copy_gtin'] != 'Select Field to Copy From') {
					$this->model_extension_feed_google_product_feed->copyGTIN($this->request->post['gpf_copy_gtin'], $this->request->post['gpf_copy_to']);
				}
				if($this->request->post['gpf_copy_mpn'] != 'Select Field to Copy From') {
					$this->model_extension_feed_google_product_feed->copyMPN($this->request->post['gpf_copy_mpn'], $this->request->post['gpf_copy_to']);
				}
				$data['success'] = 'Data has been copied successfully';
			} 
			
		}

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

   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'user_token=' . $this->session->data['user_token'], true),
      		'separator' => false
   		);

   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_extension'),
			'href'      => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'], true),
      		'separator' => ' :: '
   		);

   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], true),
      		'separator' => ' :: '
   		);


		$data['action'] = $this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], true);
		$data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'], true);
		$data['export_csv'] = $this->url->link('extension/feed/google_product_feed/export', 'user_token=' . $this->session->data['user_token'], true);
		$data['import_csv'] = $this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], true);


		// Check Database Table is up to date
		$this->model_extension_feed_google_product_feed->checkGPFTables();

		// Variants from Product Options
		$data['options'] = $this->model_extension_feed_google_product_feed->getOptions();
		
        if (isset($this->request->post['gpf_size_option1'])) {
            $data['gpf_size_option1'] = $this->request->post['gpf_size_option1'];
        } else {
            $data['gpf_size_option1'] = $this->config->get('gpf_size_option1');
        }

        if (isset($this->request->post['gpf_size_option2'])) {
            $data['gpf_size_option2'] = $this->request->post['gpf_size_option2'];
        } else {
            $data['gpf_size_option2'] = $this->config->get('gpf_size_option2');
        }

        if (isset($this->request->post['gpf_size_option3'])) {
            $data['gpf_size_option3'] = $this->request->post['gpf_size_option3'];
        } else {
            $data['gpf_size_option3'] = $this->config->get('gpf_size_option3');
        }

        if (isset($this->request->post['gpf_colour_option'])) {
            $data['gpf_colour_option'] = $this->request->post['gpf_colour_option'];
        } else {
            $data['gpf_colour_option'] = $this->config->get('gpf_colour_option');
        }
		
        if (isset($this->request->post['gpf_material_option'])) {
            $data['gpf_material_option'] = $this->request->post['gpf_material_option'];
        } else {
            $data['gpf_material_option'] = $this->config->get('gpf_material_option');
        }
		
        if (isset($this->request->post['gpf_pattern_option'])) {
            $data['gpf_pattern_option'] = $this->request->post['gpf_pattern_option'];
        } else {
            $data['gpf_pattern_option'] = $this->config->get('gpf_pattern_option');
        }
		
		if (isset($this->request->post['gpf_status'])) {
			$data['gpf_status'] = $this->request->post['gpf_status'];
		} else {
			$data['gpf_status'] = $this->config->get('gpf_status');
		}

		if (isset($this->request->post['gpf_split'])) {
			$data['gpf_split'] = $this->request->post['gpf_split'];
		} else {
			$data['gpf_split'] = $this->config->get('gpf_split');
		}

		$data['splits'] = array(0, 10, 200, 500, 1000, 1500, 2000, 2500, 3000, 4000, 6000, 8000, 10000, 12000, 15000, 20000);
		$limit = $data['gpf_split'];
		if($limit == 0) {
			$limit = 1000000;
		}
		
		$no_of_products = $this->model_extension_feed_google_product_feed->getNoOfProducts();
		$pages = ($no_of_products % $limit == 0 ? ($no_of_products/$limit)-1 : (int)($no_of_products/$limit));
		
		$data['data_feed'] = $no_of_products . ' products enabled. Your feed will be split into ' . ($pages + 1) . ' separate files:' . '<br /></br>';
		for ($i=0; $i<=$pages; $i++) {
			if ($i == 0) {
				$pg = '';
			} else {
				$pg = '&page=' . $i;
			}
			$data['data_feed'] .= '<a onclick="viewSplitFeed(\'' . HTTP_CATALOG . 'index.php?route=feed/google_product_feed' . $pg . '\')" title="Click the link to view this feed">' . HTTP_CATALOG . 'index.php?route=feed/google_product_feed' . $pg . '</a><br />';
		
		}

        $data['currencies'] = array('GBP', 'USD', 'EUR', 'AUD', 'JPY', 'CNY', 'CHF', 'CZK', 'BRL', 'CAD', 'INR', 'IDR', 'NOK', 'DKK', 'PLN', 'SEK', 'TRY', 'RUB', 'MXN');

        if (isset($this->request->post['gpf_currency'])) {
            $data['gpf_currency'] = $this->request->post['gpf_currency'];
        } else {
            $data['gpf_currency'] = $this->config->get('gpf_currency');
        }

        $data['languages'] = array(
			array('value'=>'cs-CZ', 'selection' => '&#268;esky'),
			array('value'=>'da-DK', 'selection' => 'Dansk'),
			array('value'=>'de-DE', 'selection' => 'Deutsch'),
			array('value'=>'en-US', 'selection' => 'English (US)&lrm;'),
			array('value'=>'en-AU', 'selection' => 'English (Australia)&lrm;'),
			array('value'=>'en-GB', 'selection' => 'English (GB)&lrm;'),
			array('value'=>'es-ES', 'selection' => 'Espa&#241;ol'),
			array('value'=>'fr-FR', 'selection' => 'Fran&#231;ais'),
			array('value'=>'it-IT', 'selection' => 'Italiano'),
			array('value'=>'nl-NL', 'selection' => 'Nederlands'),
			array('value'=>'no-NO', 'selection' => 'Norsk'),
			array('value'=>'pl-PL', 'selection' => 'Polski'),
			array('value'=>'pt-BR', 'selection' => 'Portugu&#234;s (Brasil)&lrm;'),
			array('value'=>'ru-RU', 'selection' => 'Russian'),
			array('value'=>'sv-SE', 'selection' => 'Svenska'),
			array('value'=>'tr-TR', 'selection' => 'T&uuml;rk&ccedil;e'),
			array('value'=>'ch-US', 'selection' => 'Chinese'),
			array('value'=>'ja-JP', 'selection' => 'Japanese')	
		);
		
        if (isset($this->request->post['gpf_lang'])) {
            $data['gpf_lang'] = $this->request->post['gpf_lang'];
        } else {
            $data['gpf_lang'] = $this->config->get('gpf_lang');
        }
		if(VERSION >= '1.5.4') {
	        $data['original_gtin'] = array('Select Field to Copy From', 'upc', 'ean', 'isbn', 'jan', 'model', 'sku', 'mpn');
	        $data['original_mpn'] = array('Select Field to Copy From', 'upc', 'ean', 'isbn', 'jan', 'model', 'sku');
		} else {
        	$data['original_gtin'] = array('Select Field to Copy From',  'model', 'sku', 'mpn');
        	$data['original_mpn'] = array('Select Field to Copy From', 'model', 'sku');
		}

        if (isset($this->request->post['gpf_copy_gtin'])) {
            $data['gpf_copy_gtin'] = $this->request->post['gpf_copy_gtin'];
        } else {
            $data['gpf_copy_gtin'] = $this->config->get('gpf_copy_gtin');
        }

        if (isset($this->request->post['gpf_copy_mpn'])) {
            $data['gpf_copy_mpn'] = $this->request->post['gpf_copy_mpn'];
        } else {
            $data['gpf_copy_mpn'] = $this->config->get('gpf_copy_mpn');
        }

		if (isset($this->request->post['gpf_default_google_product_category'])) {
            $data['gpf_default_google_product_category'] = $this->request->post['gpf_default_google_product_category'];
        } else {
            $data['gpf_default_google_product_category'] = $this->config->get('gpf_default_google_product_category');
        }
		
		if (isset($this->request->post['gpf_copy_manufacturer'])) {
            $data['gpf_copy_manufacturer'] = $this->request->post['gpf_copy_manufacturer'];
        } else {
            $data['gpf_copy_manufacturer'] = $this->config->get('gpf_copy_manufacturer');
        }
		
		$data['gtins'] = array(
						'gtin'		=> 'GTIN',
						'ean'		=> 'EAN',
						'upc'		=> 'UPC',
						'isbn'		=> 'ISBN',
						'jan'		=> 'JAN',
						'sku'		=> 'SKU'
		);
		
        if (isset($this->request->post['gpf_gtin'])) {
            $data['gpf_gtin'] = $this->request->post['gpf_gtin'];
        } elseif($this->config->get('gpf_gtin') != '') {
            $data['gpf_gtin'] = $this->config->get('gpf_gtin');
        } else {
            $data['gpf_gtin'] = 'gtin';
		}
		
		$data['available_conditions'] = array('New', 'Refurbished', 'Used');
		$data['yes_no'] = array('Yes', 'No');

        if (isset($this->request->post['gpf_condition'])) {
            $data['gpf_condition'] = $this->request->post['gpf_condition'];
        } else {
            $data['gpf_condition'] = $this->config->get('gpf_condition');
        }
		
		$data['available_oos_statuses'] = array('Out of Stock', 'Preorder', 'In Stock');

        if (isset($this->request->post['gpf_oos_status'])) {
            $data['gpf_oos_status'] = $this->request->post['gpf_oos_status'];
        } else {
            $data['gpf_oos_status'] = $this->config->get('gpf_oos_status');
        }

		$data['available_size_systems'] = array('Not Applicable', 'US', 'UK', 'EU', 'DE', 'FR', 'JP', 'CN', 'IT', 'BR', 'MEX', 'AU');

        if (isset($this->request->post['gpf_size_system'])) {
            $data['gpf_size_system'] = $this->request->post['gpf_size_system'];
        } else {
            $data['gpf_size_system'] = $this->config->get('gpf_size_system');
        }

		if (isset($this->request->post['gpf_identifier_exists'])) {
            $data['gpf_identifier_exists'] = $this->request->post['gpf_identifier_exists'];
        } else {
            $data['gpf_identifier_exists'] = $this->config->get('gpf_identifier_exists');
        }

		if (isset($this->request->post['gpf_mobile_url'])) {
            $data['gpf_mobile_url'] = $this->request->post['gpf_mobile_url'];
        } else {
            $data['gpf_mobile_url'] = $this->config->get('gpf_mobile_url');
        }

        $data['gpf_custom_labels_group'] = array();
		if (isset($this->request->post['gpf_custom_labels_group'])) {
            $data['gpf_custom_labels_group'] = $this->request->post['gpf_custom_labels_group'];
        } else {
            $data['gpf_custom_labels_group'] = $this->config->get('gpf_custom_labels_group');
        }

        $data['gpf_custom_labels'] = array();
		if (isset($this->request->post['gpf_custom_labels'])) {
            $data['gpf_custom_labels'] = $this->request->post['gpf_custom_labels'];
        } else {
            $data['gpf_custom_labels'] = $this->config->get('gpf_custom_labels');
        }

		if(!$this->config->get('gpf_status')) {
			$data['gpf_defaults_saved'] ='0';
		} else {
			$data['gpf_defaults_saved'] ='1';
		}

		$data['copy_options'] = array('Products with empty data field', 'All Products');
		$data['fields'] = array('Default Google Category', 'Condition', 'Out of Stock Status', 'Size System', 'Identifier Exists', 'Brand');

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');
				
		$this->response->setOutput($this->load->view('extension/feed/google_product_feed', $data));
	}


	private function sortCustomLabels($data) {
	
		$sorted_data = '';
		if ($data != '') {
			$labels = array();
			$labels = array_map('trim', explode(',', $data));
			sort($labels);
			$sorted_data = implode(',', $labels);
		}

		return $sorted_data;
	}
	


	public function export() {
		
		$this->optimiseResources();
		$this->language->load('extension/feed/google_product_feed');
		if ($this->user->hasPermission('modify', 'extension/feed/google_product_feed')) {
			
			$file_name = 'google-product-feed-export-' . date('Y-m-d_H-i-s', time()).'.xlsx';
			$destination = DIR_LOGS . $file_name;
			
			$this->load->model('extension/feed/google_product_feed');
			$this->model_extension_feed_google_product_feed->exportXlsx($destination);
		
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Cache-Control: public");
			header("Content-Description: File Transfer");
			header("Content-type: application/octet-stream");
			header("Content-Disposition: attachment; filename=\"" . $file_name . "\"");
			header("Content-Transfer-Encoding: binary");
			// make sure the file size isn't cached
			clearstatcache();
			header("Content-Length: ".filesize($destination));
			// output the file
			readfile($destination);
			
			unlink($destination);
			
		} else {
			$this->session->data['error'] = $this->language->get('error_permission');
			$this->response->redirect($this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], true));			
		}
	}
			
			
	//////////////////////////////////////////////////////////////////////////////
	//                                                                          //
	//      Formatting Errors found in import file                              //
	//                                                                          //
	//////////////////////////////////////////////////////////////////////////////

	public function csvErrors() {
		
		$this->load->language('extension/feed/google_product_feed');
		$this->load->model('setting/setting');
		$this->load->model('extension/feed/google_product_feed');

		$this->document->setTitle($this->language->get('heading_title_import'));
		
		$csv_errors = $this->session->data['csv_errors'];
		unset($this->session->data['csv_errors']);


		$data['heading_title'] = $this->language->get('heading_title_import');

		$data['text_csv_errors'] = '<ul>';		
		foreach($csv_errors as $key => $csv_error) {
			$data['text_csv_errors'] .= '<li>' . $key . '  >  ' . $csv_error . ' errors</li>';
		}		
		$data['text_csv_errors'] .= '</ul>';
		
		$data['text_csv_errors_heading'] = $this->language->get('text_csv_errors_heading');
		$data['entry_csv_errors'] = $this->language->get('entry_csv_errors');
		$data['alert_update_database'] = $this->language->get('alert_update_database');

		$data['button_yes'] = $this->language->get('button_yes');
		$data['button_no'] = $this->language->get('button_no');

		
		if(VERSION >= '2.2.0.0') {
			$data['yes'] = html_entity_decode($this->url->link('extension/feed/google_product_feed', 'validate_csv=true&user_token=' . $this->session->data['user_token'], true));
			$data['no'] = $this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], true);
		} else {
			$data['yes'] = html_entity_decode($this->url->link('extension/feed/google_product_feed', 'validate_csv=true&user_token=' . $this->session->data['user_token'], 'SSL'));
			$data['no'] = $this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], 'SSL');
		}
			
		$data['user_token'] = $this->session->data['user_token'];

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

   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'user_token=' . $this->session->data['user_token'], true),
      		'separator' => false
   		);

   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_feed'),
			'href'      => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'], true),
      		'separator' => ' :: '
   		);

   		$data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('extension/feed/google_product_feed', 'user_token=' . $this->session->data['user_token'], true),
      		'separator' => ' :: '
   		);

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

		$this->response->setOutput($this->load->view('extension/feed/google_product_feed_csv_errors', $data));
		
		
	}

	private function optimiseResources(){
	
		error_reporting(E_ALL); 
		ini_set('display_errors', 1);
		
		// memory_limit
		$mem_limit = ini_get('memory_limit');
		if(substr($mem_limit, -1) == 'M') {
			$mem_limit = (substr($mem_limit, 0, -1) * 1024 * 1024);
		}
		$mem_limit = $mem_limit / 1024 / 1024;
		
		if($mem_limit < 256) {
			ini_set('memory_limit', '256M');
		}
		
		// max_execution_time
		ini_set('max_execution_time', 600);
	}

	private function validate() {
		if (!$this->user->hasPermission('modify', 'extension/feed/google_product_feed')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
}
?>