<?php

require_once 'vendor/autoload.php';
require "./framework/error.inc.php";
define("IN_MOBILE", true);
require "./framework/bootstrap.inc.php";
if (empty($uniacid)) {
    $res = pdo_get("ewei_shop_domain_bindings", array("domain" => $_SERVER['HTTP_HOST']));
    if (!empty($res)) {
        $_W["uniacid"] = $res["uniacid"];
        $uniacid = $_W["uniacid"];
        $_GPC['i'] = $_W["uniacid"];
    } else {
        echo "域名未绑定!";
        exit;
    }
}
//echo '<pre>';
//print_r($_SERVER['HTTP_REFERER']);
//exit;

//这一行要放前面，因为有加载全局公共方法功能，下面要用到公共方法
$site = WeUtility::createModuleSite("ewei_shopv2");

//专馆需求-查询当前域名获取域名配置
$httpHost = $_SERVER['HTTP_HOST'];

//匹配域名后首个目录,如:www.gtrade365.com/balin/
preg_match(
    '/[\w\-_]+(\.[\w\-_]+){1,2}\/[\w\-_]+\/?/',
    $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
    $matches
);
$dirHost = $matches[0] ? : null;
// 末尾确保是带斜杠的
$dirHost = mb_substr($dirHost, -1) == '/' ? $dirHost : $dirHost . '/';

