<?php

namespace App\Http\Controllers\panel;

use App\Http\Controllers\Controller;
use App\Rules\Mobile;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{

    public function __construct()
    {
        $this->authorizeResource(User::class);
    }


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $users = User::where([['id', '<>', auth()->user()->id], ['role', 'user']])->latest()->paginate(20);
        return view('panel.users.list', compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        return view('panel.users.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'mobile' => ['required', new Mobile(), 'unique:users'],
            'username' => ['nullable', 'max:20', 'alpha_dash', 'unique:users,username'],
            'password' => 'required|min:8'
        ]);

        if ($request->has('status') and $request->status == 'active') {
            $status = 'active';
        }

        $data = $request->all();
        $data['status'] = $status ?? 'disabled';
        $data['mobile_verified_at'] = !$request->has('needsVerification') ? Carbon::now() : null;
        $data['email_verified_at'] = !$request->has('needsVerification') ? Carbon::now() : null;

        $user = User::create($data);

        if ($request->has('needVerification') and $request->needVerification == 'true') {
            $user->accountVerificationActions();
        }

        if ($request->expectsJson()) {
            return response()->json(['status' => 'success', 'msg' => 'با موفقیت افزوده شد']);
        }

        return redirect()->route('panel.users.index')->with('success', 'با موفقیت افزوده شد');
    }

    /**
     * Display the specified resource.
     *
     * @param \App\User $user
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(User $user)
    {
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param \App\User $user
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(User $user)
    {
        return view('panel.users.edit', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\User $user
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\DiskDoesNotExist
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileDoesNotExist
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileIsTooBig
     */
    public function update(Request $request, User $user)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email,' . $user->id . ',id',
            'mobile' => ['required', new Mobile(), 'unique:users,mobile,' . $user->id . ',id'],
            'username' => ['nullable', 'max:20', 'alpha_dash', 'unique:users,username,' . $user->id . ',id'],
            'password' => 'nullable|min:8',
            'status' => 'required|in:active,disabled,banned',
        ]);

        $mobileVerified = $request->has('mobileVerified') ? $request->mobileVerified : null;
        $emailVerified = $request->has('emailVerified') ? $request->emailVerified : null;

        $data = Arr::except($request->all(), ['password', 'mobileVerified', 'emailVerified']);
        $data['mobile_verified_at'] = $mobileVerified;
        $data['email_verified_at'] = $emailVerified;

        //change password only if set a new one on form
        if ($request->password) {
            $data['password'] = $request->password;
        }

        if ($request->hasFile('avatar')) {
            $request->validate([
                'avatar' => 'sometimes|file|image'
            ]);
            $avatarPath = $request->avatar->store('avatars');
            if ($user->getFirstMedia('avatar')) {
                $user->getFirstMedia('avatar')->delete();
            }
            $user->addMedia('files/' . $avatarPath)->toMediaCollection('avatar');
        }

        $user->update($data);

        return redirect()->route('panel.users.index')->with('success', 'با موفقیت ویرایش شد');
    }

    /**
     * Show the form for editing user profile
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editProfile()
    {
        if (auth()->user()->isUser()) {
            return view('panel.users.user-profile', ['user' => auth()->user()]);
        }
        return view('panel.users.profile', ['user' => auth()->user()]);
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function updateProfile(Request $request)
    {
        /** @var User $user */
        $user = auth()->user();
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email,' . $user->id . ',id',
            'mobile' => ['required', new Mobile(), 'unique:users,mobile,' . $user->id . ',id'],
            'username' => ['nullable', 'max:20', 'alpha_dash', 'unique:users,username,' . $user->id . ',id'],
        ]);

        if ($request->hasFile('avatar')) {
            $request->validate([
                'avatar' => 'sometimes|file|image'
            ]);
            $avatarPath = $request->file('avatar')->store('avatars');
            if ($user->getFirstMedia('avatar')) {
                $user->getFirstMedia('avatar')->delete();
            }
            $user->addMediaFromRequest('avatar')->toMediaCollection('avatar');
        }

        $data = [
            'name' => $request->name,
            'email' => $request->email,
            'mobile' => $request->mobile,
            'username' => $request->username
        ];

        if ($request->has('signature')) {
            $data['signature'] = $request->signature;
        }

        $user->update($data);

        return redirect()->back()->withSuccess('حساب کاربری با موفقیت ذخیره شد');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param \App\User $user
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     * @throws \Exception
     */
    public function destroy(User $user, Request $request)
    {
        $user->delete();

        if ($request->expectsJson()) {
            return response()->json(['status' => 'success', 'msg' => 'با موفقیت حذف شد']);
        }

        return redirect()->route('panel.users.index')->with('success', 'با موفقیت حذف شد');
    }

    public function showChangePasswordForm()
    {
        if (auth()->user()->isUser()) {
            return view('panel.users.user-change-password');
        }
        return view('panel.users.change-password');
    }

    public function updatePassword(Request $request)
    {
        Validator::make($request->all(), [
            'currentPassword' => 'required',
            'password' => 'required|min:8'
        ], [
            'currentlyPassword.required' => 'وارد کردن کلمه عبور فعلی الزامی میباشد',
            'password.required' => 'وارد کردن کلمه عبور جدید الزامی میباشد',
        ])->validate();

        if (!Hash::check($request->currentPassword, auth()->user()->password)) {
            return redirect()->back()->withErrors(['authError' => 'کلمه عبور وارد شده اشتباه است']);
        }

        auth()->user()->update([
            'password' => $request->password
        ]);

        return redirect()->back()->withSuccess('کلمه عبور با موفقیت تغییر کرد');
    }

    public function search(Request $request)
    {
        $request->validate([
            'q' => 'required|min:3'
        ]);

        $name = trim(htmlentities($request->q));

        $users = User::select('id', 'name as text')->where('name', 'like', '%' . $name . '%')->get()->toArray();

        return response()->json(['status' => 'success', 'items' => $users]);
    }
}
