<?php

namespace App\Http\Controllers\API\v1\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;

class AddController extends Controller
{
    public function __invoke (Request $request)
    {
    	$this->validateRequest($request);
    	$user = $this->insertAdmin($request);

        activity()
            ->performedOn($user)
            ->withProperties([
                'admin_id' => $user->id,
                'admin_name' => $user->name,
                'admin_email' => $user->email,
                'admin_role' => $user->role,
                'created_by_admin_id' => $request->user() ? (int) $request->user()->id : null,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("create admin: {$user->name}");
    	return response()->json([
    		'status'  =>  'success',
    		'message'  =>  'Admin added successfully'
    	]);
    }

    private function insertAdmin($request)
    {
    	$admin = $request->all();
    	$admin['password'] = bcrypt($request->password);
    	return User::create($admin);
    }

    private function validateRequest($request)
    {
    	$this->validate($request, [
    		'name'  =>  'required|unique:users',
    		'email'  =>  'required|email|unique:users',
    		'password'  =>  'required',
    		'confirm_password'  =>  'same:password',
			'role'  =>  'required'
    	]);
    }
}
