<?php

session_start(); // starts new or resumes existing session
Doo::loadModelAt('auser', 'admin');
Doo::loadModelAt('ausers', 'admin');
Doo::loadModel('users');
Doo::loadClass('profile');
Doo::loadClass('PasswordHash');
Doo::loadClass('mailer');
Doo::loadClass('measureauditact');
Doo::loadClass('project');
Doo::loadClass('actmeasure');
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

// 列表停用 编辑 重置密码
// 管理员权限管理
// 管理员修改密码
class AdminController extends DooController
{

    private $data, $users, $user, $profile, $ph, $userz, $mailer, $project, $actmeasure, $measureauditact;

    public function beforeRun($resource, $action)
    {
        if (!isset($_SESSION['auid'])) {
            return Doo::conf()->APP_URL . 'manage';
        }
    }

    public function __construct()
    {
        $this->users = new AUsers();
        $this->user = new AUser();
        $this->userz = new Users();
        $this->profile = new Profile();
        $this->mailer = new Mailer();
        $this->project = new Project();
        $this->actmeasure = new actMeasure();
        $this->measureauditact = new MeasureauditAct();
        $this->ph = new PasswordHash(8, FALSE);
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
    }

    function addUser()
    {
        $params = NULL;
        if (isset($_POST['email'])) {
            if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $postArray = $_POST;
                $passwdStr = $this->randomPassword();
                $postArray['userid'] = $this->users->createUser($_POST['email'], $passwdStr);
                if (isset($postArray['userid'])) {
                    $this->profile->insertProfile($postArray);
                    $this->mailer->setEmails($_POST['email']);
                    $this->mailer->seteTitle('新账号开通');
                    $this->mailer->setClientName($postArray['realname']);
                    $signupConfigStr = '<p>开通了计量支付云版的帐号：</p><p>登录帐号（邮箱）：<b><a href="mailto:' . $_POST['email'] . '" target="_blank">' . $_POST['email'] . '</a></b></p><p>登录密码：<b>' . $passwdStr . '</b></p><p>请及时登录并修改您的个人信息及密码。</p><p><b style="font-size:20px">登录云端，下载桌面软件：</b></p><p><a href="'.'http://' . $_SERVER['HTTP_HOST'].'" style="font-size:20px">'.'http://' . $_SERVER['HTTP_HOST'].'</a></p>';
                    $this->mailer->setContent($signupConfigStr);
                    $this->mailer->send_mail();
                    return Doo::conf()->APP_URL . 'manage/user/list';
                } else {
                    return Doo::conf()->APP_URL . 'manage/user/add';
                }
            } else {
                return Doo::conf()->APP_URL . 'manage/user/add';
            }
        }
        $this->data['menu'] = 3;
        $this->render('admin-addUser', $this->data, TRUE);
    }

    public function randomPassword()
    {
        $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }

    function editUser()
    {
        $this->data['users'] = $this->users->getOne(array('where' => 'uid = ?', 'param' => array($this->params['uid']), 'asArray' => TRUE));
        $this->data['profile'] = $this->profile->getProWithUid($this->params['uid']);
        if (isset($_POST['email']) && ($_POST['email'] != $this->data['users']['uemail']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            if (!$this->userz->getOne(array('where' => 'uemail = ?', 'param' => array($_POST['email']), 'asArray' => TRUE))) {
                $this->userz->uemail = $_POST['email'];
                $this->userz->update(array('where' => 'uid = ?', 'param' => array($this->params['uid'])));
            }
        }
        if(isset($_FILES['sign']) && !empty($_FILES['sign']['name']) && $_FILES['sign']['type'] == "image/png"){
            $dir = 'global/signpath';
            if ($_FILES['sign']['error'] > 0) {

            } else {
                $fileName = date("YmdHis") . '_' . floor(microtime() * 1000) . '_' . self::createRandomCode(8);
                $virtualPath = "$dir/php_sign_$fileName.jpg";
                move_uploaded_file($_FILES['sign']["tmp_name"], Doo::conf()->SITE_PATH .$virtualPath);
                $this->profile->setSignPath($this->params['uid'], $virtualPath);
            }
        }
        if (isset($_POST['company']) && isset($_POST['jobs']) && isset($_POST['name']) && isset($_POST['phone'])) {
            $this->profile->upProfile($this->params['uid'], $_POST);
            return Doo::conf()->APP_URL . 'manage/user/list';
        }

        //获取该用户审批标段，创建的标段，创建的项目
        $mnflist = $this->measureauditact->getUserPmid($this->params['uid']);
        if(!empty($mnflist)){
            foreach($mnflist as $k => $v){
                $pmmsg = $this->actmeasure->getRowByPmid($v['pmid']);
                $mnflist[$k]['pmname'] = $pmmsg['pmname'];
                $promsg = $this->project->getRowByPid($pmmsg['pid']);
                $mnflist[$k]['pname'] = $promsg['pname'];
            }
            $this->data['mnflist'] = $mnflist;
        }

        $mnflist2 = $this->actmeasure->getPmidRow($this->params['uid']);
        if(!empty($mnflist2)){
            foreach($mnflist2 as $k2 => $v2){
                $promsg = $this->project->getRowByPid($v2['pid']);
                $mnflist2[$k2]['pname'] = $promsg['pname'];
                $mnflist2[$k2]['intime'] = date('Y-m-d H:i:s',$v2['intime']);
            }
            $this->data['mnflist2'] = $mnflist2;
        }

        $prolist = $this->project->getRowUid($this->params['uid']);
        if(!empty($prolist)){
            foreach($prolist as $k3 => $v3){
                $prolist[$k3]['intime'] = date('Y-m-d H:i:s',$v3['intime']);
            }
            $this->data['prolist'] = $prolist;
        }
        $this->data['menu'] = 2;
        $this->render('admin-editUser', $this->data, TRUE);
    }

    function option()
    {
        $this->data['auser'] = $this->user->getOne(array('where' => 'auid = ?', 'param' => array($_SESSION['auid']), 'asArray' => TRUE));
        if (isset($_POST['oldpasswd']) && isset($_POST['newpasswd']) && isset($_POST['renewpasswd']) && ($_POST['newpasswd'] == $_POST['renewpasswd']) && $this->ph->CheckPassword($_POST['oldpasswd'], $this->data['auser']['aupass'])) {
            $this->user->upPasswWd($_SESSION['auid'], $this->ph->HashPassword($_POST['newpasswd']));
            return Doo::conf()->APP_URL . 'manage/user/list';
        }
        $this->render('admin-option', $this->data, TRUE);
    }

    function userSwitch()
    {
        $userzArray = $this->userz->getOne(array('where' => 'uid = ?', 'param' => array($this->params['uid']), 'asArray' => TRUE));
        if (isset($userzArray['uid']) && $userzArray['isstop']) {
            $this->userz->isstop = 0;
        } else {
            $this->userz->isstop = 1;
        }
        $this->userz->update(array('where' => 'uid = ?', 'param' => array($this->params['uid'])));
        return Doo::conf()->APP_URL . 'manage/user/list';
    }

    function userRepasswd()
    {
        $userzArray = $this->userz->getOne(array('where' => 'uid = ?', 'param' => array($this->params['uid']), 'asArray' => TRUE));
        if (isset($userzArray['uemail'])) {
            $passwdStr = $this->randomPassword();
            $this->userz->upass = $this->ph->HashPassword($passwdStr);
            if ($this->userz->update(array('where' => 'uid=?', 'param' => array($this->params['uid'])))) {
                $proArray = $this->profile->getProWithUid($this->params['uid']);
                $this->mailer->setEmails($userzArray['uemail']);
                $this->mailer->seteTitle('密码重置');
                $this->mailer->setClientName($proArray['name']);
                $signupConfigStr = '<p>重置了计量支付云版的帐号密码：</p><p>登录帐号（邮箱）：<b><a href="mailto:' . $userzArray['uemail'] . '" target="_blank">' . $userzArray['uemail'] . '</a></b></p><p>登录密码：<b>' . $passwdStr . '</b></p><p>请及时登录并修改您的新密码。</p>';
                $this->mailer->setContent($signupConfigStr);
                $this->mailer->send_mail();
                echo $userzArray['uemail'];
            }
        }
    }

    function userList()
    {
        if (isset($_SESSION['passwd'])) {
            echo '添加用户的密码是：' . $_SESSION['passwd'];
        }
        $this->data['userlist'] = $this->users->getRowAll();
        foreach ($this->data['userlist'] as $key => $value) {
            $proArray = $this->profile->getProWithUid($value['uid']);
            if (isset($proArray)) {
                $this->data['userlist'][$key]['name'] = $proArray['name'];
                $this->data['userlist'][$key]['company'] = $proArray['company'];
                $this->data['userlist'][$key]['jobs'] = $proArray['jobs'];
                $this->data['userlist'][$key]['remark'] = $proArray['remark'];
                $this->data['userlist'][$key]['phone'] = $proArray['phone'];
                $this->data['userlist'][$key]['mobile'] = $proArray['mobile'];
                $this->data['userlist'][$key]['isstop'] = $value['isstop'];
            }
            unset($proArray);
            $this->data['userlist'][$key]['email'] = $value['uemail'];
        }
        $this->data['menu'] = 2;
        $this->render('admin-userlist', $this->data, TRUE);
    }

    /*     * ************************************************************
    *  生成指定长度的随机码。
    *  @param int $length 随机码的长度。
    *  @access public
    * ************************************************************ */

    function createRandomCode($length)
    {
        $randomCode = "";
        $randomChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for ($i = 0; $i < $length; $i++) {
            $randomCode .= $randomChars{mt_rand(0, 35)};
        }
        return $randomCode;
    }

}