$res_gallery = pdo_fetch('select * from ' . tablename('ewei_shop_gallery') . ' where (domain=:httpHost or domain=:dirHost or domain_second=:domain_second or domain_second=:secondDirHost) and status=1', array(':httpHost' => $httpHost, ':dirHost' => $dirHost, ':domain_second' => $httpHost, ':secondDirHost' => $dirHost));
//    $res_gallery = pdo_get("ewei_shop_gallery", array("domain" => $_SERVER['HTTP_HOST'], "status" => 1));
if (!empty($res_gallery)) {
    $_W['gallery'] = $res_gallery;
    $_W['gallery']['systemSetting'] = [];//专馆--系统设置信息（ewei_shop_gallery_system_setting表数据）
    //获取专馆--系统设置信息（html里title,keywords,description等）
    $systemSetting = pdo_fetchall('select * from ' . tablename('ewei_shop_gallery_system_setting') . ' where gallery_id=' . $_W['gallery']['id'] . ' AND site_type=' . getSiteTypeByLang());
    if (!empty($systemSetting)) {
        foreach ($systemSetting as $v) {
            $_W['gallery']['systemSetting'][$v['type']] = $v;
        }
    }

    $cookie_key = 'ewei_shopv2_language_' . $_W['uniacid'];
    $oldLang = igetcookie($cookie_key);
    //新专馆(长沙机械)，不能是老的/?r= 这种链接方式
    if (in_array($_W['gallery']['id'],[15,16]) OR $_W['gallery']['is_gallery'] == 3) {
        $oldLangArr['zh_CN'] = '/zh';
        $oldLangArr['en_US'] = '';
        $fullurl = referer();
        $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $arr = parse_url($url);

        if ($_W['gallery']['is_gallery'] == 3) {
            //获取所有站点列表
            $_W['gallery']['siteList'] = pdo_fetchall('select * from ' . tablename('ewei_shop_gallery_cms_site') . ' where (gallery_id=:gallery_id and status=1)', array(':gallery_id' => $_W['gallery']['id']));

            //以下是为了获取站点信息
            $newLang = 'en_US';
            $tmp = isset($arr['path']) ? $arr['path'] : '';
            $_W['gallery']['siteInfo'] = [];
            $_W['gallery']['navigationList'] = [];
            $_W['gallery']['gcNavigationId'] = 0;
            if (!empty($tmp)) {
                $tmp = explode('/', $tmp);
                if (isset($tmp['1']) && !empty($tmp['1'])) {
                    $newLang = $tmp['1'];
                    if ($newLang == 'zh') {
                        $newLang = 'zh_CN';
                    } elseif ($newLang == 'tw') {
                        $newLang = 'zh_TW';
                    } elseif($tmp['1'] == 'en'){
                        $newLang = 'en_US';
                    } elseif($tmp['1'] == 'pc'){
                        $newLang = $oldLang;
                    } elseif (empty($newLang)) {
                        $newLang = $oldLang;
                    }
                }else{
                    $newLang = $oldLang;
                }
            }
            //获取站点信息--根据语言获取
            if(!empty($_W['gallery']['siteList'])) {
                if(count($_W['gallery']['siteList']) > 1) {
                    $_W['gallery']['siteInfo'] = pdo_fetch('select * from ' . tablename('ewei_shop_gallery_cms_site') . ' where (gallery_id=:gallery_id and language_code=:language_code and status=1)', array(':gallery_id' => $_W['gallery']['id'], ':language_code' => $newLang));
                    //没有语言对应站点信息--则获取其他语言的数据
                    if (empty($_W['gallery']['siteInfo'])) {
                        $newLang = 'en_US';
                        //有站点信息
                        if (!empty($_W['gallery']['siteList'])) {
                            //默认获取英文
                            $_W['gallery']['siteInfo'] = pdo_fetch('select * from ' . tablename('ewei_shop_gallery_cms_site') . ' where (gallery_id=:gallery_id and language_code=:language_code and status=1)', array(':gallery_id' => $_W['gallery']['id'], ':language_code' => $newLang));
                            if (empty($_W['gallery']['siteInfo'])) {    //英文也没有，获取最早的一个
                                $_W['gallery']['siteInfo'] = pdo_fetch('select * from ' . tablename('ewei_shop_gallery_cms_site') . ' where (gallery_id=:gallery_id and status=1)', array(':gallery_id' => $_W['gallery']['id']));
                            }
                        }
                    }
                } else {
                    $_W['gallery']['siteInfo'] = $_W['gallery']['siteList']['0'];
                }
            }
            if (!empty($_W['gallery']['siteInfo'])) {
                $_W['gallery']['siteInfo']['footer'] = !empty($_W['gallery']['siteInfo']['footer']) ? json_decode($_W['gallery']['siteInfo']['footer'], true) : '';
                $_W['gallery']['siteInfo']['header'] = !empty($_W['gallery']['siteInfo']['header']) ? json_decode($_W['gallery']['siteInfo']['header'], true) : '';
                $_W['gallery']['siteInfo']['mobile_header'] = !empty($_W['gallery']['siteInfo']['mobile_header']) ? json_decode($_W['gallery']['siteInfo']['mobile_header'], true) : '';
                $_W['gallery']['siteInfo']['mobile_footer'] = !empty($_W['gallery']['siteInfo']['mobile_footer']) ? json_decode($_W['gallery']['siteInfo']['mobile_footer'], true) : '';
                $newLang = $_W['gallery']['siteInfo']['language_code'];

                //根据站点信息获取导航
                $_W['gallery']['navigationList'] = pdo_fetchall('select `name`,`type`,`type_value`,`id` from ' . tablename('ewei_shop_gallery_cms_navigation') . ' where (gallery_id=:gallery_id and site_id=:site_id) ORDER BY `sort` ASC,id ASC', array(':gallery_id' => $_W['gallery']['id'], ':site_id' => $_W['gallery']['siteInfo']['id']));
                $_W['gallery']['gcNavigationId'] = $_GPC['gcNavigationId'];  //这是是导航id，为了导航栏哪个有选中效果
                if (!empty($_W['gallery']['navigationList'])) {
                    foreach ($_W['gallery']['navigationList'] as &$v) {
                        if ($v['type'] == 1) {
                            $tmp = [];
                            $tmp = pdo_fetch('select `style_id`,`id` as `page_id` from ' . tablename('ewei_shop_gallery_cms_page') . ' where (id=:id and status=1)', array(':id' => $v['type_value']));
                            $v['style_id'] = !empty($tmp) ? $tmp['style_id'] : 0;
                            $v['page_id'] = !empty($tmp) ? $tmp['page_id'] : 0;
                            //这里pcSeoUrl拿不到最新的cookie，所以不能生成链接
                        }
                    }
                }
            }

            if($_SERVER['REQUEST_URI'] == '/'){
                isetcookie($cookie_key, $newLang, 7 * 86400);
                $tmpurl = 'pc/index.html';
//                if ($newLang == 'zh_CN') {
//                    $tmpurl = 'zh'.$tmpurl;
//                } elseif ($newLang == 'zh_TW') {
//                    $tmpurl = 'tw'.$tmpurl;
//                } elseif($newLang == 'en_US'){
//                    $tmpurl = $tmpurl;
//                } elseif (!empty($newLang)) {
//                    $tmpurl = $newLang.$tmpurl;
//                }
                header('location:' . $url.$tmpurl);
                exit;
            }

//            链接里有?r=、&r=、以及只有域名、以及ajax请求都屏蔽 (直接带链接/tw、/en、/pc等进入)
            if (strstr($url, '?r=') == false && strstr($url, '&r=') == false && strlen($_SERVER['REQUEST_URI']) > 1 && !$_W['isajax']) {
                isetcookie($cookie_key, $newLang, 7 * 86400);
                if ($newLang != $oldLang) {
                    header('location:' . $url);
                }
            }
        }
        else{

            //链接里有?r=、&r=、以及只有域名、以及ajax请求都屏蔽 (直接带链接/tw、/en、/pc等进入)
            if (strstr($url, '?r=') == false && strstr($url, '&r=') == false && strlen($_SERVER['REQUEST_URI']) > 1 && !$_W['isajax']) {
                $newLang = 'en_US';
//                if (strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/zh/') == false && strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/tw') == false) { //英文链接
//                    $newLang = 'en_US';
//                    isetcookie($cookie_key, $newLang, 7 * 86400);
//                } elseif (strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/zh') != false || strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/tw') != false) { //中文链接
//                    $newLang = 'zh_CN';
//                    isetcookie($cookie_key, $newLang, 7 * 86400);
//                }

                if(strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/zh/') != false || strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/tw') != false){
                    $newLang = 'zh_CN';
                    isetcookie($cookie_key, $newLang, 7 * 86400);
                }elseif(strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/en/') != false){
                    $newLang = 'en_US';
                    isetcookie($cookie_key, $newLang, 7 * 86400);
                }elseif(strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/zh/') == false && strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/tw') == false && strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/en') == false){
                    $newLang = $oldLang == '' ? $newLang : $oldLang;
                }

                if ($newLang != $oldLang) {
                    header('location:' . $url);
                }
            }
        }
    }

    if($_W['gallery']['id'] == 14){
        if($oldLang == 'zh_TW'){
            $oldLang = 'zh_CN';
            isetcookie($cookie_key, $oldLang, 7 * 86400);
        }
    }
    unset($res_gallery);
    unset($systemSetting);
} else {
    $_W['gallery'] = [];
}

