<?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 === 'pwd') {
    $data[ 'a' ] = isset($_POST[ 'a' ]) ? purge($_POST[ 'a' ]) : '';
}

// 首页订单数据
if ($act === 'orderView') {
    // 构造日期数组
    $dates = [];
    for ($i = 6; $i >= 0; $i--) {
        $date    = date('Y-m-d' , strtotime("-$i day"));
        $dates[] = $date;
    }
    // 计算今日收入和总收入
    $start_time    = date('Y-m-d 00:00:00');
    $end_time      = date('Y-m-d 23:59:59');
    $today_revenue = Db::query("SELECT CAST(SUM(pay_money) AS DECIMAL(10,2)) as money from `app_order` where pay_time >= '{$start_time}' and pay_time <= '{$end_time}' and pay_status = '1'");
    $total_revenue = Db::query("SELECT CAST(SUM(pay_money) AS DECIMAL(10,2)) as money from `app_order` where pay_status = '1'");
    // 订单数量
    $order_paid   = Db::table('app_order')
                      ->where(['pay_status' => 1])
                      ->count();
    $order_unpaid = Db::table('app_order')
                      ->where('pay_status' , '!=' , '1')
                      ->count();
    // 查询每天的订单数据
    $paid_orders   = [];
    $unpaid_orders = [];
    foreach ($dates as $date) {
        $start_time      = "$date 00:00:00";
        $end_time        = "$date 23:59:59";
        $res_paid        = Db::table('app_order')
                             ->where('pay_time' , '>=' , $start_time)
                             ->where('pay_time' , '<=' , $end_time)
                             ->where('pay_status' , '=' , '1')
                             ->count();
        $res_unpaid      = Db::table('app_order')
                             ->where('pay_time' , '>=' , $start_time)
                             ->where('pay_time' , '<=' , $end_time)
                             ->where('pay_status' , '!=' , '1')
                             ->count();
        $paid_orders[]   = $res_paid;
        $unpaid_orders[] = $res_unpaid;
    }

    // 计算每天的支付率和比上升下降率
    $payment_rate = [];
    $rate_change  = [];
    $last_rate    = 0;
    foreach ($dates as $date) {
        $index = array_search($date , $dates);
        $rate  = 0;
        if ($paid_orders[ $index ] + $unpaid_orders[ $index ] > 0) {
            $rate = round($paid_orders[ $index ] / ( $paid_orders[ $index ] + $unpaid_orders[ $index ] ) , 4) * 100;
        }
        $payment_rate[] = $rate;
        $change         = 0;
        if ($last_rate > 0) {
            $change = round(( $rate - $last_rate ) / $last_rate , 4) * 100;
        }
        $rate_change[] = $change;
        $last_rate     = $rate;
    }

    // 输出结果
    $result = [
        // 'date' 表示日期数组，包含最近 7 天的日期
        'date'          => preg_replace('/\d{4}-/' , '' , $dates) ,
        // 'paid_orders' 表示每天的已支付订单数数组，按日期顺序存储
        'paid_orders'   => $paid_orders ,
        // 'unpaid_orders' 表示每天的未支付订单数数组，按日期顺序存储
        'unpaid_orders' => $unpaid_orders ,
        // 已支付订单总数
        'order_paid'    => $order_paid ,
        // 未支付订单总数
        'order_unpaid'  => $order_unpaid ,
        // 今日收入
        'today_revenue' => $today_revenue[ 0 ][ 'money' ] ,
        // 总收入
        'total_revenue' => $total_revenue[ 0 ][ 'money' ] ,
        // 'payment_rate' 表示每天的支付率数组，按日期顺序存储
        'payment_rate'  => $payment_rate ,
        // 'rate_change' 表示每天的比上升下降率数组，按日期顺序存储
        'rate_change'   => $rate_change

    ];

    if ($result) {
        exit(return_msg(200 , 'success' , $result));
    } else {
        exit(ReturnError('接口请求失败'));
    }


}

