<?php


namespace App\Modules\Push\Models;


use DB;
use Illuminate\Database\Eloquent\Model;

class QappPushUser extends Model
{
    protected $table = 'qapp_push_user';
    protected $fillable = ['uid', 'reg_id', 'provider', 'app_id', 'channel_id'];

    /**
     * @param $uid
     * @return array
     */
    public static function getPushUserByUid($uid)
    {
        if (empty($uid)) {
            return [];
        }

        $tableName = 'qapp_push_user';
        return DB::connection('mysql::write')
            ->table($tableName)
            ->where('uid', $uid)->first();
    }

    public static function getPushUserByUids($uids): array
    {
        if (empty($uids)) {
            return [];
        }

        $result = self::whereIn('uid', $uids)->get();
        return $result ? $result->toArray() : [];
    }

    public static function getPushUsersByProvider($provider, $id = 0): array
    {
        if (empty($provider)) {
            return [];
        }

        $result = self::where('id', '<', $id)->where('provider', $provider)->orderBy('id', 'desc')->limit(1000)->get();
        return $result ? $result->toArray() : [];
    }

    /**
     * @param $uid
     * @param $regId
     * @param $appId
     * @param $provider
     * @param $channelId
     * @return bool
     */
    public static function initPushUser($uid, $regId, $appId, $provider, $channelId): bool
    {
        if (empty($uid) || empty($regId) || empty($appId) || empty($provider)) {
            return false;
        }

        return self::insert([
            'uid'        => $uid,
            'reg_id'     => $regId,
            'provider'   => strtolower($provider),
            'app_id'     => $appId,
            'channel_id' => $channelId,
            'created_at' => date('Y-m-d H:i:s', SERVER_TIME),
            'updated_at' => date('Y-m-d H:i:s', SERVER_TIME),
        ]);
    }

    /**
     * @param $uid
     * @param $regId
     * @return bool
     */
    public static function setUserRegId($uid, $regId): bool
    {
        if (empty($uid) || empty($regId)) {
            return false;
        }

        return self::where('uid', $uid)->update(['reg_id' => $regId, 'updated_at' => date('Y-m-d H:i:s', SERVER_TIME)]);
    }
}