<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class ModUser extends Module {

	protected $_filters = array(
        'check_admin' => '{adddeliveryaddr}'
    );
	
    public function admin_list() {
        $this->_layout = 'content';

    	$user_data =& Pager::pageByObject('User');

        $this->assign('users', $user_data['data']);
        $this->assign('pager', $user_data['pager']);
    }

    public function admin_add() {
        $this->_layout = 'content';

        $this->assign('roles', Toolkit::loadAllRoles(array('guest')));
    }

    public function admin_create() {

        $user_info =@ ParamHolder::get('user', array());
        if (sizeof($user_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing user information!')));
            return '_result';
        }
        if ($user_info['passwd'] != $user_info['re_passwd']) {
            $this->assign('json', Toolkit::jsonERR(__('Password Mismatch!')));
            return '_result';
        }
        $user_info['passwd'] = sha1($user_info['passwd']);
        try {
            $o_user = new User();

            /* Check duplicates */
            if ($o_user->count("login=?", array($user_info['login'])) > 0) {
                $this->assign('json', Toolkit::jsonERR(__('User login name exists!')));
                return '_result';
            }
            if ($o_user->count("email=?", array($user_info['email'])) > 0) {
                $this->assign('json', Toolkit::jsonERR(__('User E-mail address exists!')));
                return '_result';
            }

            if ($user_info['active'] == '1') {
                $user_info['active'] = '1';
            } else {
                $user_info['active'] = '0';
            }
			if ($user_info['wizard'] == '1') {
                $user_info['wizard'] = '1';
            } else {
                $user_info['wizard'] = '0';
            }
            $user_info['s_role'] = '{'.$user_info['s_role'].'}';
            $o_user->set($user_info);
            $o_user->lastlog_time = 0;
            $o_user->lastlog_ip = '0.0.0.0';
            $o_user->rstpwdreq_time = 0;
            $o_user->rstpwdreq_rkey = '';
            $o_user->save();

            // Initialize user extend info
            $o_user_extend = new UserExtend();
            $o_user_extend->total_saving = '0.00';
            $o_user_extend->total_payment = '0.00';
            $o_user_extend->balance = '0.00';
            $o_user_extend->user_id = $o_user->id;
            $o_user_extend->save();

            // TODO: send registration mail
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_result';
        }

        $this->assign('json', Toolkit::jsonOK(array('forward' => Html::uriquery('mod_user', 'admin_list'))));
        return '_result';
    }

    public function admin_edit() {
        $this->_layout = 'content';

        $curr_user_id = trim(ParamHolder::get('u_id', '0'));
        if (intval($curr_user_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_error';
        }
        try {
            $curr_user = new User($curr_user_id);
            $this->assign('curr_user', $curr_user);

        	$this->assign('roles', Toolkit::loadAllRoles(array('guest')));
        } catch (Exception $ex) {
            $this->assign('json', $ex->getMessage());
            return ('_error');
        }
    }

    public function admin_update() {

        $user_info =@ ParamHolder::get('user', array());
        if (sizeof($user_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing user information!')));
            return '_result';
        }

        $passwd_changed = false;
        try {
            $o_user = new User($user_info['id']);

            if ($user_info['email'] != $o_user->email) {
                /* Check duplicates */
                if ($o_user->count("email=?", array($user_info['email'])) > 0) {
                    $this->assign('json', Toolkit::jsonERR(__('User E-mail address exists!')));
                    return '_result';
                }
            }

            if ($user_info['active'] == '1') {
                $user_info['active'] = '1';
            } else {
                $user_info['active'] = '0';
            }
            $user_info['s_role'] = '{'.$user_info['s_role'].'}';

            $o_user->set($user_info);

            /* Check password */
            $passwd_info =@ ParamHolder::get('passwd', array());
            if (sizeof($passwd_info) != 2) {
                $this->assign('json', Toolkit::jsonERR(__('Invalid Password!')));
                return '_result';
            }
            if (strlen(trim($passwd_info['passwd'])) > 0 ||
                strlen(trim($passwd_info['re_passwd'])) > 0) {
                if ($passwd_info['passwd'] == $passwd_info['re_passwd']) {
                    $o_user->passwd = sha1($passwd_info['passwd']);
                    $passwd_changed = true;
                }
            }

            $o_user->save();
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_result';
        }

        if ($passwd_changed && $o_user->login == SessionHolder::get('user/login')) {
        	SessionHolder::destroy();
        	$this->assign('json', Toolkit::jsonOK(array('forward' => 'index.php', 'selfpwd' => '1')));
        } else {
        	$this->assign('json', Toolkit::jsonOK(array('forward' => Html::uriquery('mod_user', 'admin_list'))));
        }
        return '_result';
    }

    public function admin_delete() {

        $curr_user_id = trim(ParamHolder::get('u_id', '0'));
        if (intval($curr_user_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_result';
        }
        try {
            $curr_user = new User($curr_user_id);
            if ($curr_user->login == SessionHolder::get('user/login')) {
                $this->assign('json', Toolkit::jsonERR(__('Cannot delete yourself!')));
                return '_result';
            } else {
                $curr_user->delete();
               // $db = MysqlConnection::get();
            	//$db->query('DELETE FROM es_user_extends WHERE user_id = ?',array($curr_user_id));
            }
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return ('_result');
        }

        $this->assign('json', Toolkit::jsonOK());
        return '_result';
    }

	public function chk_login_name() {
        $login =@ trim(ParamHolder::get('login', ''));
        if (strlen($login) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing login name!')));
            return '_result';
        }

        try {
            $o_user = new User();
            if ($o_user->count("login=?", array($login)) > 0) {
                $this->assign('json', Toolkit::jsonERR(__('User login name exists!')));
            } else {
                $this->assign('json', Toolkit::jsonOK(array('msg' => __('User login name available!'))));
            }
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
        }
        return '_result';
    }
    
    public function admin_toggle_active() {

        $curr_user_id = trim(ParamHolder::get('u_id', '0'));
        if (intval($curr_user_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_result';
        }
        $active = trim(ParamHolder::get('u_acti', '0'));
        if ($active != '1') {
            $active = '0';
        }
        try {
            $curr_user = new User($curr_user_id);
            if ($curr_user->login == SessionHolder::get('user/login') && $active == '0') {
                $this->assign('json', Toolkit::jsonERR(__('Cannot deactive yourself!')));
                return '_result';
            } else {
                $curr_user->active = $active;
                $curr_user->save();
            }
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return ('_result');
        }

        $this->assign('json', Toolkit::jsonOK(array('u_id' => $curr_user_id, 'u_acti' => $active)));
        return '_result';
    }

    public function admin_finance() {
        $this->_layout = 'content';

        $curr_user_id = trim(ParamHolder::get('u_id', '0'));
        if (intval($curr_user_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_error';
        }

        $o_user_ext = new UserExtend();
        $curr_user_ext =& $o_user_ext->find("user_id=?", array($curr_user_id));
        if (!$curr_user_ext) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_error';
        }
        $this->assign('curr_user_ext', $curr_user_ext);

        $user_transactions =& Pager::pageByObject('Transaction', "user_id=?", array($curr_user_id),
                "ORDER BY `action_time` DESC");
        $this->assign('transactions', $user_transactions['data']);
        $this->assign('pager', $user_transactions['pager']);
    }

    public function admin_financialop() {

        $trans_info =& ParamHolder::get('usermoney', array());
        if (sizeof($trans_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing money information!')));
            return '_result';
        }

        $curr_user_id = trim(ParamHolder::get('u_id', '0'));
        if (intval($curr_user_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_result';
        }

        try {
            $o_transaction = new Transaction();
            $o_transaction->set($trans_info);
            $o_transaction->action_time = time();
            $o_transaction->user_id = $curr_user_id;
            $o_transaction->save();

            $o_user_ext = new UserExtend();
            $curr_user_ext =& $o_user_ext->find("user_id=?", array($curr_user_id));
            if (!$curr_user_ext) {
                $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
                return '_result';
            }
            if (intval($trans_info['type']) == 1) {
                $curr_user_ext->total_saving = floatval($curr_user_ext->total_saving) + floatval($trans_info['amount']);
            } else if (intval($trans_info['type']) == 2) {
                $curr_user_ext->total_payment = floatval($curr_user_ext->total_payment) + floatval($trans_info['amount']);
            }
            $curr_user_ext->balance = floatval($curr_user_ext->total_saving) - floatval($curr_user_ext->total_payment);
            $curr_user_ext->save();
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_result';
        }

        $this->assign('json', Toolkit::jsonOK());
        return '_result';
    }

    // Delivery address functions
    public function adddeliveryaddr() {
        $this->_layout = 'content';
        $this->assign('success_action', 'close');
        $this->assign('content_title', __('New Delivery Address'));
        $this->assign('next_action', 'createdeliveryaddr');

        return '_delivery_addr_form';
    }
    
    public function admin_dashboard() {
   		$this->_layout = 'default';
    }
}
?>