SpotRepository.php 2.88 KB
<?php

namespace App\Repositories\Business;

use App\Exceptions\Api\ApiException;
use App\Modules\Enums\ErrorCode;
use App\Modules\Models\Business\Business;
use App\Modules\Models\Spot\Spot;
use App\Modules\Repositories\BaseRepository;


/**
 * Class SpotRepository
 * @package App\Repositories\Spot
 */
class SpotRepository extends BaseRepository
{


    function getSelectedSpot($user_obj)
    {
        $where = [
            ['id', '=', $user_obj->business_id]
        ];
        $business = Business::where($where)->first();
        if ($business == null) {
            throw new ApiException(ErrorCode::BUSINESS_NOT_EXIST, trans('api.error.business_not_exist'));
        }
        if ($business->selected_spot_id) {
            return $business->selected_spot_id;
        }
        return false;
    }

    public function getToShowSpot($user_obj, $bool = false)
    {
        if ($selected_spot = $this->getSelectedSpot($user_obj)) {
            return $selected_spot;
        }
        $spots_obj = $this->getMylist($user_obj);
        if($bool){
            return $spots_obj[0];
        }else{
            return $spots_obj[0]->id;
        }
    }

    public function getToShowSpotObj($user_obj)
    {
        if ($selected_spot = $this->getSelectedSpot($user_obj)) {
            $spot = Spot::where('id', $selected_spot)->first();
            if ($spot == null) {
                throw new ApiException(ErrorCode::BUSINESS_DO_NOT_HAS_THIS_SPOT, trans('api.error.business_do_not_has_this_spot'));
            }
            return $spot;
        }
        $spots_obj = $this->getMylist($user_obj);
        return $spots_obj[0];

    }


    public function getMylist($user_obj)
    {
        $where = [
            [
                'business_id', '=', $user_obj->business_id,
            ],
        ];
        $spots = Spot::where($where)->get();
        if ($spots == null) {
            throw new ApiException(ErrorCode::BUSINESS_DO_NOT_HAS_SPOT, trans('api.error.business_do_not_has_spot'));
        }
        return $spots;

    }

    public function setSpotSelected($user_obj, $spot_id)
    {
        $business = $user_obj->business()->first();
        if ($business == null) {
            throw new ApiException(ErrorCode::USER_BUSINESS_NOT_FIND, trans('api.error.user_business_not_find'));
        }
        if ($business->selected_spot_id == $spot_id) {
            return true;
        }
        $business->selected_spot_id = $spot_id;
        $business->save();
        return true;
    }

    function spotPermission($user_obj, $spot_id)
    {
        $where = [
            ['business_id', '=', $user_obj->business_id],
            ['id', '=', $spot_id],
        ];
        $spot = spot::where($where)->first();
        if ($spot == null) {
            throw new ApiException(ErrorCode::BUSINESS_DO_NOT_HAS_SPOT_PERMISSION, trans('api.error.business_do_not_has_spot_permission'));
        }
        return $spot;
    }

}