<?php

class Default_RegisterController extends Ec_Controller_DefaultAction
{
    // --------------------------------------------------------------------
    public function preDispatch()
    {
        $this->tplDirectory = "default/views/register/";
    }

    // --------------------------------------------------------------------

    /**
     * 注册首页
     * @access  public
     * @return  resource
     */
    public function indexAction()
    {
        $session = new Zend_Session_Namespace('RegisterStep');
        $session->step = '0';
        $customer_type = $this->_request->getParam("customer_type", "");
        $this->view->customer_type = $customer_type;
        echo Ec::renderTpl($this->tplDirectory . "index.tpl", 'layoutqy');
    }

    // --------------------------------------------------------------------

    /**
     * 注册步骤
     *
     */
    public function stepAction()
    {
        $current = $this->getRequest()->getParam('current');
        $session = new Zend_Session_Namespace('register');

        if (empty($session->data)) {
            $this->_redirect('/register');
        }
        $this->view->data = $session->data;
        $sessioCurrentStep = $session->data['current'];
        if ($current != $sessioCurrentStep) {
            $this->_redirect('/register/step?current=' . $sessioCurrentStep);
        }
        $this->view->customer = Service_Customer::getByField($session->data['code'], "customer_code", "*");
        switch ($current) {
            case '2':
                echo Ec::renderTpl($this->tplDirectory . "step2.tpl", 'layoutqy2');
                break;
            case '3_1':
                if (!($this->getRequest()->isPost() && $this->getRequest()->getParam('is_agree'))) {
                    $this->_redirect('/register/step?current=3');
                }
                $this->view->currency = Common_DataCache::getCurrency();
                $this->view->country = Common_DataCache::getCountry();
                echo Ec::renderTpl($this->tplDirectory . "step3_1.tpl", 'layoutqy2');
                break;
            case '3':
                $this->view->currency = Common_DataCache::getCurrency();
                $this->view->country = Common_DataCache::getCountry();
                echo Ec::renderTpl($this->tplDirectory . "step3.tpl", 'layoutqy2');
                break;
            case '4':
                echo Ec::renderTpl($this->tplDirectory . "step4.tpl", 'layoutqy2');
                break;
        }
    }

    // --------------------------------------------------------------------

    /**
     * 邮件激活
     *
     */
    public function activateAction()
    {
        $code = trim($this->getRequest()->getParam('code'));
        if (empty($code) || strlen($code) != 12) {
            die("<script>alert('验证链接无效！');window.history.back();</script>");
        }
        $result = Service_Customer::getCustomQuery('*', 'where customer_activate_code = ?', $code);
        if (!$result) {
            die("<script>alert('验证链接无效！');window.history.back();</script>");
        }
        if (!empty($result[0]['customer_activate_code']) && ($result[0]['customer_activate_code'] == $code) && ($result[0]['reg_step'] == 1)) {
            $data = array(
                //'customer_activate_code'	=> 0,
                'reg_step' => 2
            );
            $state = Service_Customer::update($data, $result[0]['customer_id'], 'customer_id');
            if ($state) {
                $session = new Zend_Session_Namespace('register');
                $session->data = array(
                    'id' => $result[0]['customer_id'],
                    'code' => $result[0]['customer_code'],
                    'email' => $result[0]['customer_email'],
                    'current' => 3
                );
                $this->_redirect('/register/step?current=3');
            }
        } else {
            if (!empty($result[0]['customer_activate_code']) && ($result[0]['customer_activate_code'] == $code) && ($result[0]['reg_step'] > 1)) {
                $session = new Zend_Session_Namespace('register');
                $step = 3;
                if ($result[0]['reg_step'] == '3') {
                    //unset($session);
                    $session->unsetAll();
                    $this->_redirect('/login');
                }
                $session->data = array(
                    'id' => $result[0]['customer_id'],
                    'code' => $result[0]['customer_code'],
                    'email' => $result[0]['customer_email'],
                    'current' => $step
                );
                $this->_redirect('/register/step?current=' . $result[0]['reg_step']);
            }
        }
        die("<script>alert('验证链接无效！');window.history.back();</script>");
    }

    // --------------------------------------------------------------------

