<?php
$more = \Phpcmf\Service::L('cache')->get_auth_data('more_weixin', 1);
if (!$more) {
    $more = 1;
} else {
    // 防止丢失
    \Phpcmf\Service::L('cache')->set_auth_data('more_weixin', $more, 1);
}

if (isset($_GET['gzh_id']) && $_GET['gzh_id']) {
    $more = intval($_GET['gzh_id']);
}

$data = \Phpcmf\Service::L('cache')->get_file('app_weixin', $more); // 配置
if (!$data) {
    $more = 1;
}

define('WEIXIN_MORE_ID', $more);
define('WEIXIN_MORE_NAME', $data ? '【'.$data.'】' : '');

\Phpcmf\Hooks::on('cms_init', function() {
    // 微信中访问网站时，未登录时直接授权微信登录
	if (IS_API
        || IS_API_HTTP
        || in_array(APP_DIR, ['weixin', 'api', 'member'])
        || in_array(\Phpcmf\Service::L('Router')->class, ['register', 'login', 'api', 'go'])) {
		return;
	} elseif (!IS_MEMBER && !\Phpcmf\Service::C()->uid) {
        \Phpcmf\Service::C()->init_file('weixin');
		$config = \Phpcmf\Service::M('Weixin', 'Weixin')->get_config('config'); // 配置
		if (isset($config['autologin']) && $config['autologin']
			&& strpos((string)$_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            // 公众号内自动登陆
            if ($config['autologin'] == 1) {
                dr_redirect(SITE_URL.'index.php?s=weixin&c=go&url='.urlencode(FC_NOW_URL));
            } else {
                // 提示绑定：静默获取openid，已绑定则直接登录，未绑定则提示
                $openid = \Phpcmf\Service::L('input')->get_cookie('weixin_gzh_openid');
                if (!$openid) {
                    dr_redirect(SITE_URL.'index.php?s=weixin&c=go&m=check&url='.urlencode(FC_NOW_URL));
                } else {
                    $uid = 0;
                    $user = \Phpcmf\Service::M()->table(weixin_wxtable('user'))->where('openid', $openid)->getRow();
                    $oauth = \Phpcmf\Service::M()->table('member_oauth')->where('oauth', 'wechat')->where('oid', $openid)->getRow();
                    if (!$user || !$user['uid']) {
                        if ($oauth) {
                            $uid = $oauth['uid'];
                        }
                    } else {
                        $uid = $user['uid'];
                    }
                    if ($uid) {
                        $member = \Phpcmf\Service::M('member')->member_info($uid);
                        if ($member) {
                            $user && \Phpcmf\Service::M()->table(weixin_wxtable('user'))->update($user['id'], ['uid' => $uid]);
                            $oauth && \Phpcmf\Service::M()->table('member_oauth')->update($oauth['id'], ['uid' => $uid]);
                            \Phpcmf\Service::M('member')->save_cookie($member, 1);
                            XR_C()->_msg(1, dr_lang('自动登录成功'), FC_NOW_URL);
                        } else {
                            $user && \Phpcmf\Service::M()->table(weixin_wxtable('user'))->update($user['id'], ['uid' => 0]);
                            $oauth && \Phpcmf\Service::M()->table('member_oauth')->update($oauth['id'], ['uid' => 0]);
                            $uid = 0;
                            XR_C()->_msg(0, dr_lang('账号不存在，解绑成功'));
                        }
                    }
                    if (!$uid) {
                        $text = $config['bang_text'] ? $config['bang_text'] : '您还没有绑定本站账号，是否立即绑定？';
                        define('MY_WEIXIN_BIND_URL', SITE_URL.'index.php?s=weixin&c=go&url='.urlencode(FC_NOW_URL));
                        define('MY_WEIXIN_BIND_TEXT', $text);
                    }
                }
                
            }
			
		}
	}
});



\Phpcmf\Hooks::on('cms_view_end', function() {

    if (!defined('MY_WEIXIN_BIND_URL') || !MY_WEIXIN_BIND_URL) {
        return;
    } elseif (IS_AJAX || IS_API_HTTP || defined('SC_HTML_FILE')) {
        return;
    }

    $cookieName = 'weixin_bind_prompt';
    $today = date('Ymd', SYS_TIME);
    if (\Phpcmf\Service::L('input')->get_cookie($cookieName) == $today) {
        return;
    }
    \Phpcmf\Service::L('input')->set_cookie($cookieName, $today, 86400);

    $url = MY_WEIXIN_BIND_URL;
    $text = json_encode(MY_WEIXIN_BIND_TEXT, JSON_UNESCAPED_UNICODE);
    $script = '<script type="text/javascript">'
        .'(function(){'
        .'var _k='.json_encode($cookieName).',_d='.json_encode($today).';'
        .'if(document.cookie.indexOf(_k+"="+_d)>=0){return;}'
        .'document.cookie=_k+"="+_d+";path=/;max-age=86400";'
        .'if(typeof layer==="undefined"){return;}'
        .'layer.confirm('.$text.',{icon:3,shade:0.3,title:dr_lang("提示"),btn:[dr_lang("确定"),dr_lang("取消")]},function(index){'
        .'layer.close(index);window.location.href='.json_encode($url).';'
        .'});'
        .'})();'
        .'</script>';

    if (ob_get_level() > 0) {
        $html = ob_get_clean();
        if (stripos($html, '</body>') !== false) {
            $html = preg_replace('/<\/body>/i', $script.'</body>', $html, 1);
        } else {
            $html .= $script;
        }
        ob_start();
        echo $html;
    } else {
        echo $script;
    }
});
