<?php

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

class Home extends MX_Controller {

	const TOKENPW = 'violet';

    public function __construct() {
        parent::__construct();
        $this->load->helper('cookie');
		$this->load->helper('language');
		$this->lang->load('messages', 'message');
    }

    public function index() {
		
        $collaborator_info = $this->session->userdata('collaboratorInfo');
        if ($collaborator_info) {
			$id = $collaborator_info['id'];
            $data['statistics'] = $this->getStatistics($id);
			$data['content'] = $this->getCollaboratorsUsers();
            $this->load->view('collaborator/reportAsistant/indexCollaborator', $data);
        } else {
            $this->load->view('login');
        }
    }

    public function login() {
		
        $login_name = $this->input->post('login_name');
        $passwd = $this->input->post('passwd');
		
        $this->load->model('admin/Collabolator_model');
        $data = $this->Collabolator_model->check_login($login_name, $passwd);
        if ($data == null) {
            $this->session->set_flashdata('login_error', TRUE);
            redirect("/cong_tac_vien");
        } else {
            $collaboratorData = array('login_name' => $login_name, 'id' => $data->id, 'fullname' => $data->full_name, 'logined_in' => TRUE);
            $this->session->set_userdata('collaboratorInfo', $collaboratorData);
            redirect("/cong_tac_vien");
        }
    }

    public function logout() {
		$this->session->unset_userdata('collaboratorInfo');
        redirect("/collaborator");
    }
    
    public function is_timeout()
    {
        $result['login']=1;
        $collaborator_infor = $this->session->userdata('collaboratorInfo');
        if (!$collaborator_infor) {
            $result['login']=0;
        }
        echo json_encode($result);
    }

    public function getStatistics($id = false) {
        $data = array();

        $this_year['start'] = strtotime(date("Y") . "-01-01 00:00:00");

        $this->load->model('admin/collabolator_model');
        $collaborators = $this->collabolator_model->getAllCollaboratorUser($this_year['start'], $id);
        for ($i = 1; $i <= 12; $i++) {
            $statistics[$i] = 0;
        }
        $y = date("Y");
        foreach ($collaborators as $collaborator) {
            for ($i = 1; $i <= 12; $i++) {
                if ($i < 12) {
                    if (($collaborator['time'] > strtotime($y . "-" . $i . "-1 00:00:00")) && (($collaborator['time'] < strtotime($y . "-" . ($i + 1) . "-1 00:00:00")))) {
                        $statistics[$i] ++;
                    }
                } else {
                    if (($collaborator['time'] > strtotime($y . "-" . $i . "-1 00:00:00")) && (($collaborator['time'] < strtotime(($y + 1) . "-1-1 00:00:00")))) {
                        $statistics[$i] ++;
                    }
                }
            }
        }

        $max = 0;
        foreach ($statistics as $index => $total) {
            if ($total > $max) {
                $max = $total;
            }
            $chart[] = array($index, $total);
        }

        $data['max'] = $max;
        $chard[] = array("color" => "#e67e22", "label" => "Lượng người dùng giới thiệu bởi cộng tác viên theo từng tháng", "data" => $chart);
        $data['chard'] = $chard;
         
        return $this->load->view('collaborator/reportAsistant/statistics', $data, true);
    }

    public function getLastquarter() {
        $current_month = date('m');
        $current_year = date('Y');

        if ($current_month >= 1 && $current_month <= 3) {
            $start_date = strtotime('1-October-' . ($current_year - 1));  // timestamp or 1-October Last Year 12:00:00 AM
            $end_date = strtotime('1-Janauary-' . $current_year);  // // timestamp or 1-January  12:00:00 AM means end of 31 December Last year
        } else if ($current_month >= 4 && $current_month <= 6) {
            $start_date = strtotime('1-January-' . $current_year);  // timestamp or 1-Janauray 12:00:00 AM
            $end_date = strtotime('1-April-' . $current_year);  // timestamp or 1-April 12:00:00 AM means end of 31 March
        } else if ($current_month >= 7 && $current_month <= 9) {
            $start_date = strtotime('1-April-' . $current_year);  // timestamp or 1-April 12:00:00 AM
            $end_date = strtotime('1-July-' . $current_year);  // timestamp or 1-July 12:00:00 AM means end of 30 June
        } else if ($current_month >= 10 && $current_month <= 12) {
            $start_date = strtotime('1-July-' . $current_year);  // timestamp or 1-July 12:00:00 AM
            $end_date = strtotime('1-October-' . $current_year);  // timestamp or 1-October 12:00:00 AM means end of 30 September
        }
        return array("start" => $start_date, "end" => $end_date);
    }