    /**
     * 保存注册账号
     *
     */
    public function saveAction()
    {
        $time = date('Y-m-d H:i:s');
        $name = $this->_request->getParam('username', '');
        $pwd = $this->_request->getParam('userpwd', '');
        $repwd = $this->_request->getParam('repwd', '');
        $customer_type = $this->_request->getParam("customer_type", "");
        $registerRow = array(
            'customer_password' => $pwd,
            're_password' => $repwd,
            'customer_email' => $name,
            'customer_activate_code' => substr(md5($time), 0, 12),
            'reg_step' => 1,
            'verify' => $this->_request->getParam('verify', ''),
            'customer_type' => $customer_type,
            'check_verify' => 1,
        );
        //print_r($registerRow);
        $process = new Service_CustomerProcess();
        $result = $process->createTransaction($registerRow);
        if ($result['ask'] == '0') {
            /*die("<script>alert('');window.history.back();</script>"); */

        } else {
            $session = new Zend_Session_Namespace('register');
            $session->data = array(
                'id' => $result['customer_id'],
                'code' => $result['customer_code'],
                'email' => $name,
                'current' => 2
            );
            //$this->_redirect('/register/step?current=2');
        }
        echo json_encode($result);
        exit;

        /*

        exit;

        $verify	= new Common_Verifycode();
        $value	= $this->getRequest()->getParam('verify');
        $state	= $verify->is_true($value);
        if ($state) {
            $time	= date('Y-m-d H:i:s');
            $name	= $this->getRequest()->getParam('username');
            $pwd	= $this->getRequest()->getParam('userpwd');
            $state	= Service_Customer::getByField($name, 'customer_email', 'customer_id');
            if (is_array($state)) {
                die("<script>alert('邮件已被使用，请重新填写！');window.history.back();</script>");
            }
            $mark	= new Common_Customer();
            $code	= $mark->markCustomCode('register');
            if (empty($code)) {
                die("<script>alert('生成编码失败，请重新填写！');window.history.back();</script>");
            }
            $lastId	= Service_Customer::add(
                array(
                    'customer_code'			=> $code,
                    'customer_password'		=> md5($pwd),
                    'customer_email'		=> $name,
                    'customer_activate_code'=> substr(md5($time),0,12),
                    'reg_step'				=> 1,
                    'customer_reg_time'		=> $time
                )
            );
            if (empty($lastId)) {
                die("<script>alert('保存数据出错，请重新填写！');window.history.back();</script>");
            }
            $state	= Common_Email::send(array(
                'email'		=> $name,
                'subject'	=> '注册账户验证--OMS',
                'bodyType'	=> 'html',
                'body'		=> '请复制该链URL接至浏览器进行访问激活账户！<br/>链接地址：http://192.168.25.128:6666/register/activate?code='.substr(md5($time),0,12)
            ));
            if (empty($state)) {
                die("<script>alert('验证邮件发送失败，请重新填写！');window.history.back();</script>");
            }
            $session= new Zend_Session_Namespace('register');
            $session->data	= array(
                'id'		=> $lastId,
                'code'		=> $code,
                'email'		=> $name,
                'current'	=> 2
            );
            $this->_redirect('/register/step?current=2');
        } else {
            die("<script>alert('验证码错误，请重新填写！');window.history.back();</script>");
        }
       */
    }

    // --------------------------------------------------------------------

    /**
     * 重发验证
     *
     */
    public function resendAction()
    {
        $session = new Zend_Session_Namespace('register');
        if (empty($session)) {
            $this->_redirect('/login');
        }
        $id = $session->data['id'];
        $email = $session->data['email'];
        $code = substr(md5(date('Y-m-d H:i:s')), 0, 12);
        $state = Service_Customer::update(array('customer_activate_code' => $code), $id, 'customer_id');
        if (!empty($state)) {

            $activeurl = 'http://' . $_SERVER['HTTP_HOST'] . '/register/activate?code=' . $code;

            $activeHtml = "<a href='$activeurl' target='_blank'>请点击此链接激活您的账户</a>";
            $params = array(
                'bodyType' => 'html',
                'email' => array($email),
                'subject' => '[深圳市招海国际货运代理有限公司]账号激活通知',
                'body' => "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您注册的邮箱是：{$email},<br/>感谢您的注册，{$activeHtml}。<br/>或者复制以下链接到浏览器进行激活：{$activeurl}",
            );
            $state = Common_Email::sendMail($params);
            /* $state	= Common_Email::send(array(
                'email'		=> $email,
                'subject'	=> '注册账户验证--OMS',
                'bodyType'	=> 'html',
                'body'		=> '请复制该链URL接至浏览器进行访问激活账户！<br/>链接地址：http://192.168.25.128:6666/register/activate?code='.$code
            )); */
        }
        if (empty($state)) {
            die("<script>alert('验证邮件发送失败，请重新填写！');window.history.back();</script>");
        } else {
            die("<script>alert('验证邮件发送成功，请您查收！');window.history.back();</script>");
        }
    }

    // --------------------------------------------------------------------

