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

class Brands extends CI_Controller { 
    
	// Columns names after parsing
    private $fields;
    // Separator used to explode each line
    private $separator = ';';
    // Enclosure used to decorate each field
    private $enclosure = '"';
    // Maximum row size to be used for decoding
    private $max_row_size = 4096;
	
	private $getAllUserBrands;
	
	private $role_id;

    function __construct() {
        parent::__construct();
        $this->load->model('admin/brands_model');
		$this->load->model('admin/users_model');
		if(!$this->session->userdata('isAdminLoggedIn'))
		{
			 redirect('admin');
		}
		$this->getAllUserBrands = $this->brands_model->getUserBrandsIds($this->session->userdata('userId'));
		$loginData = $this->session->userdata('loginUserData');
		$this->role_id = $loginData['role_id'];
		/* elseif($this->session->userdata('loginUserData')['role_id'] != 1)
		{
			redirect(base_url().'admin/dashboard');
		} */
    }



	function index()
	{
		$whereArray = array();
		$alias = "br";
		$fields = array($alias.".*");
		if(null!==$this->input->get('brand_name') && $this->input->get('brand_name')!=""){
			$whereArray[$alias.'.brand_name'] = $this->input->get('brand_name');
		}
		if(null!==$this->input->get('status') && $this->input->get('status')!=""){
			$whereArray[$alias.'.status'] = $this->input->get('status');
		}
		
		$orderby = array($alias.".id", "asc");
		$joins = array();
		$where = array("where"=>$whereArray); 
		$data['brands'] = $this->brands_model->getBrands($fields,$where,$joins,$alias,"",$orderby);
		// echo "<pre>"; print_r($this->db->last_query()); echo "</pre>";	die;	
		// echo "<pre>"; print_r($data['brands']); echo "</pre>";die;
		$data['totalCount'] = $this->brands_model->totalCount($fields,$where,$joins,$alias,"",$orderby); 
		// echo "<pre>"; print_r($this->db->last_query()); echo "</pre>";die;
		$data['numrecord'] = $this->brands_model->getNumRecord();
		$data['page'] = $this->brands_model->getPage();
		$data['filters'] = $this->getFilter();
		$data['number_of_page'] = ceil($data['totalCount']/$data['numrecord']);
		$data['file']  = 'admin/brands/brands_view';
		$this->load->view('admin/template',$data);	
		
	}
	
	function getFilter(){
		$filter = array();
		
		$filter['name'] = array("field"=>"text", "values"=>"brand_name");
		$filter['status'] = array("field"=>"select","values"=>array("0"=>"Disabled","1"=>"Enabled"));
		return $filter;
	}
	

