<?php

namespace Modules\User\Controllers\Admin;

/** Ajax Request */

use App\Services\Response\ResponseService;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Country\Services\CountryService;
use Modules\MainService\Enums\ViewEnum;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Exports\AdminExport;
use Modules\User\Requests\Admin\UserRequest;
use Modules\User\Services\ModuleService;
use Modules\User\Services\UserService;

class UserController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/admin/users';
    /** View folder */
    private $viewDirectory= 'admin.users.';
    //

    public function __construct(
        private UserService $userService,
        private ModuleService $moduleService,
        private CountryService $countryService,
    ){}

    /**
     * Display a listing of the users.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $data =
            [
                'head'=>__('users.head'),
                'view' => ViewEnum::INDEX->value,
                'route'=>$this->viewDirectory,
                'request' => $request,
            ];
        return $this->countryService->render($data);
    }

    /**
     * return data of the users.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request)
    {
        if(isset($request->orderBy))
        {
            $orderBy = json_decode($request->orderBy, true);
            $request->merge(['orderBy'=>['key'=>$orderBy['key'], 'value'=>$orderBy['value']]]);
        }
        if ($request->export)
        {
            $data = $request->all();
            $data['roles']=UserRoleEnum::admins();
            $users = $this->userService->get($data);
            return Excel::download(new AdminExport($users,Auth::user()), 'admins.xlsx');
        }
        $roles = UserRoleEnum::admins();
        $request->merge([
            'paginate' => true,
            'route' => $this->viewDirectory,
            'view' => ViewEnum::LIST->value,
            'request'=>$request,
            'roles'=> $roles,
        ]);

        return $this->userService->renderView($request->all());
    }

    public function fetchColumnToggle(Request $request)
    {
        $data = $request->all();
        $data['user_id'] = auth()->user()->id;
        $this->userService->toggleColumn($data);
    }

    /**
     * Show the form for creating a new User.
     *
     * @return View
     */
    public function create() :View
    {
        $data =
        [
            'head'=>__('users.new'),
            'action' => route('users.store'),
            'roles' => UserRoleEnum::admins(),
            'view' => ViewEnum::FORM->value,
            'route'=> $this->viewDirectory,
            'user_modules' => [],
            'modules' => $this->moduleService->get(['group'=>true,'dashboard'=>'admin']),
            'countries' => $this->countryService->get()
        ];
        return $this->userService->render($data);
    }

    /**
     * Store a newly created User in storage.
     * @param UserRequest $request
     * @return JsonResponse
     */
    public function store(UserRequest $request) :JsonResponse
    {
        $data = $request->validated();
        $data['verified'] = 1;
        $this->userService->create($data);

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('users.index'),
        ];
        return ResponseService::response($response);
    }


    public function lock($id)
    {
        $user = $this->userService->getItem($id);
        if (!$user)
        {
            abort(404);
        }
        $this->userService->updateLock($id);
        session()->flash('message', __('dashboard.saveDone'));
        return redirect()->back();
    }

    /**
     * Show the form for editing the specified User.
     *
     * @param  int $id
     * @return View
     */
    public function edit(int $id) :View
    {
        $user = $this->userService->getItem($id);
        if (!$user)
        {
            abort(404);
        }
        $data =
            [
                'head'=>__('users.edit'),
                'action' => route('users.update', $user->id),
                'roles' => UserRoleEnum::admins(),
                'view' => ViewEnum::FORM->value,
                'route'=> $this->viewDirectory,
                'user_modules' => $this->moduleService->get(['user_id'=>$id])->pluck('id')->toArray(),
                'modules' => $this->moduleService->get(['group'=>true,'dashboard'=>'admin']),
                'countries' => $this->countryService->get(),
                'user'=>$user
            ];
        return $this->userService->render($data);
    }

    public function show(int $id) :View
    {
        $user = $this->userService->getItem($id);
        if (!$user)
        {
            abort(404);
        }
        $data =
            [
                'head'=>__('users.show'),
                'view' => ViewEnum::SHOW->value,
                'route'=> $this->viewDirectory,
                'user_modules' => $this->moduleService->get(['user_id'=>$id])->pluck('id')->toArray(),
                'modules' => $this->moduleService->get(['group'=>true,'dashboard'=>'admin']),
                'user'=>$user
            ];
        return $this->userService->render($data);
    }

    /**
     * Update the specified User in storage.
     * @param UserRequest $request
     * @param int $id
     * @return JsonResponse
     */
    public function update(UserRequest $request, int $id) :JsonResponse
    {
        $user = $this->userService->checkItem($id);
        if (!$user)
        {
            abort(404);
        }
        $this->userService->update($request->validated(), $id);
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('users.index'),
        ];
        return ResponseService::response($response);
    }

    /**
     * Remove the specified User from storage.
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(int $id) :JsonResponse
    {
        $this->userService->destroy($id);
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('users.index'),
        ];
        return ResponseService::response($response);
    }

    /**
     * Remove several users by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $this->userService->destroyAll([
            'ids' => $request->ids,
            'status' => 1
        ]);
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('users.index'),
        ];
        return ResponseService::response($response);
    }

    /**
     * Restore the specified User from storage.
     *
     * @param int $id
     * @return JsonResponse
     */
    public function restore(int $id) :JsonResponse
    {
        $this->userService->destroy($id);
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('users.index'),
        ];
        return ResponseService::response($response);
    }

    /**
     * Restore several users by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $this->userService->destroyAll([
            'ids' => $request->ids,
            'status' => 0
        ]);
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('users.index'),
        ];
        return ResponseService::response($response);
    }
}
