<?php

namespace app\common\service\promotion;

use think\facade\Db;
use app\common\model\Users as UsersModel;
use app\common\model\users\UsersLog as UsersLogModel;
use app\common\model\users\UsersPointLog as UsersPointLogModel;
use app\common\model\promotion\Invite as InviteModel;
use app\common\model\promotion\InviteLog as InviteLogModel;

/**
 * @package app\common\service\promotion
 * @class Invite
 * @author xzncit 2024/3/22
 */
class Invite {

    public static function reward($id,$uid){
        try{
            if(empty($uid) || empty($id)){
                return false;
            }

            $invite = InviteModel::where("status",1)->find();
            if(empty($invite)){
                return false;
            }

            Db::startTrans();

            $data = [];
            if($invite["point"] > 0){
                $data["score"] = Db::raw("score+" . $invite["point"]);
                UsersPointLogModel::create([
                    "user_id"       => $uid,
                    "type"          => 1,
                    "value"         => $invite["point"],
                    "content"       => "邀请奖励",
                    "create_time"   => time()
                ]);
            }

            if($invite["price"] > 0){
                $data["money"] = Db::raw("money+" . $invite["price"]);
                UsersLogModel::create([
                    "user_id"       => $uid,
                    "type"          => 1,
                    "operation"     => 1,
                    "value"         => $invite["price"],
                    "description"   => "邀请奖励",
                    "create_time"   => time()
                ]);
            }

            if(!empty($data)){
                UsersModel::where("id",$uid)->save($data);
                InviteLogModel::create([
                    "inviter_id"    => $uid,
                    "user_id"       => $id,
                    "point"         => $invite["point"],
                    "price"         => $invite["price"],
                    "create_time"   => time()
                ]);
            }

            Db::commit();
            return true;
        }catch (\Exception $ex){
            Db::rollback();
            return false;
        }
    }

}