<?php

namespace Portal\Overide\Http\Controllers;

use Illuminate\Database\QueryException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Mail;
use Laravolt\Epicentrum\Contracts\Requests\Account\Delete;
use Laravolt\Epicentrum\Contracts\Requests\Account\Store;
use Laravolt\Epicentrum\Mail\AccountInformation;
use Laravolt\Epicentrum\Repositories\RepositoryInterface;
use Portal\Overide\Model\User;
use Laravolt\Support\Contracts\TimezoneRepository;
use Illuminate\Http\Request;
use Laravolt\Epicentrum\Contracts\Requests\Account\Update;

class UserControllers extends Controller
{
    use AuthorizesRequests;

    protected RepositoryInterface $repository;

    protected TimezoneRepository $timezone;

    /**
     * UserController constructor.
     *
     * @param \Laravolt\Epicentrum\Repositories\RepositoryInterface $repository
     * @param \Laravolt\Support\Contracts\TimezoneRepository        $timezone
     */
    public function __construct(RepositoryInterface $repository, TimezoneRepository $timezone)
    {
        $this->repository = $repository;
        $this->timezone = $timezone;
    }

    /**
     * Display a listing of the resource.
     *
     * @throws \Exception
     */
    public function users(Request $request)
    {
        if(isset($request->role))
        {
            $users = User::where(function ($query) use ($request) {
                $query->whereHas('roles', function ($q) use ($request) {
                          $q->where('role_id', '=', $request->role);
                      });
            })
            ->paginate();

        } else {

            $users = User::where(function ($query) use ($request) {
                $query->where('name', 'like', '%' . $request->search . '%')
                      ->orWhere('email', 'like', '%' . $request->search . '%')
                      ->orWhereHas('roles', function ($q) use ($request) {
                          $q->where('name', 'like', '%' . $request->search . '%');
                      });
            })
            ->paginate();
        }
        
        return view('overide::user.index',compact('users'));

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        $this->authorize('create', User::class);
        $statuses = $this->repository->availableStatus();
        $roles = app('laravolt.epicentrum.role')->all()->pluck('name', 'id');
        $multipleRole = config('laravolt.epicentrum.role.multiple');
        $timezones = $this->timezone->all();

        return view('overide::user.create', compact('statuses', 'roles', 'multipleRole'));
    }

    public function edit($id)
    {
        $user = $this->repository->findById($id);
        $statuses = $this->repository->availableStatus();
        $timezones = $this->timezone->all();
        $roles = app('laravolt.epicentrum.role')->all()->pluck('name', 'id');
        $multipleRole = config('laravolt.epicentrum.role.multiple');
        $roleEditable = config('laravolt.epicentrum.role.editable');

        return view('overide::user.edit', compact('user', 'statuses', 'timezones', 'roles', 'multipleRole', 'roleEditable'));

    }

    public function update(Update $request, $id)
    {
        try {
            $this->repository->updateAccount($id, $request->except('_token', '_method'), $request->get('roles', []));

            return redirect()->back()->withSuccess(trans('laravolt::message.account_updated'));
        } catch (\Exception $e) {
            return redirect()->back()->withError($e->getMessage());
        }
    }

    /**
     * Store the specified resource.
     *
     * @param Store $request
     *
     * @return Response
     */
    public function store(Store $request)
    {
        $this->authorize('create', User::class);

        // save to db
        $roles = $request->get('roles', []);
        $user = $this->repository->createByAdmin($request->all(), $roles);
        $password = $request->get('password');

        // send account info to email
        if ($request->has('send_account_information')) {
            Mail::to($user)->send(new AccountInformation($user, $password));
        }

        return redirect()->route('epicentrum::users.index')->withSuccess(trans('laravolt::message.user_created'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     *
     * @return Response
     */
    
    public function destroy(Delete $request, $id)
    {
        try {
            $this->repository->delete($id);

            return redirect(route('epicentrum::users.index'))->withSuccess(trans('laravolt::message.user_deleted'));
        } catch (QueryException $e) {
            return redirect()->back()->withError($e->getMessage());
        }
    }
}
