<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\UserRequest;
use App\Models\SecurityManagement\Role;
use App\Models\UserManagement\Admin;
use App\Models\UserManagement\User;
use App\Models\UserManagement\UserType;
use App\Services\ImageService;
use App\Traits\ImageUploadTrait;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;


class UserControllerV1 extends Controller{
    use ImageUploadTrait;

    protected $imageService;

    public function __construct(ImageService $imageService){
        $this->imageService = $imageService;
    }

    public function index(): View{
        $this->authorize('access_user');

        $users = User::role(['user'])
                        ->when(request()->keyword != null, function ($query) {
                            $query->search(request()->keyword);
                        })
                        ->when(request()->active != null, function ($query) {
                            $query->whereStatus(request()->active);
                        })
                        ->orderBy(request()->sortBy ?? 'id', request()->orderBy ?? 'desc')
                        ->paginate(request()->limitBy ?? 10);


        return view('backend.users.index', compact('users'));
    }

    public function create(): View{
        $this->authorize('create_user');
        $roles = Role::get();
        return view('backend.users.create',compact("roles"));
    }

    public function store(UserRequest $request): RedirectResponse{
        $this->authorize('create_user');

        if ($request->hasFile('user_image')) {
            $userImage = $this->imageService->storeUserImages($request->username, $request->user_image);
        }

        $user = Admin::create([
                    'first_name' => $request->first_name,
                    'last_name' => $request->last_name,
                    'username' => $request->username,
                    'email' => $request->email,
                    'email_verified_at' => now(),
                    'phone' => $request->phone,
                    'password' => bcrypt($request->password),
                    'active' => $request->active,
                    'receive_email' => true,
                ]);

        $user->markEmailAsVerified();

        if($request->roles){
            $user->assignRole($request->roles);
        }

        return redirect()->route('admin.users.index')->with([
            'message' => action_message("create"),
            'alert-type' => 'success'
        ]);
    }

    public function show(User $user): View{
        $this->authorize('user_show');

        return view('backend.users.show', compact('user'));
    }

    public function edit(User $user): View{
        $this->authorize('edit_user');
        $roles = Role::get();

        return view('backend.users.edit', compact('user',"roles"));
    }

    public function update(UserRequest $request, User $user): RedirectResponse{
        $this->authorize('edit_user');

        if ($request->hasFile('user_image')) {
            if ($user->user_image) {
                $this->imageService->unlinkImage($user->user_image, 'users');
            }
            $userImage = $this->imageService->storeUserImages($request->username, $request->user_image);
        }

        if ($request->password){
            $password = bcrypt($request->password);
        }

        $user->update([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'username' => $request->username,
            'email' => $request->email,
            'phone' => $request->phone,
            'active' => $request->active,
            'receive_email' => $request->receive_email,
            'user_image' => $userImage ?? $user->user_image,
            'password' => $password ?? $user->password
        ]);


        if($request->filled("roles")){
            $user->roles()->sync($request->roles, true);
           // $user->assignRole($request->roles);
        }
        return redirect()->route('admin.users.index')->with([
            'message' => action_message("update"),
            'alert-type' => 'success'
        ]);
    }

    public function destroy(User $user): RedirectResponse{
        $this->authorize('delete_user');

        if ($user->user_image) {
            $this->imageService->unlinkImage($user->user_image, 'users');
        }

        $user->delete();

        return redirect()->route('admin.users.index')->with([
            'message' => action_message("delete"),
            'alert-type' => 'success'
        ]);
    }

    public function get_users(): JsonResponse{
        $users = User::role(['user'])
                        ->when(request()->input('query') != '', function ($query) {
                            $query->search(request()->input('query'));
                        })
                        ->get(['id', 'first_name', 'last_name', 'email'])->toArray();

        return response()->json($users);
    }
}
