<?php
namespace addons\group_buy\controller\clientarea;

class IndexController extends \app\home\controller\PluginHomeBaseController
{
    public $data;
    public $theme = "/ajax";
    public $priceNameArray = ["annually", "biennially", "triennially", "fourly", "fively"];
    public $Api;
    public function initialize()
    {
        parent::initialize();
        $this->Api = new \addons\group_buy\GroupBuyPlugin();
        $this->data = $_POST;
    }
    public function success($arr)
    {
        echo json_encode(["status" => 1, "encrypt" => 1, "info" => $arr]);
        exit;
    }
    public function error($arr)
    {
        echo json_encode(["status" => 0, "info" => $arr]);
        exit;
    }
    public function index()
    {
        $User = request()->uid;
        if (empty($User)) {
        }
        if (empty($User)) {
            $this->assign("msg", "登录失效，请重新登录");
            return $this->fetch("/error");
        }
        if (!empty($this->data)) {
            switch ($this->data["action"]) {
                case "get":
                    $List = ["two" => \Think\Db::name("group_buy_gzhx")->alias("a")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,'two' as e_type,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("a.end_time", ">=", date("Y-m-d"))->where("a.two", ">", 0)->select()->toArray(), "three" => \Think\Db::name("group_buy_gzhx")->alias("a")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,'three' as e_type,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("a.end_time", ">=", date("Y-m-d"))->where("a.three", ">", 0)->select()->toArray(), "five" => \Think\Db::name("group_buy_gzhx")->alias("a")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,'five' as e_type,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("a.end_time", ">=", date("Y-m-d"))->where("a.five", ">", 0)->select()->toArray()];
                    foreach ($List as $key => $value) {
                        foreach ($value as $kk => $vv) {
                            $List[$key][$kk]["description"] = strip_tags(htmlspecialchars_decode($vv["description"]));
                            $List[$key][$kk]["config_cn"] = strip_tags($vv["config_cn"]);
                            $join = \Think\Db::name("group_buy_gzhx_user")->where("uid", "=", $User)->where("type", "=", $key)->where("status", "=", 1)->where("aid", "=", $vv["id"])->where("uuid", ">", 0)->value("uuid") ?: NULL;
                            if (!empty($join)) {
                                $join = bin2hex(openssl_encrypt($join, "aes-128-cbc", "A89VB9PXBXJZ7834", true, "A89VB9PXBXJZ7835"));
                            }
                            $List[$key][$kk]["join"] = $join ?: NULL;
                        }
                    }
                    $this->success($List);
                    exit;
                    break;
                default:
                    $this->error($this->data["action"] . "参数不存在");
                    exit;
            }
        } else {
            $this->assign("Title", "拼团秒杀");
            return $this->fetch("/index");
        }
    }
    public function my()
    {
        $User = request()->uid;
        if (empty($User)) {
        }
        if (empty($User)) {
            $this->assign("msg", "登录失效，请重新登录");
            return $this->fetch("/error");
        }
        if (!empty($this->data)) {
            switch ($this->data["action"]) {
                case "get":
                    $Page = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
                    $count = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->field("a.*,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.uid", "=", $User)->where("e.uuid", ">", 0)->count();
                    $groups = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("clients f", "f.id=e.uid")->join("pricing b", "c.id=b.relid")->field("a.*,e.uid as e_uid,e.uuid as e_uuid,e.product_id as e_product_id,f.username,e.add_time as e_add_time,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.uid", "=", $User)->where("e.uuid", ">", 0)->order("e.id desc")->page($Page . ",20")->select()->toArray();
                    foreach ($groups as $key => $vv) {
                        $groups[$key]["description"] = strip_tags(htmlspecialchars_decode($vv["description"]));
                        $groups[$key]["config_cn"] = strip_tags($vv["config_cn"]);
                        $groups[$key]["join"] = bin2hex(openssl_encrypt($vv["e_uuid"], "aes-128-cbc", "A89VB9PXBXJZ7834", true, "A89VB9PXBXJZ7835"));
                    }
                    $this->success(["data" => $groups, "limit" => 20, "page" => $Page, "count" => $count]);
                    exit;
                    break;
                default:
                    $this->error($this->data["action"] . "参数不存在");
                    exit;
            }
        } else {
            $this->assign("Title", "我的拼团");
            return $this->fetch("/my");
        }
    }
    public function getClientIP()
    {
        global $ip;
        if (getenv("HTTP_CLIENT_IP")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")) {
                $ip = getenv("HTTP_X_FORWARDED_FOR");
            } else {
                if (getenv("REMOTE_ADDR")) {
                    $ip = getenv("REMOTE_ADDR");
                } else {
                    $ip = "Unknow";
                }
            }
        }
        return $ip;
    }
    public function admin()
    {
        $ip = $this->getClientIP();
        $data = json_decode(file_get_contents("php://input"), true);
        $Admin = $data["Admin"];
        setcookie("admin_username", $Admin["user_login"], false, "/");
        setcookie("SameSite", "Lax", false, "/");
        $ip = $this->getClientIP();
        $token = cmf_generate_user_token($Admin["id"], "web");
        sessionInit();
        session_start();
        session("ADMIN_ID", $Admin["id"]);
        session("name", $Admin["user_login"]);
        session("admin_login_info", md5($ip));
        session("token", $token);
        $this->success("OK");
    }
    public function activity()
    {
        if (!empty($this->data)) {
            $action = $this->data["action"];
            if (empty($action)) {
                $action = "";
            }
            switch ($action) {
                case "save":
                    $User = request()->uid;
                    if (empty($User)) {
                        $this->error("login");
                        exit;
                    }
                    if (!empty($this->data["data"]["id"])) {
                        $gid = openssl_decrypt(hex2bin($this->data["data"]["id"]), "aes-128-cbc", "A89VB9PXBXJZ7834", true, "A89VB9PXBXJZ7835");
                        if (!empty($gid)) {
                            $info = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,e.id as e_id,e.status as e_status,e.add_time as e_add_time,e.end_time as e_end_time,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.id", "=", $gid)->where("e.uuid", "=", 0)->where("a.end_time", ">=", date("Y-m-d"))->find();
                            if (!empty($info)) {
                                $outTime = strtotime($info["e_end_time"]) - time();
                                if ($outTime < 0) {
                                    $this->error("当前活动已结束");
                                    exit;
                                }
                                $outTimeConfig["time"] = $outTime;
                                $outTimeConfig["day"] = mb_substr("00" . floor($outTime / 86400), -2, NULL, "UTF-8");
                                $outTimeConfig["hour"] = mb_substr("00" . floor($outTime % 86400 / 3600), -2, NULL, "UTF-8");
                                $outTimeConfig["minute"] = mb_substr("00" . floor($outTime % 3600 / 60), -2, NULL, "UTF-8");
                                $info["outTimeConfig"] = $outTimeConfig;
                                $num = 2;
                                switch ($info["e_type"]) {
                                    case "two":
                                        $num = 2;
                                        break;
                                    case "three":
                                        $num = 3;
                                        break;
                                    case "five":
                                        $num = 5;
                                        break;
                                    default:
                                        $info["max_num"] = $num;
                                        $f = \Think\Db::name("group_buy_gzhx_user")->where("uid", "=", $User)->where("status", "<", 3)->where("uuid", "=", $info["e_id"])->find();
                                        $PayPrice = $info[$info["e_type"]];
                                        if (empty($f)) {
                                            $clients = \Think\Db::name("clients")->where("id", $User)->find();
                                            if (floatval($clients["credit"]) - floatval($PayPrice) < 0) {
                                                $this->error("pay");
                                                exit;
                                            }
                                            \Think\Db::startTrans();
                                            try {
                                                $InvoicesId = \Think\Db::name("Invoices")->insertGetId(["uid" => $User, "invoice_num" => date("YmdHis") . mt_rand(10000, 999999), "create_time" => time(), "subtotal" => $PayPrice, "status" => "Paid", "credit" => $PayPrice, "payment" => "UserCustom", "type" => "product"]);
                                                $payInfo = $info["pay_type"] == "monthly" ? "月" : "年";
                                                $InvoicesItemsId = \Think\Db::name("InvoiceItems")->insertGetId(["uid" => $User, "invoice_id" => $InvoicesId, "description" => "参与拼团活动#" . $info["id"] . "，商品：" . $info["name"] . "，原价：" . $info[$info["pay_type"]] . "元，拼团价：" . $PayPrice . "元，拼团人数：" . $num . "人", "rel_id" => 0, "amount" => $PayPrice, "payment" => "UserCustom", "type" => "host"]);
                                                $CreditId = \Think\Db::name("Credit")->insertGetId(["uid" => $User, "create_time" => time(), "description" => "Credit Applied to Invoice #" . $InvoicesId, "relid" => $InvoicesId, "amount" => $PayPrice]);
                                                $insert = ["uid" => $User, "uuid" => $info["e_id"], "num" => 1, "aid" => $info["id"], "type" => $info["e_type"], "add_time" => $info["e_add_time"], "end_time" => $info["e_end_time"], "invoices_id" => $InvoicesId];
                                                $id = \Think\Db::name("group_buy_gzhx_user")->insertGetId($insert);
                                                \Think\Db::name("clients")->where("id", $User)->setDec("credit", $PayPrice);
                                                \Think\Db::name("group_buy_gzhx_user")->where("id", "=", $info["e_id"])->setInc("num", 1);
                                                $info["e_num"] = \Think\Db::name("group_buy_gzhx_user")->where("id", "=", $info["e_id"])->value("num");
                                                \Think\Db::commit();
                                            } catch (\Matrix\Exception $e) {
                                                \Think\Db::rollback();
                                                $this->error(var_export($e, true));
                                            }
                                        }
                                        if ($num <= intval($info["e_num"])) {
                                            $list = \Think\Db::name("group_buy_gzhx_user")->alias("e")->join("group_buy_gzhx a", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,c.host as c_host,e.uid as e_uid,e.id as e_id,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.uuid", "=", $gid)->where("e.status", "=", 1)->where("a.end_time", ">=", date("Y-m-d H:i:s"))->select()->toArray();
                                            $postData = [];
                                            $login = $this->Api->login();
                                            foreach ($list as $key => $item) {
                                                $configoptions = [];
                                                if (!empty($item["option"])) {
                                                    $optionData = json_decode($item["option"], true);
                                                    foreach ($optionData as $kk => $vv) {
                                                        $option_id = mb_substr($kk, 7, NULL, "UTF-8");
                                                        if (!strstr($option_id, "_children")) {
                                                            if (array_key_exists($kk . "_children", $optionData)) {
                                                                $configoptions[$option_id] = $optionData[$kk . "_children"];
                                                            } else {
                                                                $configoptions[$option_id] = $vv;
                                                            }
                                                        }
                                                    }
                                                }
                                                $clientsUser = \Think\Db::name("clients")->where("id", "=", $item["e_uid"])->find();
                                                $postData = ["username" => $clientsUser["username"], "uid" => $item["e_uid"], "payment" => "UserCustom", "status" => "Pending", "adminorderconf" => 1, "admingenerateinvoice" => 1, "adminsendinvoice" => 1, "use_credit" => 0, "ops" => [["pid" => $item["pid"], "billingcycle" => $item["pay_type"], "qty" => 1, "configoptions" => $configoptions, "os" => []]]];
                                                if (intval($info["renew"]) == 2) {
                                                    $postData["ops"][0]["interior_price_renew"] = $PayPrice;
                                                }
                                                $res = $this->Api->curl("/zjmfAdmin/order/create?request_time=" . time(), "POST", $postData, 30, ["Content-Type: application/json; charset=utf-8", "Cookie: admin_username=" . $login["admin"] . "; SameSite=Lax; PHPSESSID=" . $login["token"]], true);
                                                $res = json_decode($res["info"], true);
                                                $invoiceid = $res["data"]["invoiceid"];
                                                \Think\Db::name("Invoices")->where("id", "=", $invoiceid)->update(["subtotal" => 0, "total" => 0]);
                                                $up_data = [];
                                                $up_data["invoice_id"] = $invoiceid;
                                                $up_data["amount_in"] = 0;
                                                $up_data["trans_id"] = "#" . $invoiceid;
                                                $up_data["currency"] = "CNY";
                                                $up_data["paid_time"] = date("Y-m-d H:i:s");
                                                $up_data["payment"] = "UserCustom";
                                                $Order = new \app\home\controller\OrderController();
                                                $Order->orderPayHandle($up_data);
                                                $product_id = \Think\Db::name("invoice_items")->where("type", "=", "host")->where("invoice_id", "=", $invoiceid)->value("rel_id");
                                                \Think\Db::name("group_buy_gzhx_user")->where("id", "=", $item["e_id"])->update(["status" => 2, "product_id" => $product_id]);
                                            }
                                            \Think\Db::name("group_buy_gzhx_user")->where("id", "=", $info["e_id"])->update(["status" => 2]);
                                            $success = \Think\Db::name("group_buy_gzhx_user")->where("uuid", "=", $info["e_id"])->where("uid", "=", $User)->value("product_id");
                                            $this->success(["success" => $success]);
                                            exit;
                                        } else {
                                            $this->success(["id" => bin2hex(openssl_encrypt($gid, "aes-128-cbc", "A89VB9PXBXJZ7834", true, "A89VB9PXBXJZ7835"))]);
                                        }
                                }
                            }
                        }
                    }
                    $info = \Think\Db::name("group_buy_gzhx")->alias("a")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("a.end_time", ">=", date("Y-m-d H:i:s"))->where("a.id", "=", $this->data["info"]["id"])->find();
                    if (empty($info)) {
                        $this->error("活动不存在");
                        exit;
                    }
                    $num = 2;
                    switch ($this->data["type"]) {
                        case "two":
                            $num = 2;
                            break;
                        case "three":
                            $num = 3;
                            break;
                        case "five":
                            $num = 5;
                            break;
                        default:
                            $f = \Think\Db::name("group_buy_gzhx_user")->where("uid", "=", $User)->where("uuid", "=", 0)->where("status", "=", 1)->where("num", "<", $num)->where("type", "=", $this->data["type"])->where("aid", "=", $this->data["info"]["id"])->find();
                            if (!empty($f)) {
                                $this->success(["id" => bin2hex(openssl_encrypt($f["id"], "aes-128-cbc", "A89VB9PXBXJZ7834", true, "A89VB9PXBXJZ7835"))]);
                            }
                            \Think\Db::startTrans();
                            try {
                                $PayPrice = $info[$this->data["type"]];
                                $clients = \Think\Db::name("clients")->where("id", $User)->find();
                                if (floatval($clients["credit"]) - floatval($PayPrice) < 0) {
                                    $this->error("pay");
                                    exit;
                                }
                                $insert = ["uid" => $User, "uuid" => 0, "num" => 1, "aid" => $this->data["info"]["id"], "type" => $this->data["type"], "add_time" => date("Y-m-d H:i:s"), "end_time" => date("Y-m-d H:i:s", strtotime("+" . $info["days"] . " day", time()))];
                                $id = \Think\Db::name("group_buy_gzhx_user")->insertGetId($insert);
                                $InvoicesId = \Think\Db::name("Invoices")->insertGetId(["uid" => $User, "invoice_num" => date("YmdHis") . mt_rand(10000, 999999), "create_time" => time(), "subtotal" => $PayPrice, "status" => "Paid", "credit" => $PayPrice, "payment" => "UserCustom", "type" => "product"]);
                                $payInfo = $info["pay_type"] == "monthly" ? "月" : "年";
                                $InvoicesItemsId = \Think\Db::name("InvoiceItems")->insertGetId(["uid" => $User, "invoice_id" => $InvoicesId, "description" => "参与拼团活动#" . $id . "，商品：" . $info["name"] . "，原价：" . $info[$info["pay_type"]] . "元，拼团价：" . $info[$this->data["type"]] . "元，拼团人数：" . $num . "人", "rel_id" => 0, "amount" => $PayPrice, "payment" => "UserCustom", "type" => "host"]);
                                $CreditId = \Think\Db::name("Credit")->insertGetId(["uid" => $User, "create_time" => time(), "description" => "Credit Applied to Invoice #" . $InvoicesId, "relid" => $InvoicesId, "amount" => $PayPrice]);
                                $insertUUID = $insert;
                                $insertUUID["uuid"] = $id;
                                $insertUUID["invoices_id"] = $InvoicesId;
                                \Think\Db::name("group_buy_gzhx_user")->insertGetId($insertUUID);
                                \Think\Db::name("group_buy_gzhx_user")->where("id", "=", $id)->update(["invoices_id" => $InvoicesId]);
                                \Think\Db::name("clients")->where("id", $User)->setDec("credit", $PayPrice);
                                \Think\Db::commit();
                                $this->success(["id" => bin2hex(openssl_encrypt($id, "aes-128-cbc", "A89VB9PXBXJZ7834", true, "A89VB9PXBXJZ7835"))]);
                            } catch (\Matrix\Exception $e) {
                                \Think\Db::rollback();
                                $this->error(var_export($e, true));
                            }
                            exit;
                    }
                    break;
                case "get":
                    if (!empty($this->data["data"]["id"])) {
                        $gid = openssl_decrypt(hex2bin($this->data["data"]["id"]), "aes-128-cbc", "A89VB9PXBXJZ7834", true, "A89VB9PXBXJZ7835");
                        if (!empty($gid)) {
                            $info = \Think\Db::name("group_buy_gzhx")->alias("a")->join("group_buy_gzhx_user e", "e.aid=a.id")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,e.id as e_id,e.status as e_status,e.num as e_num,e.type as e_type,e.end_time as e_end_time,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("e.id", "=", $gid)->where("e.uuid", "=", 0)->where("a.end_time", ">=", date("Y-m-d H:i:s"))->find();
                            if (!empty($info)) {
                                $outTime = strtotime($info["e_end_time"]) - time();
                                $outTimeConfig["time"] = $outTime;
                                $outTimeConfig["day"] = mb_substr("00" . floor($outTime / 86400), -2, NULL, "UTF-8");
                                $outTimeConfig["hour"] = mb_substr("00" . floor($outTime % 86400 / 3600), -2, NULL, "UTF-8");
                                $outTimeConfig["minute"] = mb_substr("00" . floor($outTime % 3600 / 60), -2, NULL, "UTF-8");
                                $info["outTimeConfig"] = $outTimeConfig;
                                $num = 2;
                                switch ($info["e_type"]) {
                                    case "two":
                                        $num = 2;
                                        break;
                                    case "three":
                                        $num = 3;
                                        break;
                                    case "five":
                                        $num = 5;
                                        break;
                                    default:
                                        $info["max_num"] = $num;
                                        $User = request()->uid;
                                        if (!empty($User)) {
                                            $f = \Think\Db::name("group_buy_gzhx_user")->where("uid", "=", $User)->where("status", "<", 3)->where("uuid", "=", $info["e_id"])->find();
                                            if (!empty($f)) {
                                                $info["join"] = $f;
                                            }
                                        }
                                        $info["description"] = htmlspecialchars($info["description"] . (htmlspecialchars($info["config_cn"]) ?: ""));
                                        $this->success(["data" => $info]);
                                        exit;
                                }
                            }
                        }
                    }
                    $List = ["two" => \Think\Db::name("group_buy_gzhx")->alias("a")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("a.end_time", ">=", date("Y-m-d"))->where("a.two", ">", 0)->select()->toArray(), "three" => \Think\Db::name("group_buy_gzhx")->alias("a")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("a.end_time", ">=", date("Y-m-d"))->where("a.three", ">", 0)->select()->toArray(), "five" => \Think\Db::name("group_buy_gzhx")->alias("a")->join("products c", "c.id=a.pid")->join("product_groups d", "d.id=a.gid")->join("pricing b", "c.id=b.relid")->field("a.*,c.description,c.name,d.name as group_name,b.monthly,b.annually")->where("b.type", "=", "product")->where("a.end_time", ">=", date("Y-m-d"))->where("a.five", ">", 0)->select()->toArray()];
                    foreach ($List as $key => $value) {
                        foreach ($value as $kk => $vv) {
                            $List[$key][$kk]["description"] = htmlspecialchars($vv["description"] . (htmlspecialchars($vv["config_cn"]) ?: ""));
                        }
                    }
                    $this->success($List);
                    exit;
                    break;
                default:
                    $this->error("参数不存在");
            }
        }
    }
}

?>