// 网站设置
if ($act === 'web_set') {
    $data[ 'site_name' ]            = isset($_POST[ 'site_name' ]) ? purge($_POST[ 'site_name' ]) : '';
    $data[ 'site_title' ]           = isset($_POST[ 'site_title' ]) ? purge($_POST[ 'site_title' ]) : '';
    $data[ 'site_keywords' ]        = isset($_POST[ 'site_keywords' ]) ? purge($_POST[ 'site_keywords' ]) : '';
    $data[ 'site_desc' ]            = isset($_POST[ 'site_desc' ]) ? purge($_POST[ 'site_desc' ]) : '';
    $data[ 'site_item_num' ]        = isset($_POST[ 'site_item_num' ]) ? purge($_POST[ 'site_item_num' ]) : '';
    $data[ 'redis_address' ]        = isset($_POST[ 'redis_address' ]) ? purge($_POST[ 'redis_address' ]) : '';
    $data[ 'redis_port' ]           = isset($_POST[ 'redis_port' ]) ? purge($_POST[ 'redis_port' ]) : '';
    $data[ 'api_request_limit' ]    = isset($_POST[ 'api_request_limit' ]) ? purge($_POST[ 'api_request_limit' ]) : '';
    $data[ 'api_request_interval' ] = isset($_POST[ 'api_request_interval' ]) ? purge($_POST[ 'api_request_interval' ]) : '';
    $data[ 'redis_password' ]       = isset($_POST[ 'redis_password' ]) ? purge($_POST[ 'redis_password' ]) : '';
    $data[ 'code_prefix' ]          = isset($_POST[ 'code_prefix' ]) ? purge($_POST[ 'code_prefix' ]) : '';
    $data[ 'code_length' ]          = isset($_POST[ 'code_length' ]) ? purge($_POST[ 'code_length' ]) : '';
    $data[ 'code_exp_time' ]        = isset($_POST[ 'code_exp_time' ]) ? purge($_POST[ 'code_exp_time' ]) : '';
    $data[ 'footer' ]               = isset($_POST[ 'footer' ]) ? purge($_POST[ 'footer' ]) : '';
    if ($data[ 'site_item_num' ] < 10) {
        exit(return_msg(201 , '每页显示不能低于10条'));
    }

    $res = Db::table('app_web')
             ->update($data);
    if ($res) {
        exit(return_msg(200 , '保存成功'));
    } else {
        exit(return_msg(201 , '保存失败'));
    }
}

// 发信设置
if ($act === 'send') {
    $data[ 'send_smtp_host' ]     = isset($_POST[ 'hosts' ]) ? purge($_POST[ 'hosts' ]) : '';
    $data[ 'send_smtp_port' ]     = isset($_POST[ 'ports' ]) ? purge($_POST[ 'ports' ]) : '';
    $data[ 'send_from_name' ]     = isset($_POST[ 'from_name' ]) ? purge($_POST[ 'from_name' ]) : '';
    $data[ 'send_username' ]      = isset($_POST[ 'username' ]) ? purge($_POST[ 'username' ]) : '';
    $data[ 'send_password' ]      = isset($_POST[ 'password' ]) ? purge($_POST[ 'password' ]) : '';
    $data[ 'send_collect_email' ] = isset($_POST[ 'inbox' ]) ? purge($_POST[ 'inbox' ]) : '';
    $res                          = Db::table('app_web')
                                      ->update($data);
    if ($res) {
        exit(return_msg(200 , '保存成功'));
    } else {
        exit(return_msg(201 , '保存失败'));
    }
}
if ($act === 'fastlogin') {
    $data[ 'APPID' ]     = isset($_POST[ 'APPID' ]) ? purge($_POST[ 'APPID' ]) : '';
    $data[ 'APPKEY' ]     = isset($_POST[ 'APPKEY' ]) ? purge($_POST[ 'APPKEY' ]) : '';
    $data[ 'wx' ]     = isset($_POST[ 'wx' ]) ? purge($_POST[ 'wx' ]) : '';
    $data[ 'qq' ]      = isset($_POST[ 'qq' ]) ? purge($_POST[ 'qq' ]) : '';
    $data[ 'zfb' ]      = isset($_POST[ 'zfb' ]) ? purge($_POST[ 'zfb' ]) : '';
    $res                          = Db::table('app_web')
                                      ->update($data);
    if ($res) {
        exit(return_msg(200 , '保存成功'));
    } else {
        exit(return_msg(201 , '保存失败'));
    }
}


