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

class Reports extends CI_Controller { 
    
	private $getAllUserBrands;
	private $brand_id;
    function __construct() {
		// echo "Under Construction";die;
        parent::__construct();
        $this->load->model('brand/reports_model');
		if(!$this->session->userdata('isBrandLoggedIn'))
		{
			 redirect('brand');
		}
		
		// $this->getAllUserBrands = $this->reports_model->getUserBrandsIds($this->session->userdata('userId'));
		$this->brand_id = $this->session->userdata('loginUserData')['brand_id'];
    }



	function index()
	{
		if(null !== $this->input->get('filter_date'))
		{
			$brand_id = $this->brand_id;
			// $this->accessBrandCheck($brand_id);
			$filter_date = $this->input->get('filter_date');
			$filter_date_array = explode("-",$filter_date);
			$date = $filter_date_array[0];
			$month = $filter_date_array[1];
			$year = $filter_date_array[2];
			$previous_date = date('d-m-Y', strtotime('-1 day', strtotime($filter_date)));
			$previous_date_array = explode("-",$previous_date);
			$days_in_current_month = cal_days_in_month(CAL_GREGORIAN,$month,$year);
			
			$where_array = array("brand_id"=>$brand_id,"date"=>date("Y-m-d",strtotime($filter_date)));
			$data['date_imported_data'] = $this->reports_model->getDailyImportData($where_array);
			$data['month_imported_data'] = $this->reports_model->getMonthDailyImportData($brand_id,$days_in_current_month,$month,$year);
			 // echo "<pre>"; print_r($this->db->last_query()); echo "</pre>";die;
			if(empty($data['date_imported_data']))
			{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Please import data to this date first.</div>');
				redirect(base_url().'brand/reports/', 'refresh');
			}
			// echo "<pre>"; print_r($this->db->last_query()); echo "</pre>";die;
			// echo "<pre>"; print_r($data["month_imported_data"]); echo "</pre>";die;
			
			
			$whereArray = array();
			if(null!==$this->input->get('channel_id') && $this->input->get('channel_id')!=""){
				$whereArray['channel_group.id'] = $this->input->get('channel_id');
			}
			
			if(null!==$this->input->get('type') && $this->input->get('type')!=""){
				$type = $this->input->get('type');
				$brandTypeRes = $this->reports_model->checkBrandType($brand_id,$type);
				
				if($brandTypeRes)
				{
					
					$allChannels = $this->reports_model->getAllChannelGroupsType($brand_id,$type);
					// echo "<pre>"; print_r($this->db->last_query()); echo "</pre>";die;
					// $new_array = array_merge($brandTypeRes,$allChannels);
					
					// echo "<pre>"; print_r($brandTypeRes); echo "</pre>";die;
					// echo "<pre>"; print_r($allChannels); echo "</pre>";die;
					$brandChannelArray = array();
					// echo "<pre>"; print_r($allChannels); echo "</pre>";die;
					foreach($brandTypeRes as $k=>$v)
					{
						array_push($brandChannelArray,$v->id);
					}
					foreach($allChannels as $ket=>$vat)
					{
							array_push($brandChannelArray,$vat->id);
					}
					
					$type = $brandChannelArray;
					// echo "<pre>"; print_r($brandChannelArray); echo "</pre>";die;
					
				}
				
			}else{
				$type = null;
			}
			
			
			/* Get All Channel Groups */
			$data["channel_groups"] = $this->reports_model->getChannelGroup($whereArray,$type);
			// echo "<pre>"; print_r($this->db->last_query()); echo "</pre>";die;
			
			$data["daily_cost_date"] = $this->reports_model->getDailyCostData($where_array);
			$data["daily_cost_month"] = $this->reports_model->getMonthTotalDailyCostData($brand_id,$days_in_current_month,$month,$year);
			// echo "<pre>"; print_r($this->db->last_query()); echo "</pre>";die;
			$data["monthly_budget"] = $this->reports_model->getMonthlyBudgetData($where_array);
			$data["website_revenue"] = $this->reports_model->getWebsiteRevenue($where_array);
			// echo "<pre>"; print_r($data["website_revenue"]); echo "</pre>";die;
			
			/* Get All Channel Groups Revenue  */
			foreach($data["channel_groups"] as $k=>$v)
			{
				foreach($data['date_imported_data'] as $key=>$val)
				{
					if($val->channel_group_id == $v->id)
					{
						$data["channel_groups"][$k]->revenue =  $val->day_channel_revenue;
					}
				}
				if(!isset($data["channel_groups"][$k]->revenue))
				{
					$data["channel_groups"][$k]->revenue =  0;
				}
			}
			
			/* Get All Channel Groups Daily Cost */
			
			if($data["daily_cost_date"])
			{
				foreach($data["channel_groups"] as $k=>$v)
				{
					foreach($data['daily_cost_date'] as $key=>$val)
					{
						if($val->channel_group_id == $v->id)
						{
							$data["channel_groups"][$k]->cost =  $val->cost;
						}
					}
					if(!isset($data["channel_groups"][$k]->cost))
					{
						$data["channel_groups"][$k]->cost =  0;
					}
				}
			}
			
			/* Get All Channel Groups Monthly Budget */
			
			if($data["monthly_budget"])
			{
				foreach($data["channel_groups"] as $k=>$v)
				{
					foreach($data["monthly_budget"] as $key=>$val)
					{
						if($val->channel_group_id == $v->id)
						{
							$data["channel_groups"][$k]->budget =  $val->budget;
						}
					}
					if(!isset($data["channel_groups"][$k]->budget))
					{
						$data["channel_groups"][$k]->budget =  0;
					}
				}
			}
			
			
			/* Get All Channel Groups Month to Date Achieved Number  */
			
			foreach($data["channel_groups"] as $k=>$v)
			{
				foreach($data['month_imported_data'] as $key=>$val)
				{
					if($val->channel_group_id == $v->id)
					{
						$data["channel_groups"][$k]->ach_month_to_date =  $val->total_channel_revenue;
					}
				}
				if(!isset($data["channel_groups"][$k]->ach_month_to_date))
				{
					$data["channel_groups"][$k]->ach_month_to_date =  0;
				}
			}
			
			/* Get All Channel Groups Total Month Daily Cost  */
			
			foreach($data["channel_groups"] as $k=>$v)
			{
				foreach($data["channel_groups"] as $k=>$v)
				{
					foreach($data['daily_cost_month'] as $key=>$val)
					{
						if($val->channel_group_id == $v->id)
						{
							$data["channel_groups"][$k]->total_cost =  $val->total_cost;
						}
					}
					if(!isset($data["channel_groups"][$k]->cost))
					{
						$data["channel_groups"][$k]->cost =  0;
					}
					if(!isset($data["channel_groups"][$k]->total_cost))
					{
						$data["channel_groups"][$k]->total_cost =  0;
					}
				}
			}
			
			
			/* Get All Channel Groups Month to Date Projected Number */
			$total_daily_revenue = 0;
			$total_daily_cost = 0;
			$total_budget = 0;
			$total_pr_month_to_date = 0;
			$total_ach_month_to_date = 0;
			$total_total_cost = 0;
			$difference = 0;
			$roas = 0;
			$channels_count = count($data["channel_groups"]);
			foreach($data["channel_groups"] as $nk=>$nv)
			{
				
				if($month == $previous_date_array[1])
				{
					$month_to_date = $nv->budget/$days_in_current_month*($date-1); 
				}else{
					$month_to_date = $nv->budget/$days_in_current_month*($date);
				}
				
				$data["channel_groups"][$nk]->pr_month_to_date =  round($month_to_date);
				if($nv->budget)
				{
					$diff = round($nv->ach_month_to_date/$nv->budget * 100);
					if($diff)
					{
						$data["channel_groups"][$nk]->difference =  round($nv->ach_month_to_date/$nv->budget * 100) ."%";
					}else{
						$data["channel_groups"][$nk]->difference =  0;
					}
					
				}
				else{
					$data["channel_groups"][$nk]->difference =  0;
				}
				if($nv->total_cost)
				{
					$data["channel_groups"][$nk]->roas =  number_format((float)$nv->ach_month_to_date/$nv->total_cost, 2, '.', '');
				}
				else{
					$data["channel_groups"][$nk]->roas =  0;
				}
				
				$total_daily_revenue += $nv->revenue;
				$total_daily_cost += $nv->cost;
				$total_budget += $nv->budget;
				$total_pr_month_to_date += $nv->pr_month_to_date;
				$total_ach_month_to_date += $nv->ach_month_to_date;
				$total_total_cost += $nv->total_cost;
				$total_difference = $difference;
				$total_roas = $roas;
				
			}
			
			$data["channel_groups"][$channels_count] = new \stdClass();
			$data["channel_groups"][$channels_count]->id = $channels_count+1;
			$data["channel_groups"][$channels_count]->name = "Total";
			$data["channel_groups"][$channels_count]->revenue = $total_daily_revenue;
			$data["channel_groups"][$channels_count]->cost = $total_daily_cost;
			$data["channel_groups"][$channels_count]->budget = $total_budget;
			$data["channel_groups"][$channels_count]->pr_month_to_date = $total_pr_month_to_date;
			$data["channel_groups"][$channels_count]->ach_month_to_date = $total_ach_month_to_date;
			$data["channel_groups"][$channels_count]->difference = $total_difference;
			$data["channel_groups"][$channels_count]->total_cost = $total_total_cost;
			$data["channel_groups"][$channels_count]->roas = $total_roas;
			
			if($data["website_revenue"])
			{
				$data["channel_groups"][$channels_count+1] = new \stdClass();
				$data["channel_groups"][$channels_count+1]->id = $channels_count+2;
				$data["channel_groups"][$channels_count+1]->name = "Backend Number";
				$data["channel_groups"][$channels_count+1]->revenue = $data["website_revenue"]->revenue;
			}
			
			
			// echo "<pre>"; print_r($data["channel_groups"]); echo "</pre>";die;
			$data["reports"] = $data["channel_groups"];
			$this->session->set_userdata("report_data",$data["channel_groups"]);
			$this->session->set_userdata("date",$filter_date);
			$data["brands"] = $this->reports_model->getBrands();
			$data["channels"] = $this->reports_model->getAllChannelGroups();
			$data['file']  = 'brand/reports/report';
			$this->load->view('brand/template',$data);	
		}else{
			$data["channels"] = $this->reports_model->getAllChannelGroups();
			$data["brands"] = $this->reports_model->getBrands();
			// echo "<pre>"; print_r($data["brands"]); echo "</pre>";die;
			$data['file']  = 'brand/reports/report';
			$this->load->view('brand/template',$data);	
		}
		
	}
	
	
	
	
	public function report_excel()  
	{
		if (!$this->session->userdata('isBrandLoggedIn')) {
            redirect(base_url());
        }
        require_once APPPATH . '/third_party/Phpexcel/Bootstrap.php';
        $reportList = $this->session->userdata('report_data');
        // Create new Spreadsheet object
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        // Set document properties
        $spreadsheet->getProperties()->setCreator('Media');
		if ($this->session->userdata('date')) {
            $fileName = 'media-report-' . $this->session->userdata('date') . ".xls";
            $date = $this->session->userdata('date');
        } else {
            $fileName = 'media-report-' . date('d-m-Y') . ".xls";
			$date = date('d-m-Y');
        }
		/* echo "<pre>";
		print_r($reportList);die; */
        // add style to the header
        $styleArray = array('font' => array('bold' => true,), 'alignment' => array('horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,), 'borders' => array('top' => array('style' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,),), 'fill' => array('type' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_GRADIENT_LINEAR, 'rotation' => 90, 'startcolor' => array('argb' => 'FFA0A0A0',), 'endcolor' => array('argb' => 'FFFFFFFF',),),);
        $spreadsheet->getActiveSheet()->getStyle('A1:I1')->applyFromArray($styleArray);
        // auto fit column to content
        foreach (range('A', 'I') as $columnID) {
            $spreadsheet->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
        }
        // set the names of header cells
        $spreadsheet->setActiveSheetIndex(0)
		->setCellValue("A1", 'Channel')
		->setCellValue("B1", "Date - ".$date)
		->setCellValue("C1", "Cost")
		->setCellValue("D1", "Month Target")
		->setCellValue("E1", 'MTD Projected Number')
		->setCellValue("F1", 'MTD Achieved Number')
		->setCellValue("G1", 'Difference')
		->setCellValue("H1", 'Total Cost')
		->setCellValue("I1", 'ROAS');
        // Add some data
        $x = 2;
        foreach ($reportList as $key => $report) {
			if(isset($report->revenue)){$revenue = $report->revenue;}else{$revenue = 0;}
			if(isset($report->cost)){$cost = $report->cost;}else{$cost = 0;}
			if(isset($report->budget)){$budget = $report->budget;}else{$budget = 0;}
			if(isset($report->pr_month_to_date)){$pr_month_to_date = $report->pr_month_to_date;}else{$pr_month_to_date = 0;}
			if(isset($report->ach_month_to_date)){$ach_month_to_date = $report->ach_month_to_date;}else{$ach_month_to_date = 0;}
			if(isset($report->difference)){$difference = $report->difference;}else{$difference = 0;}
			if(isset($report->total_cost)){$total_cost = $report->total_cost;}else{$total_cost = 0;}
			if(isset($report->roas)){$roas = $report->roas;}else{$roas = 0;}
            $spreadsheet->setActiveSheetIndex(0)
			->setCellValue("A$x", "$report->name")
			->setCellValue("B$x", "$revenue")
			->setCellValue("C$x", "$cost")
			->setCellValue("D$x", "$budget")
			->setCellValue("E$x", "$pr_month_to_date")
			->setCellValue("F$x", "$ach_month_to_date")
			->setCellValue("G$x", "$difference")
			->setCellValue("H$x", "$total_cost")
			->setCellValue("I$x", "$roas");
            $x++;
        }
        // Rename worksheet
        $spreadsheet->getActiveSheet()->setTitle('Media');
        $spreadsheet->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename= "' . $fileName . '"');
        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
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Excel2007');
        //ob_end_clean();
        $writer->save('php://output');
        exit;
	}
	
	/* 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().'brand/reports/', 'refresh');
		}
	} */
	
	
}
?>