<?php
/*
 * @author: CloudZA(云之安) <2922619853@qq.com>
 * @hitokoto: 一场秋雨一场凉，秋心酌满泪为霜。
 * Copyright (c) 2022 by CloudZA, All Rights Reserved.
 */

include_once 'common.php';
if ( !isset($islogin)) header("Location: /");//非法访问
$act = isset($_GET[ 'act' ]) ? purge($_GET[ 'act' ]) : '';
// 支付订单
if ($act === 'pay_order') {
    $data   = Db::table('app_order')
                ->order('pay_time desc')
                ->select();
    $custom = [];
    foreach ($data as $item) {
        $custom[] = [
            'id_custom'          => $item[ 'id' ] ,
            'pay_order_custom'   => $item[ 'pay_order' ] ,
            'pay_orderno_custom' => $item[ 'pay_orderno' ] ,
            'pay_type_custom'    => displayPayType($item[ 'pay_type' ]) ,
            'pay_name_custom'    => $item[ 'pay_name' ] ,
            'pay_money_custom'   => $item[ 'pay_money' ] ,
            'pay_time_custom'    => $item[ 'pay_time' ] ,
            'pay_ip_custom'      => $item[ 'pay_ip' ] ,
            'pay_region_custom'  => $item[ 'pay_region' ] ,
            'pay_status_custom'  => displayStutas($item[ 'pay_status' ])
        ];
    }
    if ($data) {
        exit(return_msg(200 , 'success' , [
            'custom' => $custom ,
            'page'   => PAGE_SIZE
        ]));
    } else {
        exit(return_msg(200 , 'success' , [
            'custom' => [] ,
            'page'   => PAGE_SIZE
        ]));
    }
}

// 多选删除订单
if ($act === 'delOrder') {
    $id = $_POST[ 'id' ] ?? '';
    if ($id) {
        $ids = '';
        foreach ($id as $value) {
            $ids .= intval($value) . ",";
        }
        $ids = rtrim($ids , ",");
        $res = Db::table('app_order')
                 ->where('id' , 'in' , '(' . $ids . ')')
                 ->del();
        if ($res) {
            exit(ReturnSuccess('删除成功'));
        } else {
            exit(ReturnError('删除失败'));
        }
    } else {
        exit(ReturnError('没有需要删除的数据'));
    }
}

// 支付地图
if ($act === 'order_map') {
    require '../common/class/ip2region/Ip2Region.php';
    // 创建 ip2region 实例
    $ip2region = new Ip2Region();
    // 根据传入参数计算查询日期
    if ($_GET[ 'time' ] != 0 && $_GET[ 'time' ] <= 30) {
        $queryDate = date("Y-m-d" , strtotime("-" . $_GET[ 'time' ] . " day"));
    } else if ($_GET[ 'time' ] == 0) {
        $queryDate = date("Y-m-d") . ' 00:00:00';
    } else {
        exit('{"code":-1,"msg":"查询时间过大！"}');
    }
    // 初始化订单总收入为0
    $totalRevenue = 0;
    // 查询所有已支付的订单信息
    $orderList = Db::query("SELECT pay_type, pay_orderno, pay_money, pay_ip FROM `app_order` WHERE pay_status = 1");
    // 遍历订单列表，计算总收入和每个订单所属省份、金额等信息
    foreach ($orderList as $key => $order) {
        $totalRevenue += $order[ 'pay_money' ];
        // 当订单 IP 地址不为空时，根据 IP 地址获取所在省份名称
        if ($order[ 'pay_ip' ] != '::1') {
            $regionInfo = $ip2region->btreeSearch($order[ 'pay_ip' ]);
            $regionName = trim(str_replace("省" , "" , explode('|' , $regionInfo[ 'region' ])[ 2 ]));
            // 判断省份名称是否为未知IP
            if ($regionName == '0') {
                $regionName = '其他';
            }
            // 在订单信息中添加省份名称和金额信息
            $orderList[ $key ][ 'name' ]  = $regionName;
            $orderList[ $key ][ 'value' ] = $order[ 'pay_money' ];
        }
    }
    // 按照省份统计订单数量和金额
    $orderCountByProvince = [];
    foreach ($orderList as $order) {
        // 如果当前省份已存在于数组中，累加订单金额和订单数量
        if (isset($orderCountByProvince[ $order[ 'name' ] ])) {
            $orderCountByProvince[ $order[ 'name' ] ][ 'value' ] += $order[ 'value' ];
            $orderCountByProvince[ $order[ 'name' ] ][ 'count' ]++;
        } else { // 否则将该省份作为新元素添加到数组中
            $orderCountByProvince[ $order[ 'name' ] ]            = $order;
            $orderCountByProvince[ $order[ 'name' ] ][ 'count' ] = 1;
        }

        // 对每个省份的订单金额进行格式化和省份名称的处理
        $orderCountByProvince[ $order[ 'name' ] ][ 'value' ] = sprintf("%.2f" , $orderCountByProvince[ $order[ 'name' ] ][ 'value' ]);
        $orderCountByProvince[ $order[ 'name' ] ][ 'name' ]  = str_replace("省" , "" , $orderCountByProvince[ $order[ 'name' ] ][ 'name' ]);
    }
    // 对各省份的订单按照金额进行排序
    usort($orderCountByProvince , function ($a , $b) {
        return $b[ 'value' ] - $a[ 'value' ];
    });
    // 构造响应数据并输出 JSON 结果
    $responseData = [
        'list'       => $orderCountByProvince ,
        'orderMoney' => sprintf("%.2f" , $totalRevenue) ,
        'time'       => $queryDate
    ];
    //    echo json_encode($responseData , true);
    exit(return_msg(200 , 'success' , $responseData));
}
// GptKey列表
if ($act === 'key_list') {
    $data = Db::table('app_keys')
              ->order('id desc')
              ->select();
    if ($data) {
        exit(return_msg(200 , 'success' , [
            'custom' => $data ,
            'page'   => PAGE_SIZE
        ]));
    } else {
        exit(return_msg(200 , 'success' , [
            'custom' => [] ,
            'page'   => PAGE_SIZE
        ]));
    }
}

