<?php

namespace App\Http\Controllers\Admins\Users;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Spatie\Permission\Models\Role;

class UserController extends Controller
{

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // call table user with pagination
        $users = User::latest()->paginate(10);

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $roles = Role::latest()->get();

        // call view users.create
        return view('pages.admins.users.create', compact('roles'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // validation
        $rules = array(
            'nik'  => 'required|unique:users|min:16|max:16',
            'name'  => 'required|min:5',
            'email' => 'required|email|unique:users',
            'password'  => 'required|min:8',
            'gender'  => 'required',
            'place_of_birth'  => 'required',
            'date_of_birth'  => 'required',
        );
        $validator = Validator::make($request->all(), $rules);

        // check validation
        if ($validator->fails()) {
            return Redirect::to('admin/users/create')
                ->withErrors($validator)
                ->withInput($request->except('password'));
        } else {
            // create new account
            $user = User::create([
                'nik' => $request->nik,
                'name' => $request->name,
                'email' => $request->email,
                'password' => bcrypt($request->password),
                'gender' => $request->gender,
                'place_of_birth' => $request->place_of_birth,
                'date_of_birth' => $request->date_of_birth,
            ]);

            // Create role for user
            $role = Role::findOrFail($request->role); // Pengunjung
            $user->assignRole($role);

            // Create Session message
            Session::flash('users-message', [
                'type' => 'success',
                'msg' => 'Anda berhasil menambahkan data!'
            ]);

            return Redirect::to('admin/users');
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        // get data from user
        $user = User::findOrFail($id);
        $roles = Role::latest()->get();

        // call view pages
        return view('pages.admins.users.edit', compact('user', 'roles'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {

        $userId = User::findOrFail($id);
        // validation
        $rules = array(
            'nik'  => [
                'required',
                'min:16',
                'max:16',
                Rule::unique('users')->ignore($userId),
            ],
            'name'     => 'required|min:5',
            'password'   => 'required|min:8',
            'gender'  => 'required',
            'place_of_birth'  => 'required',
            'date_of_birth'  => 'required',
        );
        $validator = Validator::make($request->all(), $rules);

        // process the login
        if ($validator->fails()) {
            return Redirect::to('admin/users/edit/' . $id)
                ->withErrors($validator)
                ->withInput($request->except('password'));
        } else {
            // create new account
            $user = User::findOrFail($id);
            if (!$user) {
                // Create Session message
                Session::flash('users-message', [
                    'type' => 'warning',
                    'msg' => 'Data pengguna tidak ditemukan!'
                ]);

                return Redirect::to('admin/users');
            }
            $user->update([
                'nik' => $request->nik,
                'name' => $request->name,
                'password' => bcrypt($request->password),
                'gender' => $request->gender,
                'place_of_birth' => $request->place_of_birth,
                'date_of_birth' => $request->date_of_birth,
            ]);

            // Update role for user
            if (isset($user->roles[0])) {
                $user->removeRole($user->roles[0]->name);
            }
            $user->assignRole($request->role);

            // Create Session message
            Session::flash('users-message', [
                'type' => 'success',
                'msg' => 'Anda berhasil mengubah data!'
            ]);

            return Redirect::to('admin/users');
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        // get data from role
        $role = Role::findOrFail($id);

        // check role
        if (!$role) {
            // Create Session message
            Session::flash('roles-message', [
                'type' => 'warning',
                'msg' => 'Data pengguna tidak ditemukan!'
            ]);

            return Redirect::to('admin/roles');
        }

        // delete role
        $role->delete();

        // Create Session message
        Session::flash('roles-message', [
            'type' => 'success',
            'msg' => 'Anda berhasil menghapus data!'
        ]);

        return Redirect::to('admin/roles');
    }
}