	public function addBrand()
	{
		
		/* echo "<pre>";
		print_r($_POST);die; */
		$this->accessBrandRoleCheck($this->role_id,ADMIN_ACCESS);
		if($this->input->post('submit'))
		{
			/* echo "<pre>";
				print_r($_POST);die; */
			//Check whether user upload picture
			
			$this->form_validation->set_rules('brand_name','Brand Name','trim|required|xss_clean|is_unique[brands.brand_name]');
			$this->form_validation->set_rules('user[]','Select User','trim|required|xss_clean');	
			$this->form_validation->set_rules('user_name','Brand User Name','trim|required|xss_clean');	
			$this->form_validation->set_rules('phone','Mobile Number','trim|required|xss_clean|is_unique[brand_user.phone]|numeric|max_length[10]');	
			$this->form_validation->set_rules('user_email','Email','trim|required|valid_email|xss_clean|is_unique[brand_user.email]');	
			$this->form_validation->set_rules('password','Password','trim|required');
			$this->form_validation->set_rules('confirm_password','Confirm Password','trim|required|matches[password]');	
				
			//$this->form_validation->set_rules('image','Image','trim|required|xss_clean');	
			if($this->form_validation->run() == false)
			{
				$data['users'] = $this->brands_model->getUsers(); 
				$data['file']  = 'admin/brands/brands_add';
				$this->load->view('admin/template',$data);
			}
			else
			{
				$mapped_user = $this->input->post('user');
				array_unshift($mapped_user , 1);
				// echo "<pre>";print_r($mapped_user);die;
					$brand_data = array(
						'brand_name'=>$this->input->post('brand_name'),
						'slug'=>str_replace(" ","_",strtolower($this->input->post('brand_name'))),
						'created_by'=>$this->session->userdata('userId'),
						'agency_id'=>$this->session->userdata('loginUserData')['agency_id'],
						'created_at'=>date('Y-m-d H:i:s'),
						'updated_at'=>date('Y-m-d H:i:s'),
						'status'=>$this->input->post('status')
					);   
				
					$brand_user_data = array(
						'name'=>$this->input->post('user_name'),
						'email'=>$this->input->post('user_email'),
						'phone'=>$this->input->post('phone'),
						'password'=>md5($this->input->post('password')),
						'user_type'=>1,
						'p1'=>$this->input->post('password'),
						'created_by'=>$this->session->userdata('userId'),
						'agency_id'=>$this->session->userdata('loginUserData')['agency_id'],
						'created_at'=>date('Y-m-d H:i:s'),
						'updated_at'=>date('Y-m-d H:i:s'),
						'status'=>$this->input->post('status')
					);    
					
				/* echo "<pre>";
				print_r($brand_user_data);die; */
				$insert_id = $this->brands_model->insertBrand($brand_data,$brand_user_data,$mapped_user);
				
			
				  if($insert_id)
				  {
					$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Brand added successfully.</div>');
					redirect(base_url().'admin/brands/', 'refresh');
				  }
				  else
				  {
					$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Please Try Again...</div>');
					redirect(base_url().'admin/brands/addBrand', 'refresh');
				  }
				
				
			}
		}
		else
		{
			$data['users'] = $this->brands_model->getUsers(); 
			$data['file']  = 'admin/brands/brands_add';
			$this->load->view('admin/template',$data);
		}
	}

	public function editBrand($id)
	{
		$this->accessBrandCheck($id);
		$this->accessBrandRoleCheck($this->role_id,ADMIN_ACCESS);
		$data['brands'] = $this->brands_model->getSingleBrand($id);
		if(empty($data['brands']))
		{
			redirect(base_url().'admin/brands/', 'refresh');
		}
		$data['brand_user'] = $this->brands_model->getSingleBrandUser($id);
		$data['users'] = $this->brands_model->getUsers(); 
		// echo "<pre>";print_r($data['brands']);die;
		$data['file']  = 'admin/brands/brands_edit';
		$this->load->view('admin/template',$data);
	}

	public function updateBrand($id)
	{
		$this->accessBrandCheck($id);
		$this->accessBrandRoleCheck($this->role_id,ADMIN_ACCESS);
		if ($this->input->post('submit')) 
		{
			$data['brands'] = $this->brands_model->getSingleBrand($id);
			$original_value = $data['brands']->brand_name;
			if($this->input->post('brand_name') != $original_value) {
			   $is_unique =  '|is_unique[brands.brand_name]';
			} else {
			   $is_unique =  '';
			}
			$this->form_validation->set_rules('brand_name','Brand Name','trim|required|xss_clean'.$is_unique);	
			$this->form_validation->set_rules('user_name','Brand User Name','trim|required|xss_clean');	
			$this->form_validation->set_rules('user[]','Select User','trim|required|xss_clean');	
			$this->form_validation->set_rules('password','Password','trim|required');
			$this->form_validation->set_rules('confirm_password','Confirm Password','trim|required|matches[password]');	
				
			if($this->form_validation->run() == false)
			{
				$data['users'] = $this->brands_model->getUsers(); 
				$data['brands'] = $this->brands_model->getSingleBrand($id);	
				$data['brand_user'] = $this->brands_model->getSingleBrandUser($id);
				$data['file']  = 'admin/brands/brands_edit';
				$this->load->view('admin/template',$data);
			}
			else
			{
				$mapped_user = $this->input->post('user');
				array_unshift($mapped_user , 1);
				// echo "<pre>";print_r($mapped_user);die;
					$update_brand_data = array(
						'brand_name'=>$this->input->post('brand_name'),
						'slug'=>str_replace(" ","_",strtolower($this->input->post('brand_name'))),
						'created_by'=>$this->session->userdata('userId'),
						'agency_id'=>$this->session->userdata('loginUserData')['agency_id'],
						'created_at'=>date('Y-m-d H:i:s'),
						'updated_at'=>date('Y-m-d H:i:s'),
						'status'=>$this->input->post('status')
					);   
				
					$update_brand_user_data = array(
						'name'=>$this->input->post('user_name'),
						'password'=>md5($this->input->post('password')),
						'p1'=>$this->input->post('password'),
						'created_by'=>$this->session->userdata('userId'),
						'agency_id'=>$this->session->userdata('loginUserData')['agency_id'],
						'created_at'=>date('Y-m-d H:i:s'),
						'updated_at'=>date('Y-m-d H:i:s'),
						'status'=>$this->input->post('status')
					); 
					
					 /* echo "<pre>";
				print_r($update_data);die; */
				
				$data_update = $this->brands_model->updateBrand($update_brand_data,$update_brand_user_data,$id,$mapped_user);
				  if($data_update > 0)
				  {
					 $this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Brand updated successfully.</div>');
					 redirect(base_url().'admin/brands/', 'refresh');
				  }
				  else
				  {
					$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Please Try Again...</div>');
				   redirect(base_url().'admin/brands/editBrand/'.$id, 'refresh');
				  }
			}
		}
		else
		{
		   
		   redirect(base_url().'admin/brands');
		}
	}
	
	
	public function deleteBrand($id)  
	{
		$this->accessBrandCheck($id);
		$this->accessBrandRoleCheck($this->role_id,ADMIN_ACCESS);
		$this->brands_model->delete($id);
	
		$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Brand  deleted successfully!</div>');
	
		redirect(base_url().'admin/brands');
	}
	