if ($_GPC['r'] == 'pc.goods.detail') {
    $goods = pdo_fetch('select * from ' . tablename('ewei_shop_goods') . ' where id=:id and uniacid=:uniacid limit 1', [':id' => $_GPC['id'], ':uniacid' => $_W['uniacid']]);
    $_W['goods'] = $goods;
}

//是否手机端
$_W['is_mobile'] = is_mobile();

require IA_ROOT . '/app/common/bootstrap.app.inc.php';
$_W["attachurl_local"] = $_W["siteroot"] . $_W["config"]["upload"]["attachdir"] . "/";
$_W["attachurl"] = $_W["attachurl_local"];
if (!empty($_W["setting"]["remote"][$_W["uniacid"]]["type"])) {
    $_W["setting"]["remote"] = $_W["setting"]["remote"][$_W["uniacid"]];
}
$info = uni_setting_load("remote", $uniacid);
if (!empty($info["remote"]) && $info["remote"]["type"] != 0) {
    $_W["setting"]["remote"] = $info["remote"];
}
if (!empty($_W["setting"]["remote"]["type"])) {
    if ($_W["setting"]["remote"]["type"] == ATTACH_FTP) {
        $_W["attachurl_remote"] = $_W["setting"]["remote"]["ftp"]["url"] . "/";
        $_W["attachurl"] = $_W["attachurl_remote"];
    } else {
        if ($_W["setting"]["remote"]["type"] == ATTACH_OSS) {
            $_W["attachurl_remote"] = $_W["setting"]["remote"]["alioss"]["url"] . "/";
            $_W["attachurl"] = $_W["attachurl_remote"];
        } else {
            if ($_W["setting"]["remote"]["type"] == ATTACH_QINIU) {
                $_W["attachurl_remote"] = $_W["setting"]["remote"]["qiniu"]["url"] . "/";
                $_W["attachurl"] = $_W["attachurl_remote"];
            } else {
                if ($_W["setting"]["remote"]["type"] == ATTACH_COS) {
                    $_W["attachurl_remote"] = $_W["setting"]["remote"]["cos"]["url"] . "/";
                    $_W["attachurl"] = $_W["attachurl_remote"];
                }
            }
        }
    }
}
header("ACCESS-CONTROL-ALLOW-ORIGIN:*");
if (empty($uniacid)) {
    exit("Access Denied.");
}
$_GPC["c"] = "site";
$_GPC["a"] = "entry";
$_GPC["m"] = "ewei_shopv2";
$_GPC["do"] = "mobile";
$_W["uniacid"] = (int)$_GPC["i"];
$_W["account"] = uni_fetch($_W["uniacid"]);
$_W["acid"] = (int)$_W["account"]["acid"];
$_GPC["r"] = isset($_GPC["r"]) ? str_replace("/", ".", $_GPC["r"]) : '';
if (strexists($_GPC["r"], "pc")) {
    $_GPC["r"] = str_replace("pc", "", $_GPC["r"]);
    $_GPC["r"] = str_replace("pc.", "", $_GPC["r"]);
}
if (!isset($_GPC["r"])) {
    $_GPC["r"] = "pc";
} else {
    $_GPC["r"] = "pc." . $_GPC["r"];
}
$_W["uniacid"] = $uniacid;

