<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Product extends MY_Controller {

	public function index()
	{
		if($this->session->userdata('user_type') && ($this->session->userdata('user_type') == SUPERADMIN || $this->session->userdata('user_type') == ADMIN)) {
			redirect('product/add', 'refresh');
		}
		else {
			redirect('login', 'refresh');
		}
	}

	public function add()
	{
		save_current_url(base_url() . 'product/add/');
		
		if($this->session->userdata('user_type') && ($this->session->userdata('user_type') == SUPERADMIN || $this->session->userdata('user_type') == ADMIN)) {
			$this->lang->load('account_general', get_language());
			
			$data['page_title'] = $this->lang->line('website_name') . ' | ' . $this->lang->line('hf_product') . ' - ' .$this->lang->line('hf_add_new_product');
			
			$this->load->model('user_model');
				
			$data['group'] = $this->user_model->get_product_group_list();
			$data['category'] = $this->user_model->get_paroduct_category_list();
			
			$this->load->view('product_add_new', $data);
		}
		else {
			redirect('login', 'refresh');
		}
	}
	
	public function submit()
	{
		if($this->session->userdata('user_type') && ($this->session->userdata('user_type') == SUPERADMIN || $this->session->userdata('user_type') == ADMIN)) {
			if($_POST) {
				$this->lang->load('account_general', get_language());
			
				$_POST['page_title'] = $this->lang->line('website_name') . ' | ' . $this->lang->line('hf_product') . ' - ' .$this->lang->line('hf_add_new_product');
			
				$this->load->model('user_model');
				
				$rs = $this->user_model->add_new_product();
					
				if($rs) {
					redirect('product/add/', 'refresh');
				}
				else {
					$_POST['group'] = $this->user_model->get_product_group_list();
					$_POST['category'] = $this->user_model->get_paroduct_category_list();
					$this->load->view('product_add_new', $_POST);
				}
			}
			else {
				redirect('product/add/', 'refresh');
			}
		}
		else {
			redirect('login', 'refresh');
		}
	}
	
	public function edit($product_id = NULL)
	{
		save_current_url(base_url() . 'product/edit/' . $product_id . '/');
		
		if($this->session->userdata('user_type') && ($this->session->userdata('user_type') == SUPERADMIN || $this->session->userdata('user_type') == ADMIN)) {
			$this->lang->load('account_general', get_language());
	
			$this->load->model('user_model');
			$data = $this->user_model->get_product_details($product_id);
			$data['group'] = $this->user_model->get_product_group_list();
			$data['category'] = $this->user_model->get_paroduct_category_list();
			
			$data['page_title'] = $this->lang->line('website_name') . ' | ' . $this->lang->line('hf_product') . ' - ' .$this->lang->line('hf_edit_product');
			
			$this->load->view('product_update', $data);
		}
		else {
			redirect('login', 'refresh');
		}
	}
	
	public function update($product_id = NULL)
	{
		if($this->session->userdata('user_type') && ($this->session->userdata('user_type') == SUPERADMIN || $this->session->userdata('user_type') == ADMIN)) {
			if($_POST) {
				$this->lang->load('account_general', get_language());
	
				$_POST['page_title'] = $this->lang->line('website_name') . ' | ' . $this->lang->line('hf_product') . ' - ' .$this->lang->line('hf_edit_product');
			
				$this->load->model('user_model');
				
				$rs = $this->user_model->update_product_details($product_id);
				
				if($rs) {
					redirect('product/edit/' . $product_id . '/', 'refresh');
				}
				else {
					$this->load->model('user_model');
					$_POST['product'] = $this->user_model->get_product_details($product_id);
					$_POST['group'] = $this->user_model->get_product_group_list();
					$_POST['category'] = $this->user_model->get_paroduct_category_list();
					
					$this->load->view('product_update', $_POST);
				}
			}
			else {
				redirect('product/edit/' . $product_id . '/', 'refresh');
			}
		}
		else {
			redirect('login', 'refresh');
		}
	}
	
	public function listing()
	{
		save_current_url(base_url() . 'member/listing/');
		
		if($this->session->userdata('user_type') && ($this->session->userdata('user_type') == SUPERADMIN || $this->session->userdata('user_type') == ADMIN)) {
			$this->lang->load('account_general', get_language());
			
			$data['page_title'] = $this->lang->line('website_name') . ' | ' . $this->lang->line('hf_product') . ' - ' .$this->lang->line('hf_product_list');
		
			$this->load->view('product_list', $data);
		}
		else {
			redirect('login', 'refresh');
		}
	}
	
	public function getlist()
    {
		if($this->session->userdata('user_type') && ($this->session->userdata('user_type') == SUPERADMIN || $this->session->userdata('user_type') == ADMIN)) {
			$this->lang->load('account_general', get_language());
			
			/* Array of database columns which should be read and sent back to DataTables. Use a space where
			 * you want to insert a non-database field (for example a counter or static image)
			 */
			$aColumns = array(
								'product_name', 
								'product_price', 
								'product_qty',
								'product_enable',
								'product_id'
							);
			
			// DB table to use
			$sTable = 'products';
			//
			
			$this->db->order_by('product_id', 'DESC');
			
			$iDisplayStart = $this->input->get_post('iDisplayStart', true);
			$iDisplayLength = $this->input->get_post('iDisplayLength', true);
			$iSortCol_0 = $this->input->get_post('iSortCol_0', true);
			$iSortingCols = $this->input->get_post('iSortingCols', true);
			$sSearch = $this->input->get_post('sSearch', true);
			$sEcho = $this->input->get_post('sEcho', true);
		
			// Paging
			if(isset($iDisplayStart) && $iDisplayLength != '-1')
			{
				$this->db->limit($this->db->escape_str($iDisplayLength), $this->db->escape_str($iDisplayStart));
			}
			
			// Ordering
			if(isset($iSortCol_0))
			{
				for($i=0; $i<intval($iSortingCols); $i++)
				{
					$iSortCol = $this->input->get_post('iSortCol_'.$i, true);
					$bSortable = $this->input->get_post('bSortable_'.intval($iSortCol), true);
					$sSortDir = $this->input->get_post('sSortDir_'.$i, true);
		
					if($bSortable == 'true')
					{
						$this->db->order_by($aColumns[intval($this->db->escape_str($iSortCol))], $this->db->escape_str($sSortDir));
					}
				}
			}
			
			/* 
			 * Filtering
			 * NOTE this does not match the built-in DataTables filtering which does it
			 * word by word on any field. It's possible to do here, but concerned about efficiency
			 * on very large tables, and MySQL's regex functionality is very limited
			 */
			if(isset($sSearch) && !empty($sSearch))
			{
				for($i=0; $i<count($aColumns); $i++)
				{
					$bSearchable = $this->input->get_post('bSearchable_'.$i, true);
					
					// Individual column filtering
					if(isset($bSearchable) && $bSearchable == 'true')
					{
						$this->db->or_like($aColumns[$i], $this->db->escape_like_str($sSearch));
					}
				}
			}
			
			// Select Data
			$this->db->select('SQL_CALC_FOUND_ROWS '.str_replace(' , ', ' ', implode(', ', $aColumns)), false);
			$rResult = $this->db->get($sTable);
		
			// Data set length after filtering
			$this->db->select('FOUND_ROWS() AS found_rows');
			$iFilteredTotal = $this->db->get()->row()->found_rows;
		
			// Total data set length
			$iTotal = $this->db->count_all($sTable);
		
			// Output
			$output = array(
				'sEcho' => intval($sEcho),
				'iTotalRecords' => $iTotal,
				'iTotalDisplayRecords' => $iFilteredTotal,
				'aaData' => array()
			);
			
			foreach($rResult->result_array() as $aRow)
			{
				$row = array();
				
				$row[] = $aRow['product_name'];
				$row[] = $aRow['product_price'];
				$row[] = $aRow['product_qty'];
				$row[] = (($aRow['product_enable'] == 1) ? $this->lang->line('product_yes') : $this->lang->line('product_no'));
				$row[] = '<a href="' . base_url() . 'product/edit/' . $aRow['product_id'] . '/">' . $this->lang->line('product_edit') . '</a>';
				
				$output['aaData'][] = $row;
			}
		
			echo json_encode($output);
		}	
    }
	
	public function order()
	{
		save_current_url(base_url() . 'product/order/');
		
		if($this->session->userdata('user_type') && ($this->session->userdata('user_type') == SUPERADMIN || $this->session->userdata('user_type') == ADMIN)) {
			$this->lang->load('account_general', get_language());
			
			if($_POST) {
				$this->session->set_userdata(
					array(
						'member_search_username' => trim($this->input->post('search_username', TRUE)), 
						'member_search_order_date' => trim($this->input->post('search_order_date', TRUE)), 
						'member_search_start_date' => trim($this->input->post('search_start_date', TRUE)), 
						'member_search_end_date' => trim($this->input->post('search_end_date', TRUE))
						)
				);
				
				$_POST['page_title'] = $this->lang->line('website_name') . ' | ' . $this->lang->line('hf_product') . ' - ' .$this->lang->line('hf_product_order_history');
		
				$this->load->view('product_order_history', $_POST);
			}
			else {
				$this->session->unset_userdata(array('member_search_username' => '', 'member_search_order_date' => '', 'member_search_start_date' => '', 'member_search_end_date' => ''));
				
				$data['page_title'] = $this->lang->line('website_name') . ' | ' . $this->lang->line('hf_product') . ' - ' .$this->lang->line('hf_product_order_history');
		
				$this->load->view('product_order_history', $data);
			}
		}
		else {
			redirect('login', 'refresh');
		}
	}
	
	public function getorderlist()
    {
		if($this->session->userdata('user_type') && ($this->session->userdata('user_type') == SUPERADMIN || $this->session->userdata('user_type') == ADMIN)) {
			$this->lang->load('account_general', get_language());
			
			/* Array of database columns which should be read and sent back to DataTables. Use a space where
			 * you want to insert a non-database field (for example a counter or static image)
			 */
			$aColumns = array(
								$this->db->dbprefix('member_product_orders') . '.order_date',
								$this->db->dbprefix('member_product_orders') . '.member_username',
								$this->db->dbprefix('products') . '.product_name',
								$this->db->dbprefix('member_product_orders') . '.product_price',
								$this->db->dbprefix('member_product_orders') . '.qty',
								$this->db->dbprefix('member_product_orders') . '.final_amount',
								$this->db->dbprefix('member_product_orders') . '.full_name',
								$this->db->dbprefix('member_product_orders') . '.contact_no',
								$this->db->dbprefix('member_product_orders') . '.address1',
								$this->db->dbprefix('member_product_orders') . '.address2',
								$this->db->dbprefix('member_product_orders') . '.postcode',
								$this->db->dbprefix('member_product_orders') . '.city',
								$this->db->dbprefix('member_product_orders') . '.state',
								$this->db->dbprefix('member_product_orders') . '.country'
							);
							
			$jColumns = $this->db->dbprefix('member_product_orders') . '.product_id = ' . $this->db->dbprefix('products') . '.product_id';				
			
			// DB table to use
			$sTable = 'member_product_orders';
			$jTable = 'products';
			//
			
			if($this->session->userdata('member_search_order_date') != '') {
				if($this->session->userdata('member_search_order_date') == 2) {
					$start_date = strtotime(date('Y-m-d 00:00:00', strtotime($this->session->userdata('member_search_start_date'))));
					$end_date = strtotime(date('Y-m-d 23:59:59', strtotime($this->session->userdata('member_search_end_date'))));
					$where = "(" . $this->db->dbprefix('member_product_orders') . ".order_date >= '" .  $start_date . "' AND " . $this->db->dbprefix('member_product_orders') . ".order_date <= '" .  $end_date . "')";
					$this->db->where($where);
				}
				
				if($this->session->userdata('member_search_username') != '') {
					$where = $this->db->dbprefix('member_product_orders') . ".member_username = '" . $this->session->userdata('member_search_username') . "'";
					$this->db->where($where);
				}
			}
			
			$this->db->order_by('member_order_id', 'DESC');
			
			$iDisplayStart = $this->input->get_post('iDisplayStart', true);
			$iDisplayLength = $this->input->get_post('iDisplayLength', true);
			$iSortCol_0 = $this->input->get_post('iSortCol_0', true);
			$iSortingCols = $this->input->get_post('iSortingCols', true);
			$sSearch = $this->input->get_post('sSearch', true);
			$sEcho = $this->input->get_post('sEcho', true);
		
			// Paging
			if(isset($iDisplayStart) && $iDisplayLength != '-1')
			{
				$this->db->limit($this->db->escape_str($iDisplayLength), $this->db->escape_str($iDisplayStart));
			}
			
			// Ordering
			if(isset($iSortCol_0))
			{
				for($i=0; $i<intval($iSortingCols); $i++)
				{
					$iSortCol = $this->input->get_post('iSortCol_'.$i, true);
					$bSortable = $this->input->get_post('bSortable_'.intval($iSortCol), true);
					$sSortDir = $this->input->get_post('sSortDir_'.$i, true);
		
					if($bSortable == 'true')
					{
						$this->db->order_by($aColumns[intval($this->db->escape_str($iSortCol))], $this->db->escape_str($sSortDir));
					}
				}
			}
			
			/* 
			 * Filtering
			 * NOTE this does not match the built-in DataTables filtering which does it
			 * word by word on any field. It's possible to do here, but concerned about efficiency
			 * on very large tables, and MySQL's regex functionality is very limited
			 */
			if(isset($sSearch) && !empty($sSearch))
			{
				for($i=0; $i<count($aColumns); $i++)
				{
					$bSearchable = $this->input->get_post('bSearchable_'.$i, true);
					
					// Individual column filtering
					if(isset($bSearchable) && $bSearchable == 'true')
					{
						$this->db->or_like($aColumns[$i], $this->db->escape_like_str($sSearch));
					}
				}
			}
			
			// Select Data
			$this->db->select('SQL_CALC_FOUND_ROWS '.str_replace(' , ', ' ', implode(', ', $aColumns)), false);
			$this->db->join($jTable, $jColumns);
			$rResult = $this->db->get($sTable);
		
			// Data set length after filtering
			$this->db->select('FOUND_ROWS() AS found_rows');
			$iFilteredTotal = $this->db->get()->row()->found_rows;
		
			// Total data set length
			$iTotal = $this->db->count_all($sTable);
		
			// Output
			$output = array(
				'sEcho' => intval($sEcho),
				'iTotalRecords' => $iTotal,
				'iTotalDisplayRecords' => $iFilteredTotal,
				'aaData' => array()
			);
			
			foreach($rResult->result_array() as $aRow)
			{
				$row = array();
				
				$row[] = date('Y-m-d H:i:s', $aRow['order_date']);
				$row[] = $aRow['member_username'];
				$row[] = $aRow['product_name'];
				$row[] = $aRow['product_price'];
				$row[] = $aRow['qty'];
				$row[] = number_format($aRow['final_amount'], 0, '', '');
				
				$redeem_info = $this->lang->line('product_billing_name') . ': ' . $aRow['full_name'] . '<br />';
				$redeem_info .= $this->lang->line('product_billing_contact') . ': ' . $aRow['contact_no'] . '<br />';
				$redeem_info .= $this->lang->line('product_billing_address1') . ': ' . $aRow['address1'] . '<br />';
				
				if($aRow['address2'] != '') {
					$redeem_info .= $this->lang->line('product_billing_address2') . ': ' . $aRow['address2'] . '<br />';
				}
				
				$redeem_info .= $this->lang->line('product_billing_postcode') . ': ' . $aRow['postcode'] . '<br />';
				$redeem_info .= $this->lang->line('product_billing_city') . ': ' . $aRow['city'] . '<br />';
				$redeem_info .= $this->lang->line('product_billing_state') . ': ' . $aRow['state'] . '<br />';
				$redeem_info .= $this->lang->line('product_billing_country') . ': ' . $this->lang->line(get_country_name($aRow['country']));
				
				$row[] = $redeem_info;
				
				$output['aaData'][] = $row;
			}
		
			echo json_encode($output);
		}	
    }
	
	public function order_export()
	{
		set_time_limit(0);
		
		if($this->session->userdata('user_type') && ($this->session->userdata('user_type') == SUPERADMIN || $this->session->userdata('user_type') == ADMIN)) {
			$this->lang->load('account_general', get_language());
			
			require_once APPPATH."/third_party/php-excel.class.php";
			
			$data[] = array (
								$this->lang->line('product_order_date'),
								$this->lang->line('product_member_username'),
								$this->lang->line('product_name'),
								$this->lang->line('product_price'),
								$this->lang->line('product_qty'),
								$this->lang->line('product_total_amount'),
								$this->lang->line('product_shipping_info')
							);
			
			//Get Data
			$aColumns = array(
								$this->db->dbprefix('member_product_orders') . '.order_date',
								$this->db->dbprefix('member_product_orders') . '.member_username',
								$this->db->dbprefix('products') . '.product_name',
								$this->db->dbprefix('member_product_orders') . '.product_price',
								$this->db->dbprefix('member_product_orders') . '.qty',
								$this->db->dbprefix('member_product_orders') . '.final_amount',
								$this->db->dbprefix('member_product_orders') . '.full_name',
								$this->db->dbprefix('member_product_orders') . '.contact_no',
								$this->db->dbprefix('member_product_orders') . '.address1',
								$this->db->dbprefix('member_product_orders') . '.address2',
								$this->db->dbprefix('member_product_orders') . '.postcode',
								$this->db->dbprefix('member_product_orders') . '.city',
								$this->db->dbprefix('member_product_orders') . '.state',
								$this->db->dbprefix('member_product_orders') . '.country'
							);				
			
			$jColumns = $this->db->dbprefix('member_product_orders') . '.product_id = ' . $this->db->dbprefix('products') . '.product_id';				
			
			// DB table to use
			$sTable = 'member_product_orders';
			$jTable = 'products';
			//
			
			if($this->session->userdata('member_search_order_date') != '') {
				if($this->session->userdata('member_search_order_date') == 2) {
					$start_date = strtotime(date('Y-m-d 00:00:00', strtotime($this->session->userdata('member_search_start_date'))));
					$end_date = strtotime(date('Y-m-d 23:59:59', strtotime($this->session->userdata('member_search_end_date'))));
					$where = "(" . $this->db->dbprefix('member_product_orders') . ".order_date >= '" .  $start_date . "' AND " . $this->db->dbprefix('member_product_orders') . ".order_date <= '" .  $end_date . "')";
					$this->db->where($where);
				}
				
				if($this->session->userdata('member_search_username') != '') {
					$where = $this->db->dbprefix('member_product_orders') . ".member_username = '" . $this->session->userdata('member_search_username') . "'";
					$this->db->where($where);
				}
			}
			
			$this->db->order_by('member_order_id', 'DESC');
			
			$this->db->select('SQL_CALC_FOUND_ROWS '.str_replace(' , ', ' ', implode(', ', $aColumns)), false);
			$this->db->join($jTable, $jColumns);
			$rResult = $this->db->get($sTable);
			
			foreach($rResult->result_array() as $aRow)
			{
				$redeem_info = $this->lang->line('product_billing_name') . ': ' . $aRow['full_name'] . "\n";
				$redeem_info .= $this->lang->line('product_billing_contact') . ': ' . $aRow['contact_no'] . "\n";
				$redeem_info .= $this->lang->line('product_billing_address1') . ': ' . $aRow['address1'] . "\n";
				
				if($aRow['address2'] != '') {
					$redeem_info .= $this->lang->line('product_billing_address2') . ': ' . $aRow['address2'] . "\n";
				}
				
				$redeem_info .= $this->lang->line('product_billing_postcode') . ': ' . $aRow['postcode'] . "\n";
				$redeem_info .= $this->lang->line('product_billing_city') . ': ' . $aRow['city'] . "\n";
				$redeem_info .= $this->lang->line('product_billing_state') . ': ' . $aRow['state'] . "\n";
				$redeem_info .= $this->lang->line('product_billing_country') . ': ' . $this->lang->line(get_country_name($aRow['country']));
				
				$data[] = array (
									date('Y-m-d H:i:s', $aRow['order_date']),
									$aRow['member_username'],
									$aRow['product_name'],
									$aRow['product_price'],
									$aRow['qty'],
									number_format($aRow['final_amount'], 0, '', ''),
									$redeem_info
								);
			}
			
			$xls = new Excel_XML('UTF-8', false, 'Product Order List');
			$xls->addArray($data);
			$xls->generateXML('product_order_list');
		}
	}
}

/* End of file product.php */
/* Location: ./application/controllers/product.php */