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

require_once APPPATH.'libraries/HtmlClean/HTMLPurifier.auto.php';

class Api extends Public_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
        $this->load->model("user_model");
        $this->load->model("token_model");
        $this->load->model("branch_model");
        $this->load->model("workorder_model");
        $this->load->model("warning_model");
        $this->load->model("appauth_model");
        $this->load->library('MY_pagination');
        $this->load->helper(array('url', 'date', 'sms'));
    }

    public function get_token()
    {
        $msg = array();
        $appid = $this->input->get("appid", true);
        $secret = $this->input->get("secret", true);
        $appauth = $this->appauth_model->get_appauth_with_id($appid);
        if ($appid && $secret && $appauth && $secret == $appauth['secret'] && $appauth['status']=="10") {
            $data['token'] = $token = $this->create_token();
            $expires = new DateTime();
            $expires->modify("+2 hours");
            $data['expires_time'] = new MongoDB\BSON\UTCDateTime($expires->getTimestamp()*1000);
            if ($this->token_model->save_token($data)) {
                $msg['errcode'] = 0;
                $msg['errmsg'] = "ok";
                $msg['access_token'] = $token;
                $msg['expires_in'] = 7200;
            } else {
                $msg['errcode'] = 40013;
                $msg['errmsg'] = "invalid appid";
            }
        } else {
            $msg['errcode'] = 40013;
            $msg['errmsg'] = "invalid appid";
        }
        $this->response($msg);
    }

    public function upload_data()
    {
        $access_token = $this->input->get("access_token", true);
        $msg = array();
        if ($access_token && $this->token_exists($access_token)) {
            $json = $this->get_json();
            $data = json_decode($json, true);
            if(count($data)>=1){
                $upload_info = $data['upload_info'];
                $device = $data['device'];
                if($upload_info['type'] == "20"){
                    $branch_list = $data['data'];
                    if (count($branch_list) > 0) {
                        foreach ($branch_list as $key => $val) {
                            $val['device'] = $device;
                            $this->branch_model->save_branch($val);
                            $this->update_branch_cache();
                        }
                    }
                }elseif($upload_info['type'] == "10") {
                    $warning_list = $data['data'];
                    if (count($warning_list) > 0) {
                        $config = HTMLPurifier_Config::createDefault();
                        $purifier = new HTMLPurifier($config);
                        foreach ($warning_list as $key => $val) {
                            if(array_key_exists("warning_name",$val)){
                                $val['warning_name'] = $purifier->purify($val['warning_name']);
                            }
                            $val['status'] = "10";
                            $val['create_time'] = new MongoDB\BSON\UTCDateTime(time()*1000);
                            $val['device'] = $device;
                            $this->warning_model->insert_warning($val);
                        }
                    }
                }
            }
            $msg['errcode'] = 0;
            $msg['errmsg'] = "OK";
        } else {
            $msg['errcode'] = 40012;
            $msg['errmsg'] = "invalid access token";
        }
        $this->response($msg);
    }

    public function update_branch_cache(){
        $branch_list = $this->branch_model->select_branch();
        if($branch_list){
            $branch = array();
            foreach($branch_list as $key=>$val){
                $branch[$val['branch_id']] = $val;
            }
            $this->cache->save('branchs', $branch, 30000);
        }else{
            $this->cache->save('branchs', array(), 30000);
        }
    }

    public function get_status()
    {
        $access_token = $this->input->get("access_token", true);
        $msg = array();
        if ($access_token && $this->token_exists($access_token)) {
            $json = $this->get_json();
            $data = json_decode($json, true);
            if(array_key_exists("id",$data)){
                $ids = $data['id'];
                for($i = 0;$i<count($ids);$i++){
                    $waning = $this->warning_model->select_warning(array("status"),$ids[$i]);
                    if($waning){
                        if($waning['status'] == "40"){
                            $msg[$ids[$i]] = true;
                        }else {
                            $msg[$ids[$i]] = false;
                        }
                    }else{
                        $msg[$ids[$i]] = false;
                    }
                }
            }
            $msg['errcode'] = 0;
            $msg['errmsg'] = "OK";
        } else {
            $msg['errcode'] = 40012;
            $msg['errmsg'] = "invalid access token";
        }
        $this->response($msg);
    }

    public function get_login_url()
    {
        $access_token = $this->input->get("access_token", true);
        $msg = array();
        if ($access_token && $this->token_exists($access_token)) {
            $json = $this->get_json();
            $data = json_decode($json, true);
            $user_model = $this->user_model;
            //$user_model->set_collection_name("sso_users");
            if(array_key_exists('type',$data)) {
                if($data['type'] == 1 || $data['type'] == '1') {
                    if ($user_model->is_exists("username", $data['username'])) {
                        $info['last_login_time'] = new MongoDB\BSON\UTCDateTime(time() * 1000);
                        $info['code'] = $this->create_token();
                        $info['from'] = $data['from'];
                        $user_model->set_val($info, array("username" => $data['username']));
                        $msg["login_url"] = site_url("v1/api/sso_login?code=" . $info['code']);
                    } else {
                        $data['user_id'] = $this->create_id();
                        $data['status'] = "10";
                        $data['create_time'] = new MongoDB\BSON\UTCDateTime(time() * 1000);
                        $data['last_login_time'] = new MongoDB\BSON\UTCDateTime(time() * 1000);
                        $data['code'] = $this->create_token();
                        $user_model->insert_user($data);
                        $msg["login_url"] = site_url("v1/api/sso_login?code=" . $data['code']);
                    }
                    $msg['errcode'] = 0;
                    $msg['errmsg'] = "OK";
                }else{
                    $msg['errcode'] = 40013;
                    $msg['errmsg'] = "该类型的用户允许免登录!";
                }
            }else{
                $msg['errcode'] = 40014;
                $msg['errmsg'] = "参数错误,未知的用户类型!";
            }
        } else {
            $msg['errcode'] = 40012;
            $msg['errmsg'] = "invalid access token";
        }
        $this->response($msg);
    }

    public function sso_login(){
        $code = $this->input->get("code", true);
        $msg = array();
        $user_model = $this->user_model;
        //$user_model->set_collection_name("sso_users");
        $sso_user = $user_model->get_user_with_code($code);
        if($code &&  $sso_user){
            $sso_user['code'] = "";
            $rand = substr(md5(microtime()), rand(0, 26), 5);
            $session_data = array("user_id" => (string)$sso_user["user_id"], "current_key" => $rand, "username" => $sso_user['username'], "user_type" => $sso_user['user_type'], "from" => $sso_user['from']);
            $sso_user['last_login_time'] = new MongoDB\BSON\UTCDateTime(time()*1000);
            $user_model->update_user($sso_user);
            $this->session->set_userdata($session_data);
            redirect("main/index");
        }else{
            show_error("invalid code!");
        }
    }

    public function send_sms(){
        $access_token = $this->input->get("access_token", true);
        $msg = array();
        if ($access_token && $this->token_exists($access_token)) {
            $json = $this->get_json();
            $data = json_decode($json, true);
            if(count($data)==2 && array_key_exists("mobile",$data) && array_key_exists("content",$data)){
                for($i = 0; $i< count($data['mobile']);$i++){
                    $number = $data['mobile'][$i];
                    if(send_by_modem($this->cache->get('setting'),$number,$data['content'])){
                        $msg[$number]=true;
                    }else{
                        $msg[$number]=false;
                    }
                }
            }
            $msg['errcode'] = 0;
            $msg['errmsg'] = "OK";
        }else {
            $msg['errcode'] = 40012;
            $msg['errmsg'] = "invalid access token";
        }
        $this->response($msg);
    }

    private function create_token()
    {
        do {
            $salt = base_convert(bin2hex($this->security->get_random_bytes(64)), 11, 36);
            if ($salt === FALSE) {
                $salt = hash('sha256', time() . mt_rand());
            }
            $token = substr($salt, 0, config_item('key_length'));
        } while ($this->token_exists($token));
        return $token;
    }

    private function token_exists($token)
    {
        if ($token) {
            if ($this->token_model->find_token($token, new MongoDB\BSON\UTCDateTime(time()*1000))) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    private function get_json(){
        $postjson = file_get_contents('php://input');
        return $postjson;
    }
}