//其他网站登录此网站 姚翔宇 20221018
if (isset($_GPC['urlToken']) && !empty($_GPC['urlToken'])) {
    //因为$_GPC这种自动urldecode了，索引要重新encode
    otherDomainlogin(urlencode($_GPC['urlToken']), (isset($_GPC['urlSign']) && !empty($_GPC['urlSign'])) ? $_GPC['urlSign'] : 'gtrade365');

    //为了解决第一次进入右上角仍是未登录状态
    header('location:' . $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . str_replace('urlToken=', '', $_SERVER['REQUEST_URI']));
    exit;
}

//echo $_GPC['lang'];

$_W['config']['setting']['paypaytone_do_domain'] = $_W['config']['setting']['paypaytone'];
$_W['config']['setting']['gtradeai_do_domain'] = $_W['config']['setting']['gtradeai'];
if (multilingField() == 'en_US' OR empty(multilingField())) {
    $_W['config']['setting']['paypaytone_do_domain'] = $_W['config']['setting']['paypaytone_en'];
    $_W['config']['setting']['gtradeai_do_domain'] = $_W['config']['setting']['gtradeai_en'];
}

if (!is_error($site)) {
    $method = "doMobileMobile";
    $site->uniacid = $uniacid;
    $site->inMobile = true;
    if (method_exists($site, $method)) {
        $r = $site->{$method}();
        if (!empty($r)) {
            echo $r;
            exit;
        }
        exit;
    }
}