    public function getCollaboratorsUsers() {
		$collaborator_info = $this->session->userdata('collaboratorInfo');
        if ($collaborator_info) {
			$this->load->helper('pagging');
			$this->load->model('admin/collabolator_model');
			$data['current_page'] = $this->uri->segment(5, 1);
			
			$data['itemsoptions'] = array(10, 25, 50, 100);
			$data['perpage'] = 10;
			$id = $collaborator_info['id'];
            $data['id'] = $id;
			
			$data['keyword'] = "";
			$data['sorting_order'] = "sorting_desc";
			$data['sorting_field'] = "user_created_time";

			if ($this->input->post('sorting_order')) {
				if ($this->input->post('sorting_order') != "sorting") {
					$data['sorting_order'] = $this->input->post('sorting_order');
					$data['sorting_field'] = $this->input->post('sorting_field');
				}
			}
			if ($this->input->post('items')) {
				$data['perpage'] = $this->input->post('items');
			}
			if ($this->input->post('keyword')) {
				$data['search_field'] = "";
				$data['keyword'] = $this->input->post('keyword');

				if (preg_match("/[0-9]/", $data['keyword'])) {
					$data['search_field'] = "cellphone";
				}
			}

			$data['daterange_start'] = "";
			$data['daterange_end'] = "";
			if ($this->input->post('daterange')){
				$daterange = explode(" - ", $this->input->post('daterange'));
				$daterange[0] = str_replace('/', '-', $daterange[0]);
				$daterange[1] = str_replace('/', '-', $daterange[1]);
				$data['date_start'] = $daterange[0];
				$data['date_end'] = $daterange[1];
				$data['daterange_start'] = date('Y-m-d H:i:s', strtotime($daterange[0]));
				$data['daterange_end'] = date('Y-m-d H:is:s', strtotime($daterange[1].' + 1 day'));
			}
			
			$data['start'] = ($data['current_page'] - 1) * $data['perpage'];
			$data['total'] = $this->collabolator_model->countCountCollaboratorUsers($data);
			$data['paidlogs'] = $this->collabolator_model->getCountCollaboratorUsers($data);
			foreach ($data['paidlogs'] as $index => $paidlog)
			{
				$data['paidlogs'][$index]['username'] = $this->get_fullname($paidlog['us_id']);
			}
			$data['paging_url'] = base_url() . "collaborator/home/getCollaboratorsUsers/".$data['id'];
			$data['num_links'] = 2;
			$data['paging'] = pagging($data);
		
			if ($this->input->is_ajax_request()) {
				return $this->load->view('collaborator/reportAsistant/listview_user', $data);
			}
			return $this->load->view('collaborator/reportAsistant/listview_user', $data, true);
		}else{
			$this->load->view('login');
		}
    }

