<?php

class sv_woocommerce_order_export_module_excel{
	public $data									= false;
	private $PHPExcel								= false;
	private $filter									= false;
	private $alphabet								= array(
														'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
														'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'
													);
	private $titles									= false;
	private $orders									= false;
	private $fields									= array(); // builded in this->header()
	private $orders_filtered						= array();
	public $childs									= NULL;
	
	public function __construct(){
		require_once(SV_WOOCOMMERCE_ORDER_EXPORT_DIR.'lib/api/phpexcel/PHPExcel.php');
		$this->PHPExcel								= new PHPExcel();
		
		require_once(SV_WOOCOMMERCE_ORDER_EXPORT_DIR.'lib/common/childs.inc.php');
		$this->childs								= new sv_woocommerce_order_export_childs();
	}
	// helpers
	private function get_fields(){
		return $this->fields;
	}
	private function get_column($i){
		if(isset($this->alphabet[$i])){
			return $this->alphabet[$i];
		}else{
			return false;
		}
	}
	private function get_column_count(){
		return count($this->get_fields());
	}
	// process export
	public function build($data){
		$this->data									= $data;
		if(isset($_POST['subscriptions']) && $_POST['subscriptions'] == 'all'){
			$this->titles							= $this->data->settings->get_subscriptions_user_settings();
			$this->globalSettings					= $this->data->settings->get_subscriptions_global_settings();
			$this->orders							= $this->data->get_subscriptions();
		}else{
			$this->titles							= $this->data->settings->get_user_settings();
			$this->globalSettings					= $this->data->settings->get_global_settings();
			$this->orders							= $this->data->get_orders();
		}
		
		require_once(SV_WOOCOMMERCE_ORDER_EXPORT_DIR.'lib/common/filter.inc.php');
		$this->filter								= new sv_woocommerce_order_export_filter($this);
		
		$this->init();
		$this->header();
		$this->content();
		$this->footer();
		$this->formatting();
		$this->shutdown();
	}
	private function init(){
		// Set document properties
		$this->PHPExcel->getProperties()->setCreator('straightvisions.com')
			->setLastModifiedBy('straightvisions.com')
			->setTitle('WooCommerce order export')
			->setSubject('WooCommerce order export')
			->setDescription('Generated by SV WooCommerce Order Export Plugin by straightvisions.com')
			->setKeywords('office 2007 openxml php')
			->setCategory('WooCommerce Order Export');
		$this->PHPExcel->setActiveSheetIndex(0);
	}
	private function header(){
		// set titles
		$i											= 0;
		foreach($this->titles['fields'] as $field_id => $field_settings){
			if($this->data->export_field_visible($field_id,$field_settings)){
				$this->PHPExcel->setActiveSheetIndex(0)->setCellValue($this->get_column($i).'1', ((isset($field_settings['name']) && strlen($field_settings['name']) > 0) ? $field_settings['name'] : $field_id));
				$this->fields[]						= $field_id;
				$i++;
			}
		}

		// formatting
		$this->PHPExcel->getActiveSheet()->getStyle('A1:'.$this->get_column($this->get_column_count()).'1')->getFont()->setBold(true);
		foreach(range('A',$this->get_column($this->get_column_count())) as $columnID) {
			$this->PHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
		}
	}
	private function content(){
		// run all filters
		foreach($this->orders as $order_id => $order){ // all orders
			$values									= array();
			foreach($this->get_fields() as $field_position => $field_id){ // all active fields
				if(method_exists($this->filter,$field_id)){
					$values[$field_position]		= call_user_func(array($this->filter,$field_id),$order);
				}elseif(
					isset($this->globalSettings['fields'][$field_id]['filter']) &&
					isset($this->data->filters_loaded[$this->globalSettings['fields'][$field_id]['filter']]) &&
					method_exists($this->data->filters_loaded[$this->globalSettings['fields'][$field_id]['filter']],'get_data')
				){
					$values[$field_position]		= $this->data->filters_loaded[$this->globalSettings['fields'][$field_id]['filter']]->get_data($field_id,$order);
				}
				
			}
			if(!$this->filter->is_order_stripped($order_id)){
				$this->orders_filtered[$order_id]	= $values;
			}
		}
		
		// after filters may have cleaned up output, it's time to actually run it.
		$i											= 2;
		foreach($this->orders_filtered as $order_id => $fields){ // all orders
			foreach($fields as $field_position => $field_value){ // all active fields
				$position							= $this->get_column($field_position).$i;
				
				$this->PHPExcel->setActiveSheetIndex(0)->setCellValue(
					$position, // position
					$field_value // value
				);
			}
			if(empty($this->globalSettings['settings']['nested']) || $this->globalSettings['settings']['nested'] != 'data_flat'){
				$i++; // next row
			}
			
			// childs
			//var_dump($this->childs->get_childs());die();
			$i										= $this->processChilds($order_id,$i);
			
			if(isset($this->globalSettings['settings']['nested']) && $this->globalSettings['settings']['nested'] == 'data_flat'){
				$i++; // next row
			}
		}
	}
	private function processChilds($order_id,$i){
		if(is_array($this->childs->get_childs_by($order_id))){
			foreach($this->childs->get_childs_by($order_id) as $item){
				foreach($item as $options){
					foreach($options as $p => $option){
						$this->outputChild($p,$i,$option);
					}
					if(empty($this->globalSettings['settings']['nested']) || $this->globalSettings['settings']['nested'] != 'data_flat'){
						$i++; // next row
					}
				}
			}
		}
		return $i;
	}
	private function outputChild($p,$i,$option){
		$column_position							= array_search($p, $this->get_fields());

		// set values
		$position									= $this->get_column($column_position).$i;
		$this->PHPExcel->setActiveSheetIndex(0)->setCellValue(
			$position, // position
			$option // value
		);
	}
	private function footer(){
		
	}
	private function formatting(){
				// formatting
		/*		$currency = array(
					'total'		=> '#,##0.00_-[$€]',
					'total_tax'	=> '#,##0.00_-[$€]'
				);
				if(isset($currency[$field_id])){
					var_dump($this->get_column($field_position).$i);var_dump($currency[$field_id]);die();
					$this->PHPExcel->getActiveSheet()->getStyle($this->get_column($field_position).$i)->getNumberFormat()->setFormatCode($currency[$field_id]);
				}
		$this->PHPExcel->getActiveSheet()->getStyle('J2:J'.($orders['stats']['orders']+1))->getNumberFormat()->setFormatCode('#,##0.00_-[$€]');
		$this->PHPExcel->getActiveSheet()->getStyle('K2:K'.($orders['stats']['orders']+1))->getNumberFormat()->setFormatCode('#,##0.00_-[$€]');*/
	}
	private function shutdown(){
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="sv_woocommerce_order_export_'.$_POST['date_range'].'.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');
		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
		$objWriter = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'Excel2007');
		$objWriter->save('php://output');
		
		die();
	}
}

$module = new sv_woocommerce_order_export_module_excel();

?>