// 刷新单条key
if ($act === 'refresh_key') {
    $key = isset($_POST[ 'key' ]) ? purge($_POST[ 'key' ]) : '';
    if (empty($key)) {
        exit(ReturnError('数据不完整'));
    }
    $response = sendCurlRequest(GPTAPI , $key);
    $arr      = json_decode($response , true);
    if ($arr[ 'code' ] !== 200) {
        $arr[ 'data' ][ 'granted' ]      = '0.00';
        $arr[ 'data' ][ 'used' ]         = '0.00';
        $arr[ 'data' ][ 'available' ]    = '0.00';
        $arr[ 'data' ][ 'effective_at' ] = date('Y-m-d H:i:s');
        $arr[ 'data' ][ 'expires_at' ]   = date('Y-m-d H:i:s');
        $key_status                      = 0;
    } else {
        $key_status = 1;
    }
    $D = Db::table('app_keys')
           ->where(['gpt_keys' => $key])
           ->update([
               'granted'      => $arr[ 'data' ][ 'granted' ] ,
               'used'         => $arr[ 'data' ][ 'used' ] ,
               'available'    => $arr[ 'data' ][ 'available' ] ,
               'effective_at' => $arr[ 'data' ][ 'effective_at' ] ,
               'expires_at'   => $arr[ 'data' ][ 'expires_at' ] ,
               'key_status'   => $key_status ,
           ]);
    exit(ReturnSuccess('更新成功'));
}

// 添加Key(一条、多条)
if ($act === 'addKey') {
    $keysArray       = $_POST[ 'keys' ] ?? [];
    $insertedKeys    = [];
    $notInsertedKeys = [];

    if (empty($keysArray)) {
        exit(ReturnError('Key不能为空'));
    }

    foreach ($keysArray as $key) {
        $response = sendCurlRequest(GPTAPI , $key);
        $arr      = json_decode($response , true);
        if (Db::table('app_keys')
              ->where(['gpt_keys' => $key])
              ->find()) {
            $notInsertedKeys[ $key ] = ' - 数据库已存在此Key';
            continue;
        }
        if ($arr[ 'code' ] !== 200) {
            $notInsertedKeys[ $key ] = ' - Key无效或者已过期';
            continue;
        }

        $data       = $arr[ 'data' ];
        $key_status = "1";
        if ($data[ 'available' ] === 0) {
            $key_status = "0";
        }

        $result = Db::table('app_keys')
                    ->add([
                        'gpt_keys'     => $key ,
                        'granted'      => $data[ 'granted' ] ,
                        'used'         => $data[ 'used' ] ,
                        'available'    => $data[ 'available' ] ,
                        'effective_at' => $data[ 'effective_at' ] ,
                        'expires_at'   => $data[ 'expires_at' ] ,
                        'key_status'   => $key_status ,
                    ]);

        if ($result) {
            $insertedKeys[] = $key;
        } else {
            $notInsertedKeys[ $key ] = '数据库插入失败';
        }
    }

    if ( !empty($notInsertedKeys)) {
        $notInsertedKeysStr = implode('<br/>' , array_map(function ($key , $reason) {
            return "$key($reason)";
        } , array_keys($notInsertedKeys) , $notInsertedKeys));
        exit(ReturnSuccess('未添加的Key如下：<br/>' . $notInsertedKeysStr));
    } elseif ( !empty($insertedKeys)) {
        $count   = count($insertedKeys);
        $message = ( $count > 1 ? "{$count} 个 Key 已添加" : "1 个 Key 已添加" );
        exit(ReturnSuccess($message . '，如果页面未刷新，请手动刷新'));
    } else {
        exit(ReturnError('添加失败，请检查Key是否有效'));
    }
}


