<?php

namespace App\Traits;

use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

/*
|--------------------------------------------------------------------------
| Api Responser Trait
|--------------------------------------------------------------------------
|
| This trait will be used for any response we sent to clients.
|
*/

trait ApiResponserTrait
{
    /**
     * Return a success JSON response.
     *
     * @param  array|string  $data
     * @param  string  $message
     * @param  int|null  $code
     * @return \Illuminate\Http\JsonResponse
     */
    protected function success($data, $message = '', $code = 200, $errors=[])
    {
        $isBlocked = $this->isUserBlocked();
        if($isBlocked != false){
            return $isBlocked;
        }
        return response()->json([
            'status' => true,
            'status_code' => $code,
            'message' => $message,
            'data' => $data,
            'errors' => (object)$errors
        ], $code);
    }

    /**
     * Return an error JSON response.
     *
     * @param  string  $message
     * @param  int  $code
     * @param  array|string|null  $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function error($message = '', $code = 400, $data = [], $errors=[])
    {
        $isBlocked = $this->isUserBlocked();
        if($isBlocked != false){
            return $isBlocked;
        }
        return response()->json([
            'status' => false,
            'status_code' => $code,
            'message' => $message,
            'data' => $data,
            'errors' => $errors
        ], $code);
    }

    private function isUserBlocked(){
        if(Auth::check() && Auth::user()->is_block == 1){
            Auth::user()->update([
                'is_active' => 0
            ]);
            return response()->json([
                'status' => false,
                'status_code' => 401,
                'message' => "Your account is temporary suspended",
                'data' => array(),
                'errors' => array()
            ], 401);
        }else{
            return false;
        }
    }

}
