<?php

namespace App\Http\Controllers\Admin\Core\Auth;

use Auth;
use Image;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

use App\Models\Core\Auth\Role;
use App\Models\Core\Auth\User;

use App\Repositories\Core\Auth\Users;
use App\Datatables\Admin\Core\Auth\UsersDataTable;

class UserController extends Controller
{
    public function index(UsersDataTable $dataTable)
    {
        $data = \App\Repositories\Config::init();
        return $dataTable->render('admin.Core.Auth.User.index', $data);
    }

    public function modalCreate()
    {
        $data['roles'] = Users::getRolesToEdit();
        return view('Admin.Core.Auth.User.modal', $data);
    }

    public function modalEdit($id = false)
    {
        $user = $id ? Users::get($id) : false;
        $data['roles'] = Users::getRolesToEdit();
        $data['user'] = $user ? $user->toArray() : [];
        $data['user']['roles'] = $user->roles->pluck('id')->toArray();
        return view('Admin.Core.Auth.User.modal', $data);
    }

    public function storeAjax(Request $request)
    {
        $data = $request->all();
        $ret = Users::store($data);
        return response()->json(['code' => '200']);
    }

    public function create()
    {
        $data = \App\Repositories\Config::init();
        $data['roles'] = Users::getRolesToEdit();
        return view('Admin.Core.Auth.User.create', $data);
    }

    public function store(Request $request)
    {
        /*
            $this->validate($request, [
                'last_name'  => 'required',
                'first_name' => 'required',
                'email'      => 'required|email|unique:users,email,NULL,id,deleted_at,NULL',
            ]);
        */
        $input = $request->all();
        if (empty($input['password'])) {
            unset($input['password']);
        }
        $user = Users::store($input);

        return redirect()->route('admin.Core.Auth.User.index')
            ->with('growl', [__('boilerplate::users.successadd'), 'success']);
    }

    public function edit($id)
    {
        $data = \App\Repositories\Config::init();
        $data['roles'] = Users::getRolesToEdit();
        $data['user'] = Users::get($id);
        return view('Admin.Core.Auth.User.edit', $data);
    }

    public function destroy($id)
    {
        Users::delete($id);
    }

    public function firstLogin($token, Request $request)
    {
        $user = User::where(['remember_token' => $token])->firstOrFail();

        return view('boilerplate::auth.firstlogin', compact('user', 'token'));
    }

    public function firstLoginPost(Request $request)
    {
        $this->validate(
            $request, [
            'token'                 => 'required',
            'password'              => 'required|min:8',
            'password_confirmation' => 'required|same:password',
            ]
        );

        $user = User::where(['remember_token' => $request->input('token')])->first();

        $user->password = bcrypt($request->input('password'));
        $user->remember_token = Str::random(32);
        $user->last_login = Carbon::now()->toDateTimeString();
        $user->save();

        Auth::attempt(['email' => $user->email, 'password' => $request->input('password'), 'active' => 1]);

        return redirect()->route('boilerplate.dashboard')
            ->with('growl', [__('boilerplate::users.newpassword'), 'success']);
    }

    public function profile()
    {
        $user = Users::get();
        $data['user'] = $user ? $user->toArray() : [];
        $data['user']['name'] = $user->name;
        $data['user']['avatar'] = Users::getAvatar($user->id);
        return view('Admin.Core.Auth.User.modalProfile', $data);
    }

    public function profilePost(Request $request)
    {
        $this->validate(
            $request, [
            'avatar'                => 'mimes:jpeg,png|max:10000',
            'last_name'             => 'required',
            'first_name'            => 'required',
            'password_confirmation' => 'same:password',
            ]
        );

        $avatar = $request->file('avatar');
        $user = Auth::user();

        if ($avatar && $file = $avatar->isValid()) {
            $destinationPath = dirname($user->avatar_path);
            if (!is_dir($destinationPath)) {
                mkdir($destinationPath, 0766, true);
            }
            $extension = $avatar->getClientOriginalExtension();
            $fileName = md5($user->id.$user->email).'_tmp.'.$extension;
            $avatar->move($destinationPath, $fileName);

            Image::make($destinationPath.DIRECTORY_SEPARATOR.$fileName)
                ->fit(100, 100)
                ->save($user->avatar_path);

            unlink($destinationPath.DIRECTORY_SEPARATOR.$fileName);
        }

        $input = $request->all();

        if ($input['password'] !== null) {
            $input['password'] = bcrypt($input['password']);
            $input['remember_token'] = Str::random(32);
        } else {
            unset($input['password']);
        }

        $user->update($input);

        return redirect()->route('boilerplate.user.profile')
            ->with('growl', [__('boilerplate::users.profile.successupdate'), 'success']);
    }

    public function avatarDelete()
    {
        $user = Auth::user();
        if (is_file($user->avatar_path)) {
            unlink($user->avatar_path);
        }
    }

    public function toggleActive(Request $request)
    {
        $data = Users::toggle_active($request->input('id'), ($request->input('active') == 'true') ? 1 : 0);
        return response()->json(['error' => 0]);
    }
}