	public function updateBrandStatus($id)  
	{
		$this->accessBrandCheck($id);
		$this->accessAjaxBrandRoleCheck($this->role_id,ADMIN_ACCESS);
		$status = $this->input->post('status');
		$status_array = array('status'=>$status);
		$query = $this->brands_model->update_status($status_array,$id);
		if($query){
			echo 1;
		}else{
			echo 0;
		}
	}
	
	public function getBrandDetail($id){
		$this->accessBrandCheck($id);
		$whereArray = array();
		$alias = "usr";
		$fields = array($alias.".name",$alias.".email",$alias.".phone", "ut.role_name as user_type_name",$alias.".status");
		if(null!==$this->input->get('name') && $this->input->get('name')!=""){
			$whereArray[$alias.'.name'] = $this->input->get('name');
		}
		if(null!==$this->input->get('status') && $this->input->get('status')!=""){
			$whereArray[$alias.'.status'] = $this->input->get('status');
		}
		
		$whereArray[$alias.'.id'] = $id;
		$orderby = array($alias.".id", "asc");
		$joins = array(array('roles as ut', 'ut.role_id = '.$alias.'.role_id'));
		$conditions = array("where"=>$whereArray); 
		$userdata = $this->brands_model->getBrandsData($fields,$conditions,$joins,$alias);
		if($userdata[0]!==null){
			
		$singleuserdata = array();
			foreach($userdata[0] as $ukey=>$uvalue){
				//if($singleuserdata->$ukey=='status' && $uvalue==1){ $singleuserdata->$uvalue="Enabled"; }else{ $singleuserdata->$uvalue="Disabled"; }
				$singleuserdata[ucfirst(str_replace('_',' ',$ukey))] = ($ukey=="email")?$uvalue:ucfirst($uvalue);
				//print_r($ukey);
				//print_r($uvalue);
			}
			echo json_encode($singleuserdata);
		}else{
			echo 0;
		}
	}
	
	function monthlyBudget($id)
	{
		$this->accessBrandCheck($id);
		$this->accessBrandRoleCheck($this->role_id,MANAGER_ACCESS);
		/* echo "<pre>";
		print_r($data["channel_groups"]);die; */
		$data["brand_id"] = $id;
		$data['brands'] = $this->brands_model->getSingleBrand($id);
		if(empty($data['brands']))
		{
			redirect(base_url().'admin/brands/', 'refresh');
		}
		$data["year"] = date("Y");
		$data['file']  = 'admin/brands/monthly_budget';
		$this->load->view('admin/template',$data);	
	}
	
