<?php

namespace app\dao;

use App\model\Users;
use App\model\BankLog;
use plugin\admin\app\model\User;

class BankDao {
    /**
     * 转账函数
     * 
     * @param int $senderAccountId - 发送账户ID
     * @param int $receiverAccountId - 接收账户手机号
     * @param float $amount - 转账金额
     * @return array - 返回转账结果
     */
    public static function transfer($senderAccountId, $receiverAccountId, $amount) {
        // 假设账户数据存储在一个简单的数组或数据库中
        // 模拟账户余额数据(实际应用中应查询数据库)
        $senderAccount=Users::where('id',$senderAccountId)->first();
        $receiverAccount=Users::where('phone',$receiverAccountId)->first();

        // 检查接收账户是否存在
        if (!isset($receiverAccount)) {
            return ['status' => 'error', 'message' => '接收账户不存在'];
        }

        // 检查转账金额是否合法
        if ($amount <= 0) {
            return ['status' => 'error', 'message' => '时间币必须大于0'];
        }

        // 检查发送账户余额是否足够
        if ($senderAccount->timecoin < $amount) {
            return ['status' => 'error', 'message' => '时间币余额不足'];
        }

        // 执行转账操作
        self::add($senderAccount->id,$amount-$amount*2,"赠送给 $receiverAccountId 时间币 $amount");
        self::add($receiverAccount->id,$amount,"收到 $senderAccount->phone 赠予 时间币 $amount");

        return [
            'status' => 'success',
            'message' => '转账成功',
        ];
    }
    /**
     * 增加时间币 传入负数就是减法
     *
     * @param [type] $userid 用户id
     * @param [type] $amount 金额
     * @param [type] $remark 备注
     * @return void
     */
    public static function add($userid, $amount,$remark) {
        $user = Users::where('id',$userid)->first();
        $log=new BankLog();
        $log->userid=$userid;
        $log->money=$amount;
        $log->remark=$remark;
        $log->save();
        $user->timecoin+=$amount;
        $user->Save();

    }
    /**
     * 减少用户时间币 好像废弃了
     *
     * @param [type] $userid 用户id
     * @param [type] $amount 金额
     * @param [type] $remark 备注
     * @return void
     */
    public static function subtraction($userid, $amount,$remark) {
        $user = Users::where('id',$userid)->first('timecoin');
        $log=new BankLog();
        $log->userid=$userid;
        $log->money=$amount;
        $log->remark=$remark;
        $log->save();
        $user->timecoin-=$amount;
        $user->Save();
    }
}