<?php

namespace App\Modules\Saasuser\Model;

use Exception;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\JsonResponse;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Yajra\DataTables\Facades\DataTables;

class SaasUser extends Authenticatable
{
    use Notifiable, SoftDeletes;

    protected $guard = 'saas';

    protected $fillable = [
        'name',
        'email',
        'password',
        'is_super',
        'avatar',
        'created_by',
        'updated_by',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get all users lists
     *
     * @param $moduleName
     * @return JsonResponse
     * @throws Exception
     */
    static public function getSaasUsers($moduleName)
    {
        
        $saasModel = self::query();

        return DataTables::eloquent($saasModel)
            ->addColumn('is_super', function ($user) {
                return isset($user->is_super) && $user->is_super == 1 ? 'Yes' : 'No';
            })
            ->addColumn('action', function ($user) use ($moduleName)  {
                $action = '';
                $action .= View('layouts.actions.view')->with('model', $user)->with('route', $moduleName.'.show');
                if(\Illuminate\Support\Facades\Auth::user()->is_super){
                    $action .= View('layouts.actions.edit')->with('model', $user)->with('route', $moduleName.'.edit');
                    $action .= View('layouts.actions.delete')->with('model', $user)->with('route', $moduleName.'.destroy');
                }
                return $action .= '';
            })
            ->rawColumns(['action'])
            ->make(true);

    }

    /**
     * @param Request $request
     * @return string
     */
    protected function uploadAvatar($request)
    {
        try {
            $file  = $request->file('avatar');
            $path  = $file->hashName('avatars');
            $image = Image::make($file)->fit(150);
            Storage::disk('public')->put($path, (string)$image->encode());
            return $path;
        } catch (Exception $exception) {

        }
    }
}