	function updateBrandBudget()
	{
		$this->accessBrandCheck($this->input->post("br_id"));
		$this->accessBrandRoleCheck($this->role_id,MANAGER_ACCESS);
		$target_amount = $this->input->post("targetAmount");
		$channel_gr_id = $this->input->post("channel_id");
		$month = $this->input->post("month");
		$brand_id = $this->input->post("br_id");
		$year = $this->input->post("year");
		$where_array = array(
			"brand_id"=>$brand_id,
			"month"=>$month,
			"channel_group_id"=>$channel_gr_id,
			"year"=>$year,
			"agency_id"=>$this->session->userdata('loginUserData')['agency_id'],
		);
		$insert_array = array(
			"brand_id"=>$brand_id,
			"month"=>$month,
			"channel_group_id"=>$channel_gr_id,
			"year"=>$year,
			"agency_id"=>$this->session->userdata('loginUserData')['agency_id'],
			"budget"=>$target_amount,
			"created_by" =>$this->session->userdata('userId'),
			"created_at" => date("Y-m-d H:i:s"),
			"status"=>1
		);
		
		$res = $this->brands_model->insertUpdateMonthlyBudget($where_array,$insert_array);
		echo 1;
		
	}
	
	function updateBrandBudgetTableYear()
	{
		$this->accessBrandCheck($this->input->post("br_id"));
		$this->accessBrandRoleCheck($this->role_id,MANAGER_ACCESS);
		$brand_id = $this->input->post("br_id");
		$year = $this->input->post("year");
		$data['records'] = $this->brands_model->getMonthlyBudget($year,$brand_id);
		$data["channel_groups"] = $this->brands_model->getChannelGroups();
		$month_array = array(
			array("month"=>"1","value"=>""),
			array("month"=>"2","value"=>""),
			array("month"=>"3","value"=>""),
			array("month"=>"4","value"=>""),
			array("month"=>"5","value"=>""),
			array("month"=>"6","value"=>""),
			array("month"=>"7","value"=>""),
			array("month"=>"8","value"=>""),
			array("month"=>"9","value"=>""),
			array("month"=>"10","value"=>""),
			array("month"=>"11","value"=>""),
			array("month"=>"12","value"=>""),
		);
		foreach($data["channel_groups"] as $k=>$v){
			if($data['records'])
			{
				$channel_gr_array = array();
				$records_channel_array = array();
				$i = 0;
				foreach($data["records"] as $key=>$val)
				{
					
					$new_array = array("budget"=>$val->budget,"month"=>$val->month);
					if(in_array($val->channel_group_id,$channel_gr_array))
					{
						$i++;
						$records_channel_array[$val->channel_group_id][$i] = $new_array;
					}
					else{
						$i = 0;
						$records_channel_array[$val->channel_group_id][$i] = $new_array;
					}
					array_push($channel_gr_array,$val->channel_group_id);
					
				}
				/* echo "<pre>";
				print_r($records_channel_array);die; */
				
				foreach($records_channel_array as $key1=>$val1)
				{
				
						$new_month_array = array(
							array("month"=>"1","value"=>""),
							array("month"=>"2","value"=>""),
							array("month"=>"3","value"=>""),
							array("month"=>"4","value"=>""),
							array("month"=>"5","value"=>""),
							array("month"=>"6","value"=>""),
							array("month"=>"7","value"=>""),
							array("month"=>"8","value"=>""),
							array("month"=>"9","value"=>""),
							array("month"=>"10","value"=>""),
							array("month"=>"11","value"=>""),
							array("month"=>"12","value"=>""),
						);
						/* echo "<pre>";
						print_r($records_channel_array);
						echo "<pre>";
						print_r($new_month_array);die; */
						if($key1 == $v['id'])
						{
							foreach($new_month_array as $keyt=>$valt)
							{	
								foreach($val1 as $new_key=>$new_val)
								{
									if($valt['month'] == $new_val['month'])
									{
										$new_month_array[$keyt]['value'] = $new_val['budget'];
									}
								
								}
							
							}
							$data["channel_groups"][$k]["month"] = $new_month_array;
							
							
						}
						
						
					
					
					
					
				}
				if(!isset($data["channel_groups"][$k]["month"]))
				{
					$data["channel_groups"][$k]["month"] = $month_array;
				}
				/* echo "<pre>";
						print_r($month_array);die; */
				
			}else{
				$data["channel_groups"][$k]["month"] = $month_array;
			}
			
		}
		
		$this->load->view('admin/brands/ajaxBrandBudgetTable',$data);	
	}
	
	
	function dailyCost($id)
	{
		$this->accessBrandCheck($id);
		$data["brand_id"] = $id;
		$data['brands'] = $this->brands_model->getSingleBrand($id);
		if(empty($data['brands']))
		{
			redirect(base_url().'admin/brands/', 'refresh');
		}
		$data["date"] = date("d-m-Y");
		$data["dateFilter"] = date("Y-m-d");
		$data['file']  = 'admin/brands/daily_cost';
		$this->load->view('admin/template',$data);	
	}
	