// 多选删除Key
if ($act === 'delKey') {
    $id = $_POST[ 'id' ] ?? '';
    if ($id) {
        $ids = '';
        foreach ($id as $value) {
            $ids .= intval($value) . ",";
        }
        $ids = rtrim($ids , ",");
        $res = Db::table('app_keys')
                 ->where('id' , 'in' , '(' . $ids . ')')
                 ->del();
        if ($res) {
            exit(ReturnSuccess('删除成功'));
        } else {
            exit(ReturnError('删除失败'));
        }
    } else {
        exit(ReturnError('没有需要删除的数据'));
    }
}

// 设置Key状态
if ($act === 'setKeyStatus') {
    $id     = $_POST[ 'id' ] ?? '';
    $status = $_POST[ 'status' ] ?? '';
    $res    = Db::table('app_keys')
                ->where(['id' => $id])
                ->update(['key_status' => $status]);
    if ($res) {
        exit(ReturnSuccess('更新成功'));
    } else {
        exit(ReturnError('更新失败'));
    }
}


// 用户列表
if ($act === 'user_list') {
    $data = Db::table('app_user' , 'AS A')
              ->field('A.id,A.username,A.email,A.plans,A.plans_name,A.chat_limit,A.effective_at,A.expires_at')
              ->select();

    if ($data) {
        exit(return_msg(200 , 'success' , [
            'custom' => $data ,
            'page'   => PAGE_SIZE
        ]));
    } else {
        exit(return_msg(200 , 'success' , [
            'custom' => [] ,
            'page'   => PAGE_SIZE
        ]));
    }
}

// 添加用户
if ($act === 'add_user') {
    $type     = isset($_POST[ 'type' ]) ? purge($_POST[ 'type' ]) : '';
    $id       = isset($_POST[ 'UID' ]) ? purge($_POST[ 'UID' ]) : '';
    $planID   = isset($_POST[ 'user_plans' ]) ? purge($_POST[ 'user_plans' ]) : '';
    $username = isset($_POST[ 'username' ]) ? purge($_POST[ 'username' ]) : '';
    $password = isset($_POST[ 'user_pass' ]) ? purge($_POST[ 'user_pass' ]) : '';
    $email    = $_POST[ 'user_email' ] ?? 0;
    if (empty($type) || empty($username) || empty($email)) {
        exit(ReturnError('数据不完整'));
    }

    if ( !checkUsername($username)) {
        exit(ReturnError('用户名只能为4-20位英文、下划线和小数点组成'));
    }
    if ( !checkEmail($email)) {
        exit(ReturnError('邮箱不合法'));
    }

    if ($type === 'add') {
        if ( !checkPassword($password)) {
            exit(ReturnError('密码长度为8到20位，只能包含英文字母和数字'));
        }
        $password = md5($password);
        if (checkUsernameExistence($username)) {
            exit(ReturnError('用户名已存在'));
        }
        $add = Db::table('app_user')
                 ->add([
                     'username' => $username ,
                     'password' => $password ,
                     'email'    => $email ,
                     'cookie'   => md5($username . $password . time()) ,
                     'salt'     => encryptPassword($password) ,
                 ]);
        if ($add) {
            $add_status = true;
            if ($planID) {
                $UID = Db::table('app_user')
                         ->where(['username' => $username])
                         ->find()[ 'id' ];
                if ( !openMember($UID , NULL , $planID)) {
                    exit(ReturnError('用户添加成功，会员开通失败'));
                }
            }
            exit(ReturnSuccess('添加成功'));
        } else {
            exit(ReturnError('添加失败'));
        }

    } else if ($type === 'edit') {
        if ($password) {
            $check = compare_arrays(Db::table('app_user' , 'AS U')
                                      ->field('U.username,U.password,U.email')
                                      ->where(['id' => $id])
                                      ->find() , [
                'username' => $username ,
                'password' => md5($password) ,
                'email'    => $email
            ]);
        } else {
            $check = compare_arrays(Db::table('app_user' , 'AS U')
                                      ->field('U.username,U.email')
                                      ->where(['id' => $id])
                                      ->find() , [
                'username' => $username ,
                'email'    => $email
            ]);
        }
        if ( !$check) {
            exit(ReturnError('不能和旧数据相同'));
        }
        if ( !$password) {
            $update = Db::table('app_user')
                        ->where(['id' => $id])
                        ->update([
                            'username' => $username ,
                            'email'    => $email
                        ]);
        } else {
            if ( !checkPassword($password)) {
                exit(ReturnError('密码长度为8到20位，只能包含英文字母和数字'));
            }
            $update = Db::table('app_user')
                        ->where(['id' => $id])
                        ->update([
                            'username' => $username ,
                            'email'    => $email ,
                            'password' => md5($password) ,
                            'cookie'   => md5($username . $password . time()) ,
                            'salt'     => encryptPassword(md5($password)) ,
                        ]);
        }
        if ($update) {
            exit(ReturnSuccess('保存成功'));
        } else {
            exit(ReturnError('保存失败'));
        }

    } else {
        exit(ReturnError('接口出错，请联系开发者'));
    }

}