    /**
     * 完善资料
     *
     */
    public function completeAction()
    {
        $session = new Zend_Session_Namespace('register');
        if ($this->getRequest()->isPost() && !empty($session->data)) {
            $imgs = array();
            $fields = empty($_FILES) ? '' : array_keys($_FILES);
            //$path	= './upload/images';
            $path = APPLICATION_PATH . '/../data/images/register/' . $session->data['code'];

            $isDir = Common_Common::createPath($path);
            if ((isset($_FILES['license']) && !$_FILES['license']) || (isset($_FILES['identity']) && !$_FILES['identity'])) {
                //$result = array("ask"=>0,"message"=>"营业执照和身份证必须上传",'error'=>array());
                //$result['error'][] = "营业执照和身份证必须上传";
                /* echo json_encode($result);
                exit; */

            }

            /* if(!$_FILES['customlsn'] || !$_FILES['customlsn']){
                $result = array("ask"=>0,"message"=>"报关注册登记证必须上传",'error'=>array());
                $result['error'][] = "报关注册登记证必须上传";
                echo json_encode($result);
                exit;

            } */
            if ($isDir && !empty($fields)) {
                foreach ($fields as $field) {
                    $state = Common_Common::uploadImg($_FILES, $field, $path);
                    if ($state['error']) {
                        $msg = strip_tags($state['msg']);
                        $result = array("ask" => 0, "message" => $msg, 'error' => array());
                        $result['error'][] = $msg;
                        echo json_encode($result);
                        exit;
                    }
                    $imgs[$field] = $state['msg']['file_name'];
                }
            }

            $id = $session->data['id'];
            $code = $session->data['code'];
            $email = $session->data['email'];
            $parms = $this->getRequest()->getParams();
            $base = array(
                'customer_company_name' => $parms['companyname'],
                'trade_name' => isset($parms['trade_name']) ? $parms['trade_name'] : "",
                'trade_co' => isset($parms['trade_co']) ? $parms['trade_co'] : "",
                //'customer_customs_hscode'	=> $parms['customscode'],
                'customer_currency' => isset($parms['currency']) ? $parms['currency'] : "",
                'customer_license' => empty($imgs['license']) ? '' : $imgs['license'],
                'customer_idcard' => empty($imgs['identity']) ? '' : $imgs['identity'],
                'customer_customlsn' => empty($imgs['customlsn']) ? '' : $imgs['customlsn'],

                'customer_firstname' => empty($parms['firstname']) ? '' : $parms['firstname'],
                'customer_lastname' => empty($parms['lastname']) ? '' : $parms['lastname'],
                'customer_telephone' => empty($parms['telphone']) ? '' : $parms['telphone'],
                'customer_fax' => empty($parms['fax']) ? '' : $parms['fax'],
                'reg_step' => 3,
                'customer_country' => empty($parms['country']) ? '' : $parms['country'],
                'customer_province' => empty($parms['province']) ? '' : $parms['province'],
                'customer_city' => empty($parms['city']) ? '' : $parms['city'],
                'customer_postno' => empty($parms['postno']) ? '' : $parms['postno'],
                'customer_address' => empty($parms['address']) ? '' : $parms['address'],
                'customer_provision' => empty($parms['provision']) ? '' : $parms['provision'],
                'customer_signature' => empty($parms['signature']) ? '' : $parms['signature'],


            );
            $book = array(
                'customer_id' => $id,
                'customer_code' => $code,
                'cab_country_id' => $parms['country'],
                'cab_firstname' => empty($parms['firstname']) ? '' : $parms['firstname'],
                'cab_lastname' => empty($parms['lastname']) ? '' : $parms['lastname'],
                'cab_state' => empty($parms['state']) ? '' : $parms['state'],
                'cab_city' => empty($parms['city']) ? '' : $parms['city'],
                'cab_postcode' => empty($parms['postcode']) ? '' : $parms['postcode'],
                'cab_street_address1' => empty($parms['address']) ? '' : $parms['address']
            );
            $process = new Service_CustomerProcess();
            $result = $process->completeTransaction($parms, $imgs);

            if ($result['ask'] == '1') {
                $session->data = array(
                    'id' => $id,
                    'code' => $code,
                    'email' => $email,
                    'current' => 4
                );

            }

            echo json_encode($result);
            exit;


        }
        $this->_redirect('/register');
    }

    // --------------------------------------------------------------------

    /**
     * 验证码
     *
     */
    public function verifyCodeAction()
    {
        $verify = new Common_Verifycode();
        $verify->set_img_size(85, 20);
        echo $verify->render();
    }
}
/* End of file RegisterController.php */
/* Location: /application/modules/default/controllers/RegisterController.php */