    private function get_fullname($us_id) {
        $fullname="";
        $src = 'SBG';
        $token = md5($us_id . self::TOKENPW);
        $this->load->model('admin/user_model');
        $data = $this->user_model->get_user_info($src, $us_id, $token);
        parse_str($data,$data);
        if (isset($data['fullname']))
        {
            $fullname=$data['fullname'];
        }
        return $fullname;
    }
	
	
	public function export(){
		
		$collaborator_info = $this->session->userdata('collaboratorInfo');
        if ($collaborator_info) {
			$id = $collaborator_info['id'];
            $data['id'] = $id;
			$data['fullname'] = $collaborator_info['fullname'];
			$this->load->model('admin/collabolator_model');
			//$data['perpage'] = $this->uri->segment(4, 10);
			$data['keyword'] = $this->uri->segment(5);
			if ($data['keyword'] == 'default') $data['keyword'] = null;
			if (preg_match("/[0-9]/", $data['keyword'])) {
					$data['search_field'] = "cellphone";
			}
			$data['daterange_start'] = $this->uri->segment(6);
			$data['daterange_end'] = $this->uri->segment(7);
			if ($data['daterange_start'] == 'default') $data['daterange_start'] = null;
			if ($data['daterange_end'] == 'default') $data['daterange_end'] = null;
			if ($data['daterange_start'])
				$data['daterange_start'] = date ( 'Y-m-d H:i:s', strtotime ( $data ['daterange_start'] ) );
			if ($data['daterange_end'])
				$data['daterange_end'] = date ( 'Y-m-d H:i:s', strtotime ( $data['daterange_end'] . ' + 1 day' ) );
			
			$data['sorting_field'] = "user_created_time";
			$data['sorting_order'] = $this->uri->segment(8);
			
			$data['paidlogs'] = $this->collabolator_model->getCountCollaboratorUsers($data);
			
			foreach ($data['paidlogs'] as $index => $paidlog)
			{
				$data['paidlogs'][$index]['username'] = $this->get_fullname($paidlog['us_id']);
			}
			$users = $data['paidlogs'];
			
			ob_end_clean();
			$this->load->library("PHPExcel");
			$sheet = $this->phpexcel->getActiveSheet();
			
			$sheet->setTitle("bao cao cua CTV " . date('m') . " - " . date('Y'));
			$sheet->getColumnDimension('A')->setWidth(10);
			$sheet->getColumnDimension('B')->setWidth(25);
			$sheet->getColumnDimension('C')->setWidth(25);
			$sheet->getColumnDimension('D')->setWidth(25);
			$sheet->getColumnDimension('E')->setWidth(15);
			$sheet->getColumnDimension('F')->setWidth(15);
			$sheet->getColumnDimension('G')->setWidth(15);
			$sheet->getColumnDimension('H')->setWidth(25); 
			$sheet->getColumnDimension('I')->setWidth(25);
			
			
			$sheet->setCellValue('B1', "TẬP ĐOÀN VIỄN THÔNG QUÂN ĐỘI");
			$style = array(
				'font' => array('bold' => true, 'size' => 12, 'name' =>'Cambria', 'color' => array('rgb' => '0070bf')),
				'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
									'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
									'wrap' => true )
			);
			$sheet->mergeCells('B1:E1');
			$sheet->getStyle('B1')->applyFromArray($style);
			
			$sheet->setCellValue('B2', "TỔNG CÔNG TY VIỄN THÔNG VIETTEL");
			$style = array(
				'font' => array('size' => 12, 'name' =>'Cambria', 'color' => array('rgb' => '0070bf')),
				'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
									'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
									'wrap' => true )
			);
			$sheet->mergeCells('B2:E2');
			$sheet->getStyle('B2')->applyFromArray($style);
			
			
			$sheet->setCellValue('A4', "DANH SÁCH NGƯỜI DÙNG DO CỘNG TÁC VIÊN GIỚI THIỆU");
			$style = array(
				'font' => array('bold' => true, 'size' => 14, 'name' =>'Cambria'),
				'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
									'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
									'wrap' => true )
			);
			$sheet->mergeCells('A4:E4');
			$sheet->getStyle('A4')->applyFromArray($style);
			
			
			
			$style = array(
				'font' => array('size' => 11, 'name' =>'Cambria'),
				'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
									'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
									'wrap' => true),
				'borders' =>	array(
					'allborders' => array(
						'style' => \PHPExcel_Style_Border::BORDER_THIN
						)
				)
			);
			
			$sheet->setCellValue('B6', "Từ ngày: ".$data['daterange_start']);
			$sheet->setCellValue('C6', "Đến ngày: ".$data['daterange_end']);
			$sheet->setCellValue('B7', "Ngày kết xuất: ".date("d")."/".date("m")."/".date("Y"));
			$sheet->setCellValue('C7', "CTV: ".$data['fullname']);
			
			$sheet->getStyle('B6')->applyFromArray($style);
			$sheet->getStyle('C6')->applyFromArray($style);
			$sheet->getStyle('B7')->applyFromArray($style);
			$sheet->getStyle('C7')->applyFromArray($style);
			
			$sheet->setCellValue('A9', 'STT');
			$sheet->setCellValue('B9', 'Tên người dùng');
			$sheet->setCellValue('C9', 'Số thuê bao');
			$sheet->setCellValue('D9', 'Ngày giờ giới thiệu');
			$style = array(
				'font' => array('bold' => true, 'size' => 11, 'name' =>'Cambria'),
				'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
									'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
									'wrap' => true),
				'borders' =>	array(
					'allborders' => array(
						'style' => \PHPExcel_Style_Border::BORDER_THIN
						)
				)
			);
			$sheet->getStyle('A9:D9')->applyFromArray($style);
			
			$style = array(
				'font' => array('size' => 11, 'name' =>'Cambria'),
				'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
									'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
									'wrap' => true),
				'borders' =>	array(
					'allborders' => array(
						'style' => \PHPExcel_Style_Border::BORDER_THIN
						)
				)
			);
			
			$dem = 0;
			foreach ($users as $index => $user):
				$sheet->setCellValue('A' . ($dem + 10), $index + 1);
				$sheet->setCellValue('B' . ($dem + 10), $user['username']);
				$sheet->setCellValueExplicit('C' . ($dem + 10), $user['user_cellphone'], PHPExcel_Cell_DataType::TYPE_STRING);
				$sheet->setCellValue('D' . ($dem + 10), $user['user_created_time']);
				$sheet->getStyle('A' . ($dem + 10).':D'.($dem + 10))->applyFromArray($style);
				$dem++;
			endforeach;
			
			$writer = new PHPExcel_Writer_Excel5($this->phpexcel);
			header('Content-Type: application/vnd.ms-excel');
			header('Content-Disposition: attachment; filename="danhsachnguoidung_ctv_'.date('d/m/Y').'.xls"');
			$writer->save('php://output');
		}else{
			$this->load->view('login');
		}
	}
	
}