// 删除或删除多个用户
if ($act === 'delUser') {
    $id = $_POST[ 'id' ] ?? '';
    if ($id) {
        $ids = '';
        foreach ($id as $value) {
            $ids .= intval($value) . ",";
        }
        $ids = rtrim($ids , ",");
        $res = Db::table('app_user')
                 ->where('id' , 'in' , '(' . $ids . ')')
                 ->del();
        if ($res) {
            exit(ReturnSuccess('删除成功'));
        } else {
            exit(ReturnError('删除失败'));
        }
    } else {
        exit(ReturnError('没有需要删除的数据'));
    }
}

// 增加或者减少用户对话额度
if ($act === 'editUserChatLimit') {
    $id    = isset($_POST[ 'id' ]) ? purge($_POST[ 'id' ]) : '';
    $type  = isset($_POST[ 'type' ]) ? purge($_POST[ 'type' ]) : '';
    $limit = isset($_POST[ 'limit' ]) ? purge($_POST[ 'limit' ]) : '0';
    if ( !$limit) {
        exit(ReturnError('请输入完整'));
    }
    if ($type === '1') {
        if (addChatLimit($id , ( $limit ))) {
            exit(ReturnSuccess('添加成功'));
        } else {
            exit(ReturnError('添加失败'));
        }
    } else {
        if (reduceChatLimit($id , $limit)) {
            exit(ReturnSuccess('减少成功'));
        } else {
            exit(ReturnError('减少失败'));
        }
    }

}

// 套餐列表
if ($act === 'plan_lists') {
    $data = Db::table('app_plans')
              ->select();
    if ($data) {
        exit(return_msg(200 , 'success' , [
            'custom' => $data ,
            'page'   => PAGE_SIZE
        ]));
    } else {
        exit(return_msg(200 , 'success' , [
            'custom' => [] ,
            'page'   => PAGE_SIZE
        ]));
    }
}

// 添加套餐
if ($act === 'addPlans') {
    $data[ 'name' ]       = isset($_POST[ 'plan_name' ]) ? purge($_POST[ 'plan_name' ]) : '';
    $data[ 'period' ]     = isset($_POST[ 'plan_period' ]) ? purge($_POST[ 'plan_period' ]) : '';
    $data[ 'price' ]      = isset($_POST[ 'plan_price' ]) ? purge($_POST[ 'plan_price' ]) : '';
    $data[ 'chat_limit' ] = isset($_POST[ 'plan_chat_limit' ]) ? purge($_POST[ 'plan_chat_limit' ]) : '';
    if (empty($data[ 'name' ]) || empty($data[ 'period' ]) || empty($data[ 'price' ]) || empty($data[ 'chat_limit' ])) {
        exit(ReturnError('数据不能为空'));
    }
    $insert = Db::table('app_plans')
                ->add($data);
    if ($insert) {
        exit(ReturnSuccess('添加成功'));
    } else {
        exit(ReturnError('添加失败'));
    }
}
// 删除套餐
if ($act === 'delPlans') {
    $id = $_POST[ 'id' ] ?? '';
    if ($id) {
        $ids = '';
        foreach ($id as $value) {
            $ids .= intval($value) . ",";
        }
        $ids  = rtrim($ids , ",");
        $res  = Db::table('app_plans')
                  ->where('id' , 'in' , '(' . $ids . ')')
                  ->del();
        $res2 = Db::query('DELETE FROM app_plan_coupons WHERE plan_id IN (' . $ids . ')');
        if ($res || $res2) {
            exit(ReturnSuccess('删除成功'));
        } else {
            exit(ReturnError('删除失败'));
        }
    } else {
        exit(ReturnError('没有需要删除的数据'));
    }
}