// 修改管理员信息
if ($act === 'setAdm') {
    $nick          = isset($_POST[ 'adminNick' ]) ? purge($_POST[ 'adminNick' ]) : '';
    $qq            = isset($_POST[ 'adminQQ' ]) ? purge($_POST[ 'adminQQ' ]) : '';
    $admin         = isset($_POST[ 'adminAccount' ]) ? purge($_POST[ 'adminAccount' ]) : '';
    $oldPwd        = isset($_POST[ 'oldPassword' ]) ? purge($_POST[ 'oldPassword' ]) : '';
    $newPwd        = isset($_POST[ 'newPassword' ]) ? purge($_POST[ 'newPassword' ]) : '';
    $confirmNewPwd = isset($_POST[ 'confirmNewPassword' ]) ? purge($_POST[ 'confirmNewPassword' ]) : '';

    if (empty($admin)) {
        exit(ReturnError('管理员账号不能为空'));
    }
    // 校验用户名和密码
    if ( !preg_match('/^[a-zA-Z0-9_]{6,20}$/' , $admin)) {
        exit(ReturnError('用户名格式不正确'));
    }

    if ( !empty($oldPwd) && !empty($newPwd) && !empty($confirmNewPwd)) {
        if ( !preg_match('/^[a-zA-Z0-9_]{6,20}$/' , $oldPwd) || !preg_match('/^[a-zA-Z0-9_]{6,20}$/' , $newPwd) || !preg_match('/^[a-zA-Z0-9_]{6,20}$/' , $confirmNewPwd)) {
            exit(ReturnError('密码格式不正确'));
        }
        // 如果涉及到密码修改，则进行相应的验证
        $old = Db::table('app_admin')
                 ->find();
        if ($old[ 'password' ] !== md5($oldPwd) && verifyPassword($old[ 'password' ] , $old[ 'salt' ])) {
            exit(ReturnError('旧密码不正确'));
        }

        if ($newPwd !== $confirmNewPwd) {
            exit(ReturnError('两次输入的新密码不一致'));
        }

        $res = Db::table('app_admin')
                 ->update([
                     'usernick' => $nick ,
                     'userqq'   => $qq ,
                     'username' => $admin ,
                     'password' => md5($newPwd) ,
                     'cookie'   => md5($admin . $newPwd . time()) ,
                     'salt'     => encryptPassword(md5($newPwd))
                 ]);
    } else {
        // 修改账号
        $res = Db::table('app_admin')
                 ->update([
                     'usernick' => $nick ,
                     'userqq'   => $qq ,
                     'username' => $admin
                 ]);
    }

    if ( !$res) {
        exit(ReturnError('修改失败，请稍后重试'));
    } else {
        exit(ReturnSuccess('修改成功'));
    }

}


// 开关配置
if ($act === 'membership') {
    $data[ 'reg_chat_limit' ]                    = $_POST[ 'reg_chat_limit' ];
    $data[ 'allow_registration' ]                = isset($_POST[ 'allow_registration' ]) ? purge($_POST[ 'allow_registration' ]) : '0';
    $data[ 'enable_email_verification' ]         = isset($_POST[ 'enable_email_verification' ]) ? purge($_POST[ 'enable_email_verification' ]) : '0';
    $data[ 'enable_membership_activation_code' ] = isset($_POST[ 'enable_membership_activation_code' ]) ? purge($_POST[ 'enable_membership_activation_code' ]) : '0';
    $data[ 'enable_online_membership' ]          = isset($_POST[ 'enable_online_membership' ]) ? purge($_POST[ 'enable_online_membership' ]) : '0';
    $data[ 'enable_local_key_input' ]            = isset($_POST[ 'enable_local_key_input' ]) ? purge($_POST[ 'enable_local_key_input' ]) : '0';
    $data[ 'bad_words' ]                         = isset($_POST[ 'bad_words' ]) ? purge($_POST[ 'bad_words' ]) : '';
    $data[ 'openai_api' ]                        = $_POST[ 'openai_api' ] ?? '';
    $data[ 'system_maintenance' ]                = $_POST[ 'system_maintenance' ] ?? 0;
    $data[ 'site_notice' ]                       = $_POST[ 'site_notice' ] ?? '';
    $data[ 'site_notice_status' ]                = $_POST[ 'site_notice_status' ] ?? '';
    $old                                         = Db::table('app_web' , 'AS O')
                                                     ->field('O.reg_chat_limit,O.allow_registration,O.enable_email_verification,O.enable_membership_activation_code,O.enable_online_membership,O.enable_local_key_input,O.bad_words,O.openai_api,O.system_maintenance,O.site_notice,O.site_notice_status')
                                                     ->find();

    if (array_compare([$old] , [$data])) {
        exit(return_msg(201 , '未更改数据' , [
            'old' => $old ,
            'new' => $data
        ]));
    }

    if (Db::table('app_web')
          ->update($data)) {
        exit(ReturnSuccess('更新成功'));
    } else {
        exit(ReturnError('更新失败'));
    }
}