	function updateDailyCost()
	{
		$this->accessBrandCheck($this->input->post("br_id"));
		$cost = $this->input->post("cost");
		$channel_gr_id = $this->input->post("channel_id");
		$brand_id = $this->input->post("br_id");
		$date = date("Y-m-d",strtotime($this->input->post("date")));
		$where_array = array(
			"brand_id"=>$brand_id,
			"date"=>$date,
			"channel_group_id"=>$channel_gr_id,
			"agency_id"=>$this->session->userdata('loginUserData')['agency_id'],
		);
		$insert_array = array(
			"brand_id"=>$brand_id,
			"date"=>$date,
			"channel_group_id"=>$channel_gr_id,
			"agency_id"=>$this->session->userdata('loginUserData')['agency_id'],
			"cost"=>$cost,
			"created_by" =>$this->session->userdata('userId'),
			"created_at" => date("Y-m-d H:i:s"),
			"status"=>1
		);
		
		$res = $this->brands_model->insertUpdateDailyCost($where_array,$insert_array);
		echo 1;
		
	}
	
	function updateDailyCostTableDate()
	{
		$this->accessBrandCheck($this->input->post("br_id"));
		$brand_id = $this->input->post("br_id");
		$date = $this->input->post("date");
		$data['records'] = $this->brands_model->getDailyCost($date,$brand_id);
		$data["channel_groups"] = $this->brands_model->getChannelGroups();
		if($data["channel_groups"])
		{
			foreach($data["channel_groups"] as $k=>$v)
			{
				$data["channel_groups"][$k]["date"] = "";
				$data["channel_groups"][$k]["cost"] = "";
			}
		}
		if($data['records'])
		{
			foreach($data["channel_groups"] as $k=>$v)
			{
				foreach($data['records'] as $key=>$val)
				{
					if($val->channel_group_id == $v['id'])
					{
						$data["channel_groups"][$k]["date"] = $val->date;
						$data["channel_groups"][$k]["cost"] = $val->cost;
					}
				}
			}
			
		}
		$this->load->view('admin/brands/ajaxDailyCostTable',$data);
	}
	
