<?php

namespace App\Modules\Welfare\Models;

use Illuminate\Database\Eloquent\Model;

class WelfareBook extends Model
{
    protected $table = 'welfare_books';

    protected $fillable = [
        'bid', 'book_name', 'charge_rate', 'data_img', 'is_enable', 'is_important', 'channer_user_id', 'force_subscribe_rate', 'created_at', 'updated_at'
    ];


    static function createWelfareBook($data)
    {
        return self::create($data);
    }

    static function getWelfarePromotionBooks($params, $isAll = false)
    {
        $search_object = self::orderBy('created_at', 'desc');
        $search_object->where('is_enable', 1);

        if (isset($params['is_important']) && $params['is_important']) {
            $search_object->where('is_important', $params['is_important']);
        }

        if (isset($params['id']) && $params['id']) {
            $search_object->where('id', $params['id']);
        }

        if ($isAll) {
            return $search_object->get();
        } else {
            return $search_object->paginate();
        }
    }

    static function updateWelfarePromotionBook($id, $params)
    {
        $updateParams = [];
        $search_object = self::where('id', $id);

        if (isset($params['book_name']) && $params['book_name']) {
            $updateParams['book_name'] = $params['book_name'];
        }

        if (isset($params['data_img']) && $params['data_img']) {
            $updateParams['data_img'] = $params['data_img'];
        }

        if (isset($params['charge_rate']) && $params['charge_rate']) {
            $updateParams['charge_rate'] = $params['charge_rate'];
        }

        if (isset($params['is_enable'])) {
            $updateParams['is_enable'] = $params['is_enable'];
        }

        if (isset($params['is_important']) && $params['is_important']) {
            $updateParams['is_important'] = $params['is_important'];
        }

        if (isset($params['force_subscribe_rate']) && $params['force_subscribe_rate']) {
            $updateParams['force_subscribe_rate'] = $params['force_subscribe_rate'];
        }

        return $search_object->update($updateParams);
    }

}