// 支付渠道选择
if ($act === 'pay_branch') {
    $pay_branch = isset($_POST[ 'branch' ]) ? purge($_POST[ 'branch' ]) : 0;
    $old        = Db::table('payment_config')
                    ->find()[ 'pay_branch' ];
    if (array_compare([$old] , [$pay_branch])) {
        exit(return_msg(202 , '未修改数据' , []));
    }
    if (Db::table('payment_config')
          ->update(['pay_branch' => $pay_branch])) {
        exit(ReturnSuccess('修改成功'));
    } else {
        exit(ReturnError('修改失败'));
    }
}
// 支付配置
if ($act === 'pay_set') {
    $data[ 'wx_mchid' ] = isset($_POST[ 'mchid' ]) ? purge($_POST[ 'mchid' ]) : "";
    $data[ 'wx_key' ]   = isset($_POST[ 'wx_key' ]) ? purge($_POST[ 'wx_key' ]) : "";
    $data[ 'wx_appid' ] = isset($_POST[ 'wx_appid' ]) ? purge($_POST[ 'wx_appid' ]) : "";
    //    $data[ 'cert_route' ]      = isset($_POST[ 'wx_cert_route' ]) ? purge($_POST[ 'wx_cert_route' ]) : "";
    //    $data[ 'key_route' ]       = isset($_POST[ 'wx_key_route' ]) ? purge($_POST[ 'wx_key_route' ]) : "";
    $data[ 'ali_appid' ]       = isset($_POST[ 'ali_appid' ]) ? purge($_POST[ 'ali_appid' ]) : "";
    $data[ 'ali_private_key' ] = isset($_POST[ 'ali_private_key' ]) ? purge($_POST[ 'ali_private_key' ]) : "";
    $data[ 'ali_public_key' ]  = isset($_POST[ 'ali_public_key' ]) ? purge($_POST[ 'ali_public_key' ]) : "";
    $data[ 'epay_api_url' ]    = isset($_POST[ 'epay_api_url' ]) ? purge($_POST[ 'epay_api_url' ]) : "";
    $data[ 'epay_appid' ]      = isset($_POST[ 'epay_appid' ]) ? purge($_POST[ 'epay_appid' ]) : "";
    $data[ 'epay_key' ]        = isset($_POST[ 'epay_key' ]) ? purge($_POST[ 'epay_key' ]) : "";
    $old                       = Db::table('payment_config' , 'AS P')
                                   ->field('P.wx_mchid,P.wx_key,P.wx_appid,P.ali_appid,P.ali_private_key,P.ali_public_key,P.epay_api_url,P.epay_appid,P.epay_key')
                                   ->find();
    unset($old[ 'pay_branch' ]);
    if (array_compare($old , $data)) {
        exit(ReturnError('未修改数据'));
    }
    if (Db::table('payment_config')
          ->update($data)) {
        exit(ReturnSuccess('保存成功'));
    } else {
        exit(ReturnError('保存失败'));
    }
}

if ($act === 'speed') {
    $url   = $_POST[ 'url' ] ?? '';
    $speed = test_api_speed($url);
    if ($speed) {
        exit(return_msg(200 , '检测完成' , ['speed' => $speed]));
    } else {
        exit(ReturnError('速度检测失败'));
    }
}






