<?php

namespace App\Http\Controllers;

//change the request class if needed
use Illuminate\Http\Request as Request;

use App\Models\User as Entity;
use App\Models\Website\Website;

use Junges\ACL\Models\Group;

use App\Http\Resources\Select2\Role;
use Illuminate\Validation\Rule;

use App\Http\Resources\JsonResource;
use Illuminate\Support\Carbon;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Auth;

class UsersController extends Controller 
{
    protected $request;
    
    public function __construct(Request $request)
    {
        $this->request = $request;

        $this->middleware(function ($request, $next) {

            if (!$request->entity || !($request->entity instanceof Entity)) {
                return $next($request);
            }

            $entity = $request->entity;
    
            if ($entity->id == 0) {
                throw ValidationException::withMessages(['email' => __('Zabranjeno je menjanje sistemskog naloga')]);
            }

            if ($entity->id == auth()->user()->id) {
                throw ValidationException::withMessages(['email' => __('Zabranjeno je menjanje sopstvenog naloga')]);
            }
            
            return $next($request);
        });
    }
    
    public function index()
    {   
        return view('users.index');
    }
    
    /*
     * Yajrabox datatables metod
     */
    public function datatable()
    {
        $query = Entity::query()->where('active', '1')
            ->where('id', '>', 0);
        
        return datatables($query)
            ->addColumn('actions', function ($entity) {
                return view('users.partials.table.actions', 
                            ['entity' => $entity]);
            })
            ->editColumn('phone', function ($entity) {
                return $entity-> phone ? $entity->phone : '---';
            })
            ->rawColumns(['actions', 'image'])
            ->setRowAttr([
                'data-id' => function($entity) {
                    return $entity->id;
                }
            ])
            ->make(true);
    }
    
    public function create()
    {   
        $entity = new Entity();
        
        $websites = Website::orderBy('title')->get();
        
        $usersGroups = Role::collection(
                    Group::get()->values()
                )->toArray($this->request);
        
        return view('users.create', [
            'entity' => $entity,
            'websites' => $websites,
            'currentUsersGroups' => [],
            'usersGroups' => $usersGroups
        ]);
    }
    
    public function store()
    {   
        $request = $this->request;
        
        $sviWebsiteId = Website::getAllIdsStr();
        
        $allUsersGroupsIds =  Group::get()->pluck('id')->toArray();
        
        $imageRules = \App\Models\Image::getImageValidationRules();
        
        if(count($allUsersGroupsIds) > 0) {
            $allUsersGroupsIds = implode(',', $allUsersGroupsIds);
        }
        
        $data = $request->validate([
            'first_name' => ['required', 'string', 'max:190'],
            'last_name' => ['required', 'string', 'max:100'],
            'email' => ['required', 'email', 'max:100', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8', 'max:190', 'confirmed'],
            'password_confirmation' => ['required', 'string'],
            'phone' => ['nullable', 'string', 'max:100'],
//            'primary_website' => ['required', 'in:' . $sviWebsiteId],
            'websites' => "nullable|array",
            'websites.*' => ['required', 'in:' . $sviWebsiteId],
            'users_group' => ['required', 'in:' . $allUsersGroupsIds],
            'image_profile' => array_merge($imageRules, [Rule::dimensions()->minWidth(100)->minHeight(100)]),
        ]);
        
        $entity = new Entity();
        
        $data['password'] = bcrypt($data['password']);

        $entity->fill($data);
        $entity->save();
        
        $entity->storeImage('image_profile');
        
        if(!array_key_exists('websites', $data)){
            $data['websites'] = [];
        }
        
//        if(!in_array($data['primary_website'], $data['websites'])){
//            array_push($data['websites'], $data['primary_website']);
//        }
        
        $entity->websites()->attach($data['websites']);
        //brisemo usera iz svih grupa kojima mozda pripada
        foreach($entity->groups as $userGroup){
            $entity->revokeGroup($userGroup);
        }
        //ubacujemo usera u novu grupu
        $entity->assignGroup([$data['users_group']]);

        
        if ($request->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Korisnik je uspešno sačuvan!'));
        }
        
        return redirect()->route('users.index')->withSystemSuccess(__('Korisnik je uspešno sačuvan!'));
    }
    
    public function edit(Entity $entity)
    {
        $websites = Website::orderBy('title')->get();
        
        $usersGroups = Role::collection(Group::get()->values())
                            ->toArray($this->request);
        
        $currentUsersGroups = $entity->groups->pluck('id')->toArray();
        
            return view('users.edit', [
            'entity' => $entity,
            'websites' => $websites,
            'currentUsersGroups' => $currentUsersGroups,
            'usersGroups' => $usersGroups
        ]);
    }
    
    public function update(Entity $entity)
    {
        $request = $this->request;
        
        $sviWebsiteId = Website::getAllIdsStr();
        
        $allUsersGroupsIds =  Group::get()->pluck('id')->toArray();
        
        $imageRules = \App\Models\Image::getImageValidationRules();
        
        if(count($allUsersGroupsIds) > 0) {
            $allUsersGroupsIds = implode(',', $allUsersGroupsIds);
        }
        
        $data = $request->validate([
            'first_name' => ['required', 'string', 'max:190'],
            'last_name' => ['required', 'string', 'max:100'],
            'email' => ['required', 'email', 'max:100', 'unique:users,email,' . $entity->id ],
            'phone' => ['nullable', 'string', 'max:100'],
//            'primary_website' => ['required', 'in:' . $sviWebsiteId],
            'websites' => "nullable|array",
            'websites.*' => ['required', 'in:' . $sviWebsiteId],
            'users_group' => ['required', 'in:' . $allUsersGroupsIds],
            'image_profile' => array_merge($imageRules, [Rule::dimensions()->minWidth(100)->minHeight(100)])
        ]);
        
        $entity->fill($data);
        $entity->save();
        
        $entity->updateImage('image_profile');
        
        if(!array_key_exists('websites', $data)){
            $data['websites'] = [];
        }
        
//        if(!in_array($data['primary_website'], $data['websites'])){
//            array_push($data['websites'], $data['primary_website']);
//        }
        
        $entity->websites()->sync($data['websites']);
        //brisemo usera iz svih grupa kojima mozda pripada
        foreach($entity->groups as $userGroup){
            $entity->revokeGroup($userGroup);
        }
        //ubacujemo usera u novu grupu
        $entity->assignGroup([$data['users_group']]);

        
        if ($request->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Korisnik je uspešno izmenjen!'));
        }
        
        return redirect()->route('users.index')->withSystemSuccess(__('Korisnik je uspešno izmenjen!'));
    }
    
    public function delete(Entity $entity)
    {
        $entity->active = Entity::INACTIVE;
        $entity->save();
        
        if ($this->request->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Korisnik je uspešno obrisan!'));
        }
        
        return redirect()->route('users.index')->withSystemSuccess(__('Korisnik je uspešno obrisan!'));
    }

    public function loginWithId(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:users,id'
        ]);

        Auth::loginUsingId($request->id);
        
        if(Auth::check()){
            return redirect('/public/truck/invoices');
        }
    }
}
