<?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['id'] = $id;
            $data['statistics'] = $this->getStatistics($id);
            $data['content'] = $this->getCollaboratorsUsers(array(), $id);
            $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($filters = array(), $id = false) {

        $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;
        if (!$id) {
            $data['id'] = $this->uri->segment(4, 1);
        } else {
            $data['id'] = $id;
        }
	
        $data['keyword'] = "";
        $data['sorting_order'] = "sorting_desc";
        $data['sorting_field'] = "id";

        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['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() . "cong_tac_vien/thong_ke_nguoi_dung/trang/" ;
        $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);
    }

    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;
    }
	
}