	function dailyImport($id)
	{
		$this->accessBrandCheck($id);
		$channels = $this->brands_model->getChannels();
		$data["dateFilter"] = date("d-m-Y",strtotime("-1 day"));
		/* echo "<pre>";
		print_r($channels);die; */
		if($this->input->post('submit'))
		{
			$date = date("Y-m-d",strtotime($this->input->post('daily_import_date')));
			if(!empty($_FILES['import_csv']['name']))
			{
				$file_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $_FILES['import_csv']["name"]);
				$config['upload_path'] = 'uploads/csv/';
				$config['allowed_types'] = 'xls|xlsx|csv';
				$config['file_name'] = $date."-".time().".csv";
				
				//Load upload library and initialize configuration
				$this->load->library('upload',$config);
				$this->upload->initialize($config);
				
				if($this->upload->do_upload('import_csv')){
					$uploadData = $this->upload->data();
					$csv = $uploadData['file_name'];
				}
				else
				{
					$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">'.$this->upload->display_errors().'</div>');
					redirect(base_url().'admin/brands/dailyImport/'.$id, 'refresh');
					
				}
			}
			
			$filepath = $_SERVER["DOCUMENT_ROOT"].DIRECTORY_PATH.$csv;
			// $filepath = $_SERVER["DOCUMENT_ROOT"].DIRECTORY_PATH."30-12-2020-16087124731.csv";
			
			if(!file_exists($filepath)){
				return FALSE;            
			}
        
			// Open uploaded CSV file with read-only mode
			$csvFile = fopen($filepath, 'r');
			
			// Get Fields and values
			$this->fields = fgetcsv($csvFile, $this->max_row_size, $this->separator, $this->enclosure);
			$keys_values = explode(',', $this->fields[0]);
			$keys = $this->escape_string($keys_values);
			
			// Store CSV data in an array
			$csvData = array();
			$i = 1;
			while(($row = fgetcsv($csvFile, $this->max_row_size, $this->separator, $this->enclosure)) !== FALSE){
				
				// Skip empty lines
				if($row != NULL){
					$values = explode(',', $row[0]);
					if(count($keys) == count($values)){
						$arr        = array();
						$new_values = array();
						$new_values = $this->escape_string($values);
						for($j = 0; $j < count($keys); $j++){
							if($keys[$j] != ""){
								$arr[str_replace(" ","_",strtolower($keys[$j]))] = $new_values[$j];
							}
						}
						$csvData[$i] = $arr;
						$i++;
					}
				}
			}
			// Close opened CSV file
			fclose($csvFile);
			
			/* echo "<pre>";
			print_r($csvData);die; */
			
			$this->db->where('date',$date);
			$this->db->delete('daily_import_data');
			$this->db->where('date',$date);
			$this->db->delete('daily_revenue_total');
			foreach($csvData as $k=>$v){
				if($v['source_/_medium'])
				{
					if($v['revenue'] != 0.00)
					{
						$medium =  str_replace(' ', '', $v['source_/_medium']);
						// $medium =  str_replace(' ', '', "flymedia / cps");
						$value = $this->in_array_r($medium, $channels);
						if(empty($value))
						{
							$insert_channel = array(
								"agency_id"=>$this->session->userdata('loginUserData')['agency_id'],
								"channel_group_id"=>11,
								"channel_name"=>$v['source_/_medium'],
								"slug"=>$medium,
								"status"=>1,
								"created_by" =>$this->session->userdata('userId'),
								"created_at" => date("Y-m-d H:i:s")
							);
							$res = $this->db->insert('channel',$insert_channel);
							$last_insert_id = $this->db->insert_id();
							array_push($channels,$insert_channel);
							$channel_id = $last_insert_id;
							$channel_group_id = 11;
						}else{
							$channel_id = $value['id'];
							$channel_group_id = $value['channel_group_id'];
						}
						
						$insert = array(
							'agency_id'=>$this->session->userdata('loginUserData')['agency_id'],
							'brand_id'=>$id,
							'date'=>$date,
							'channel_id'=>$channel_id,
							'channel_group_id'=>$channel_group_id,
							'source'=>$v['source_/_medium'],
							'users'=>$v['users'],
							'new_users'=>$v['new_users'],
							'sessions'=>$v['sessions'],
							'bounce_rate'=>$v['bounce_rate'],
							'pages_session'=>$v['pages_/_session'],
							'avg_session_duration'=>$v['avg._session_duration'],
							'ecom_conversion_rate'=>$v['ecommerce_conversion_rate'],
							'transactions'=>$v['transactions'],
							'revenue'=>$v['revenue'],
							'status'=>1,
							'created_by'=>$this->session->userdata('userId'),
							'created_at'=>date("Y-m-d H:i:s"),
						);
						$insert_id = $this->db->insert('daily_import_data',$insert);
					}
					
				}else{
					$insert_total = array(
					'agency_id'=>$this->session->userdata('loginUserData')['agency_id'],
					'brand_id'=>$id,
					'date'=>$date,
					'revenue_total'=>$v['revenue'],
					'created_at'=>date("Y-m-d H:i:s"),
					);
					$insert_id = $this->db->insert('daily_revenue_total',$insert_total);
				}
			}
			
			if($insert_id)
			{
				$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Data Imported successfully.</div>');
				redirect(base_url().'admin/brands/dailyImport/'.$id."?filter_date=".$this->input->post('daily_import_date'), 'refresh');
			}
			else
			{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Please Try Again...</div>');
				redirect(base_url().'admin/brands/dailyImport/'.$id, 'refresh');
			}
		}elseif($this->input->get('filter_date'))
		{
			$data["brand_id"] = $id;
			$where_array = array("brand_id"=>$id,"date"=>date("Y-m-d",strtotime($this->input->get('filter_date'))));
			$data["daily_import_data"] = $this->brands_model->getDailyImportData($where_array);
			/* echo "<pre>";
			print_r($data["daily_import_data"]);die; */
			$data['totalCount'] = $this->brands_model->totalDailyImportCount($where_array); 
			// echo "<pre>"; print_r($this->db->last_query()); echo "</pre>";die;
			$data['numrecord'] = $this->brands_model->getNumRecord();
			$data['page'] = $this->brands_model->getPage();
			$data['filters'] = $this->getFilter();
			$data['number_of_page'] = ceil($data['totalCount']/$data['numrecord']);
			$data['file']  = 'admin/brands/get_filter_daily_import_data';
			$this->load->view('admin/template',$data);	
		}else{
			$data["brand_id"] = $id;
			$data['file']  = 'admin/brands/daily_import';
			$this->load->view('admin/template',$data);	
		}
		
	}
	
	function in_array_r($needle, $haystack, $strict = false) {
		foreach ($haystack as $item) {
			if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && $this->in_array_r($needle, $item, $strict))) {
				return $item;
			}
		}

		return false;
	}
	
	
	function escape_string($data){
        $result = array();
        foreach($data as $row){
            $result[] = str_replace('"', '', $row);
        }
        return $result;
    }   
	
	function websiteRevenue($id)
	{
		$this->accessBrandCheck($id);
		$data["brand_id"] = $id;
		$data["date"] = date("d-m-Y");
		$data["dateFilter"] = date("Y-m-d");
		$data['brands'] = $this->brands_model->getSingleBrand($id);
		if(empty($data['brands']))
		{
			redirect(base_url().'admin/brands/', 'refresh');
		}
		$data['file']  = 'admin/brands/website_revenue';
		$this->load->view('admin/template',$data);	
	}
	
	function updateWebsiteRevenue()
	{
		$this->accessBrandCheck($this->input->post("br_id"));
		$cost = $this->input->post("cost");
		$id = explode("-",$this->input->post("id"));
		$key_price_id = $id[1]."_revenue";
		// $channel_gr_id = $this->input->post("channel_id");
		$brand_id = $this->input->post("br_id");
		$date = date("Y-m-d",strtotime($this->input->post("date")));
		$where_array = array(
			"brand_id"=>$brand_id,
			"date"=>$date,
			// "channel_group_id"=>$channel_gr_id,
			"agency_id"=>$this->session->userdata('loginUserData')['agency_id'],
		);
		$insert_array = array(
			"brand_id"=>$brand_id,
			"date"=>$date,
			// "channel_group_id"=>$channel_gr_id,
			"agency_id"=>$this->session->userdata('loginUserData')['agency_id'],
			$key_price_id=>$cost,
			"created_by" =>$this->session->userdata('userId'),
			"created_at" => date("Y-m-d H:i:s"),
			// "status"=>1
		);
		/* echo "<pre>";
		print_r($insert_array);die; */
		$res = $this->brands_model->insertUpdateWebsiteRevenue($where_array,$insert_array,$key_price_id);
		echo 1;
		
	}
	
	function updateWebsiteRevenueTableDate()
	{
		$this->accessBrandCheck($this->input->post("br_id"));
		$brand_id = $this->input->post("br_id");
		$date = $this->input->post("date");
		$data['records'] = $this->brands_model->getWebsiteRevenue($date,$brand_id);
		$data["channel_groups"] = $this->brands_model->getChannelGroups();
		$data["channel_groups"] = array(array("id"=>1,"name"=>"Total Revenue"));
		/* echo "<pre>";
		print_r($data["channel_groups"]);die; */
		if($data["channel_groups"])
		{
			foreach($data["channel_groups"] as $k=>$v)
			{
				$data["channel_groups"][$k]["date"] = "";
				$data["channel_groups"][$k]["pending_revenue"] = "";
				$data["channel_groups"][$k]["pending_payment_revenue"] = "";
				$data["channel_groups"][$k]["processing_revenue"] = "";
				$data["channel_groups"][$k]["shipped_revenue"] = "";
				$data["channel_groups"][$k]["cancelled_revenue"] = "";
				$data["channel_groups"][$k]["closed_revenue"] = "";
			}
		}
		if($data['records'])
		{
			foreach($data["channel_groups"] as $k=>$v)
			{
				foreach($data['records'] as $key=>$val)
				{
					$data["channel_groups"][$k]["date"] = $val->date;
					$data["channel_groups"][$k]["pending_revenue"] = $val->pending_revenue;
					$data["channel_groups"][$k]["pending_payment_revenue"] = $val->pending_payment_revenue;
					$data["channel_groups"][$k]["processing_revenue"] = $val->processing_revenue;
					$data["channel_groups"][$k]["shipped_revenue"] = $val->shipped_revenue;
					$data["channel_groups"][$k]["cancelled_revenue"] = $val->cancelled_revenue;
					$data["channel_groups"][$k]["closed_revenue"] = $val->closed_revenue;
					
				}
			}
			
		}
		$this->load->view('admin/brands/ajaxWebsiteRevenueTable',$data);
	}
	
	
	function channelSettings($brand_id)
	{
		$this->accessBrandCheck($brand_id);
		if($this->input->post('submit'))
		{
			$channelGroups = $this->brands_model->getAllChannelGroups();
			// echo "<pre>";print_r($channelGroups);die;
			$save_settings_values = $this->input->post();
			unset($save_settings_values['submit']);
			$saveChannelSettingArray = array();
			$channelIds = array();
			// echo "<pre>";print_r($save_settings_values);die;
			if($save_settings_values)
			{
				foreach($save_settings_values as $k=>$v)
				{
					array_push($channelIds,$k);
				}
			}
			
			$date = date('Y-m-d H:i:s');
			foreach($channelGroups as $key=>$val)
			{
				if(in_array($val->id,$channelIds))
				{
					$saveChannelSettingArrayPush = array("channel_group_id"=>$val->id,"brand_id"=>$brand_id,"type"=>1,"created_by"=>$this->session->userdata('userId'),'created_at'=>$date);
					array_push($saveChannelSettingArray,$saveChannelSettingArrayPush);
				}else{
					$saveChannelSettingArrayPush = array("channel_group_id"=>$val->id,"brand_id"=>$brand_id,"type"=>0,"created_by"=>$this->session->userdata('userId'),'created_at'=>$date);
					array_push($saveChannelSettingArray,$saveChannelSettingArrayPush);
				}
			}
			
			$res = $this->brands_model->insertChannelSettings($brand_id,$saveChannelSettingArray);
			
			$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Setting Saved Successfully.</div>');
			redirect(base_url().'admin/brands/channelSettings/'.$brand_id, 'refresh');
			// echo "<pre>";print_r($saveChannelSettingArray);die;
			// $saveChannelSettingArray = array('channel_group_id' => )
		}else
		{
			$data['brands'] = $this->brands_model->getSingleBrand($brand_id);
			// $data['channelSettings'] = $this->brands_model->insertChannelSettings();
			if(empty($data['brands']))
			{
				redirect(base_url().'admin/brands/', 'refresh');
			}
			$data['channelSettings'] = $this->brands_model->getChannelSettings($brand_id);
			if(empty($data['channelSettings']))
			{
				$data['channelSettings'] = $this->brands_model->getAllChannelGroups();
			}
			// echo "<pre>";print_r($this->db->last_query());die;
			$data['file']  = 'admin/brands/channel_settings';
			$this->load->view('admin/template',$data);	
		}
		
	}
	
	function accessBrandCheck($id)
	{
		if(!in_array($id,$this->getAllUserBrands))
		{
			$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">You are not access to this brand</div>');
			redirect(base_url().'admin/brands/', 'refresh');
		}
	}
	
	function accessBrandRoleCheck($role_id,$role_type)
	{
		if(!in_array($role_id,$role_type))
		{
			$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">You are not access to this</div>');
			redirect(base_url().'admin/brands/', 'refresh');
		}
	}
	function accessAjaxBrandRoleCheck($role_id,$role_type)
	{
		if(!in_array($role_id,$role_type))
		{
			echo 4;exit();
		}
	}
}
?>