<?php


namespace App\Services;


use App\Http\logic\api\BaseApiLogic;
use App\Models\AccountsInfo;

use App\Models\Order;
use Illuminate\Support\Facades\DB;

class FirstRechargeGifts extends BaseApiLogic
{
    // 礼包类型
    public function buyGifts($GiftsID, $userId)
    {

        if (!empty($GiftsID)) {
            $Gifts = DB::connection('write')->table('QPAccountsDB.dbo.FirstRechargeGifts')->where('GiftsID', $GiftsID)->first();

            if (!$Gifts) {
                $this->error = '礼包类型错误';
                return false;
            }

            if ($Gifts->GiftsState != 1) {
                $this->error = '礼包关闭';
                return false;
            }

            // 判断首冲礼包类型
            if ($Gifts->TimeLimit > 0) { // 注册时间大于这段时间 不能购买
                $RegisterDate = DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->where('UserID', $userId)->select('RegisterDate')->first()->RegisterDate;
                if ((strtotime(date('Y-m-d H:i:s')) - strtotime($RegisterDate)) > $Gifts->TimeLimit) {
                    $this->error = '超出有效购买日期';
                    return false;
                }
            }

            if ($Gifts->CountLimit > 0) {   // 每人数量限制
                $orderGifts = DB::connection('write')->table('agent.dbo.order')->where('GiftsID', $GiftsID)->where('user_id', $userId)->where('pay_status', 1)->count();
                if ($orderGifts >= $Gifts->CountLimit) {
                    $this->error = '超出最大购买数量';
                    return false;
                }
            }
        }
        return true;
    }
}