if ($act === 'editPlans') {
    $id                   = isset($_POST[ 'id' ]) ? purge($_POST[ 'id' ]) : '';
    $data[ 'name' ]       = isset($_POST[ 'plan_name' ]) ? purge($_POST[ 'plan_name' ]) : '';
    $data[ 'period' ]     = isset($_POST[ 'plan_period' ]) ? purge($_POST[ 'plan_period' ]) : '';
    $data[ 'price' ]      = isset($_POST[ 'plan_price' ]) ? purge($_POST[ 'plan_price' ]) : '';
    $data[ 'chat_limit' ] = isset($_POST[ 'plan_chat_limit' ]) ? purge($_POST[ 'plan_chat_limit' ]) : '';
    if (empty($data[ 'name' ]) || empty($data[ 'period' ]) || empty($data[ 'price' ]) || empty($data[ 'chat_limit' ])) {
        exit(ReturnError('数据不能为空'));
    }
    $update = Db::table('app_plans')
                ->where(['id' => $id])
                ->update($data);
    if ($update) {
        exit(ReturnSuccess('更新成功'));
    } else {
        exit(ReturnError('编辑失败'));
    }
}


// 卡密列表
//getRand 随机卡密
if ($act === 'card_list') {
    $data   = Db::table('app_plan_coupons')
                ->select();
    $custom = [];
    foreach ($data as $item) {
        $custom[] = [
            'id'         => $item[ 'id' ] ,
            'plan_id'    => $item[ 'plan_id' ] ,
            'plan_name'  => getPlanById($item[ 'plan_id' ])[ 'name' ] ,
            'coupon'     => $item[ 'coupon' ] ,
            'is_used'    => $item[ 'is_used' ] ,
            'created_at' => $item[ 'created_at' ] ,
            'used_at'    => $item[ 'used_at' ] ,
        ];
    }
    if ($custom) {
        exit(return_msg(200 , 'success' , [
            'custom' => $custom ,
            'page'   => PAGE_SIZE
        ]));
    } else {
        exit(return_msg(200 , 'success' , [
            'custom' => [] ,
            'page'   => PAGE_SIZE
        ]));
    }
}

// 生成卡密
if ($act === 'generate_card') {
    $plans        = isset($_POST[ 'plans' ]) ? purge($_POST[ 'plans' ]) : '';
    $generate_num = isset($_POST[ 'generate_num' ]) ? purge($_POST[ 'generate_num' ]) : '';
    if (empty($plans) || empty($generate_num)) {
        exit(ReturnError('缺少必要参数'));
    }

    $success = true;
    for ($i = 0; $i < $generate_num; $i++) {
        $data   = [
            'plan_id'    => $plans ,
            'coupon'     => getRand(16) ,
            'is_used'    => 0 ,
            'created_at' => date('Y-m-d H:i:s')
        ];
        $result = Db::table('app_plan_coupons')
                    ->add($data);
        if ($result === false) {
            $success = false;
            break;
        }
    }

    if ($success) {
        exit(ReturnSuccess('添加成功'));
    } else {
        exit(ReturnError('添加失败'));
    }
}

// 多选删除卡密
if ($act === 'delCard') {
    $id = $_POST[ 'id' ] ?? '';
    if ($id) {
        $ids = '';
        foreach ($id as $value) {
            $ids .= intval($value) . ",";
        }
        $ids = rtrim($ids , ",");
        $res = Db::table('app_plan_coupons')
                 ->where('id' , 'in' , '(' . $ids . ')')
                 ->del();
        if ($res) {
            exit(ReturnSuccess('删除成功'));
        } else {
            exit(ReturnError('删除失败'));
        }
    } else {
        exit(ReturnError('没有需要删除的数据'));
    }
}

if ($act === 'export_card') {
    $exp_card_plans = isset($_POST[ 'exp_card_plans' ]) ? purge($_POST[ 'exp_card_plans' ]) : '';
    $card_status    = isset($_POST[ 'card_status' ]) ? purge($_POST[ 'card_status' ]) : '0';
    if (empty($exp_card_plans)) {
        exit(ReturnError('数据不能为空'));
    }
    $data = Db::table('app_plan_coupons')
              ->where([
                  'plan_id' => $exp_card_plans ,
                  'is_used' => $card_status
              ])
              ->select();
    if ($data) {
        exit(return_msg(200 , 'success' , ['coupons' => $data]));
    } else {
        exit(ReturnError('未找到数据'));
    }
}