<?php

namespace App\Http\Controllers\Hr;

use App\Http\Controllers\Controller;
use App\Models\RoleViewTemp;
use App\Models\UserRoleMaster;
use App\Models\UserRoleMasterStaging;
use Auth;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Redirect;
use Validator;

class RoleController extends Controller
{

    public function index(request $request)
    {
        $list = UserRoleMaster::select('id', 'name','has_create_by_admin', 'status', 'is_delete', DB::raw('id, lpad(id, 10, 0) as ref'))
            ->where('is_delete', 0)
            ->where('has_create_by_admin', 1)
            ->withCount(['users as users_count' => function ($query) {
                $query->where('is_delete', 0);
            }])
            ->orderBy('users_count', 'DESC')
            ->paginate(10);

        $list->map(function ($item) {
            $item['ref'] = "STF" . $item->ref;
        });

        $data['records'] = $list;

        return view('hr.roles.list', $data);
    }

    public function create(request $request)
    {
        return view('hr.roles.create');
    }

    public function createRole(request $request)
    {
        $validator = Validator::make($request->all(),
            ['name' => 'required|max:250|unique:roles,name']
        );
        if ($validator->fails()) {
            return \Redirect::back()->withErrors($validator->errors()->all());
        }
        try {
            $model = new UserRoleMaster;
            $model->name = $request->name;
            $model->created_by = Auth::user()->id;
            $model->save();
            return \Redirect::Route('hr.roles')->with('success', 'Record added Successfully');

        } catch (Exception $e) {
            throw new \App\Exceptions\AdminException($e->getMessage());
        }

    }

    public function edit(Request $request, $id)
    {

        $model = UserRoleMaster::find($id);

        $temp = new RoleViewTemp;
        $temp->role_id = $id;
        $temp->view_by = Auth::user()->id;
        $temp->uuid = self::getUUID();
        $temp->save();

        return \Redirect::Route('hr.roles.update.uuid', $temp->uuid);
    }

    public function editWithUuid($id)
    {

        $userId = Auth::user()->id;
        $temp = RoleViewTemp::select('id', 'uuid', 'role_id'
            , \DB::raw(" TIMESTAMPDIFF(minute, created_at, NOW()) as duration"))
            ->where('uuid', $id)
            ->having('duration', '<=', 10)
            ->where('is_expired', 0)
            ->where('view_by', $userId)
            ->first();

        if (!$temp) {
            return Redirect::route('auth.deactive.logout');
        }

        $role_id = $temp->role_id;

        $model = UserRoleMaster::find($role_id);

        $data['uuid'] = $id;

        $data['record'] = $model;

        return view('hr.roles.update', $data);
    }

    public function getUUID()
    {
        $uuid = Str::uuid();

        $model = RoleViewTemp::where('uuid', $uuid)->first();

        if ($model) {

            self::getUUID();
        }

        return $uuid;

    }
    public function update(Request $request)
    {

        $name = $request->name;

        $id = $request->uuid;

        $validator = Validator::make($request->all(),
            ['name' => 'required|max:250|unique:roles,name']
        );

        if ($validator->fails()) {
            return \Redirect::back()->withErrors($validator->errors()->all());
        }

        $temp = RoleViewTemp::select('id', 'uuid', 'role_id')
            ->where('uuid', $id)
            ->where('is_expired', 0)
            ->first();

        $model = UserRoleMaster::find($temp->role_id);

        $old = new UserRoleMasterStaging;

        $old->name_new = $name;
        $old->name_old = $model->name;

        $old->status_new = $model->status;
        $old->status_old = $model->status;

        $old->is_delete_new = $model->is_delete;
        $old->is_delete_old = $model->is_delete;

        $old->role_id = $model->id;
        $old->updated_by = Auth::user()->id;
        $old->save();

        $model->name = $name;
        $model->save();
        $temp->is_expired = 1;
        $temp->save();
        return \Redirect::Route('hr.roles')->with('success', 'Record Update Successfully');

    }

    public function delete($id)
    {
        $model = UserRoleMaster::find($id);

        $temp = new RoleViewTemp;
        $temp->role_id = $id;
        $temp->view_by = Auth::user()->id;
        $temp->uuid = self::getUUID();
        $temp->save();

        return \Redirect::Route('hr.roles.delete.uuid', $temp->uuid);

    }
    public function deleteWithUuid($uuid)
    {

        $id = $uuid;

        $temp = RoleViewTemp::select('id', 'uuid', 'role_id')
            ->where('uuid', $id)
            ->where('is_expired', 0)
            ->first();

        $model = UserRoleMaster::find($temp->role_id);

        $old = new UserRoleMasterStaging;

        $old->name_new = $model->name;
        $old->name_old = $model->name;

        $old->status_new = $model->status;
        $old->status_old = $model->status;

        $old->is_delete_new = 1;
        $old->is_delete_old = $model->is_delete;

        $old->role_id = $model->id;
        $old->updated_by = Auth::user()->id;
        $old->save();

        $model->is_delete = 1;
        $model->save();
        $temp->is_expired = 1;
        $temp->save();
        return \Redirect::Route('hr.roles')->with('warning', 'Record Removed Successfully');
    }

}
