<?php

namespace App\Http\Controllers\Pages;

use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Laravel\Fortify\Rules\Password;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\Datatables\Datatables;
use Haruncpi\LaravelIdGenerator\IdGenerator;
use RealRashid\SweetAlert\Facades\Alert;

use App\Models\{User, Group};

class UserController extends Controller
{
    protected function passwordRules()
    {
        return ['required', 'string', new Password, 'confirmed'];
    }
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $page_title = 'User';
        $page_description = 'This is User test page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Users'],
            ['page' => 'users', 'title' => 'Data User']
        ];
        return view('pages.user.index', compact('page_title', 'page_description', 'page_breadcrumbs'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $page_title = 'Create User';
        $page_description = 'This is Create User test page';
        $groups = Group::all();
        return view('pages.user.create', compact('groups', 'page_title', 'page_description'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'username' => 'required|unique:users|max:255',
            'email' => 'required|unique:users|max:255',
            'password' => $this->passwordRules(),
        ]);
        if ($validator->fails()) {
            Alert::warning('Oops!', 'Something When Wrong!');
            return redirect('users')->withErrors($validator);
        } else {
            $id = IdGenerator::generate(['table' => 'users', 'field' => 'iduser', 'length' => 6, 'prefix' => 'USR']);
            User::create([
                'iduser' => $id,
                'idgroup' => $request->idgroup,
                'name' => $request->name,
                'username' => $request->username,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'isactive' => $request->isactive,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            Helper::Activity('users', $id, 'CREATE');
            Alert::success('Success!', 'Data Has Been Saved!');
            return redirect('users');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $users = DB::table('users')
            ->join('groups', 'groups.idgroup', '=', 'users.idgroup')
            ->select('users.*', 'groups.title')
            ->get();
        $i = 0;
        $array = array();
        foreach ($users as $data) {
            $i++;
            $array[] = array(
                'no' => $i,
                'iduser' => $data->iduser,
                'name' => $data->name,
                'username' => $data->username,
                'level' => $data->title,
                'email' => $data->email,
                'isactive' => $data->isactive,
                'created_at' => $data->created_at,
                'updated_at' => $data->updated_at,
                'password' => $data->password,
                'profile_photo_url' => "https://ui-avatars.com/api/?name=$data->name&color=7F9CF5&background=EBF4FF"
            );
        }
        return Datatables::of($array)->make(true);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $page_title = 'Edit User';
        $page_description = 'This is Edit User test page';
        $groups = Group::all();
        $data = User::find($id);
        return view('pages.user.edit', compact('groups', 'page_title', 'page_description', 'data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        if ($request->password == "") {
            User::find($id)
                ->update([
                    'idgroup' => $request->idgroup,
                    'name' => $request->name,
                    'idgroup' => $request->idgroup,
                    'username' => $request->username,
                    'email' => $request->email,
                    'isactive' => $request->isactive,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            Alert::success('Success!', 'Data has been update!');
            return redirect('users');
        } else {
            User::find($id)
                ->update([
                    'idgroup' => $request->idgroup,
                    'name' => $request->name,
                    'username' => $request->username,
                    'email' => $request->email,
                    'password' => Hash::make($request->password),
                    'isactive' => $request->isactive,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            Helper::Activity('users', $id, 'UPDATE');
            Alert::success('Success!', 'Data has been update!');
            return redirect('users');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Helper::Activity('users', $id, 'DELETE');
        User::find($id)->delete();
    }
}
