<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Enums\UtilEnum;
use App\Http\Controllers\Helper\GlobalController;
use App\Models\BaseModel;
use App\Models\Role;
use App\Models\RoleHasPermission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;

class RoleController extends Controller
{

    protected $roleModel;
    protected $roleHasPermission;
    protected $baseLabId;
    protected $labs;

    public function __construct(RoleHasPermission $roleHasPermission, Role $roleModel){
        $this->roleModel = $roleModel;
        $this->roleHasPermission = $roleHasPermission;
        $this->baseLabId = Session::get('base_lab_id');
        $this->base = Session::get('base_lab');
    }

    public function index(Request $request){
        if(!GlobalController::user_can(Auth::user()->role_id, ['view_user_role'])) return redirect(url('my-profile'));
        $recordStatusCondition = Auth::id()==1 ? [RecordStatusEnum::DELETE, RecordStatusEnum::ACTIVE] : [RecordStatusEnum::ACTIVE];
        $roles = $this->roleModel::with('lab')->whereIn(BaseModel::RECORD_STATUS_FIELD, $recordStatusCondition)
            ->where('lab_id', $this->baseLabId)
            ->whereNotIn('id', [UtilEnum::ADMINISTRATOR_ROLE])
            ->when(!empty($request->kword), function ($roles) use($request){
                $roles->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->kword)."%'");
            })->orderBy(BaseModel::CREATED_AT,'desc')->paginate(config('labis.pagination.perpage', 10));
        return view('role', ['roles' => $roles]);
    }

    public function save(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['create_user_role'])) return false;
            $validator = \Validator::make($request->all(), ['name_en' => 'required']);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('system_role.create_fail'), 'errors'=>$validator->errors()->all()]);
                $new = $this->roleModel::query()->create(['name_en' => $request->name_en, 'lab_id' => $this->baseLabId]);
            return response()->json(['success' => true, 'message' => __('system_role.create_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('system_role.create_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function update(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['update_user_role'])) return false;
            $validator = \Validator::make($request->all(), ['name_en' => 'required']);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('system_role.update_fail'), 'errors'=>$validator->errors()->all()]);
            $this->roleModel::query()->where('id', $request->uid)->update(array('name_en' => $request->name_en));
            return response()->json(['success' => true, 'message' => __('system_role.update_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('system_role.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function get(Request $request){
        try{
            $role = $this->roleModel::query()->find($request->uid);
            return response()->json(['success' => true, 'message' => __('system_role.get_success'), 'data' => $role]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('system_role.get_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function delete(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['delete_user_role'])) return false;
            $this->roleModel::query()->where('id', $request->uid)->update(array(BaseModel::RECORD_STATUS_FIELD=> RecordStatusEnum::DELETE));
            return response()->json(['success' => true, 'message' => __('system_role.delete_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('system_role.delete_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function restore(Request $request){
        try{
            $this->roleModel::query()->where('id', $request->uid)->update(array(BaseModel::RECORD_STATUS_FIELD=> RecordStatusEnum::ACTIVE));
            return response()->json(['success' => true, 'message' => __('system_role.restore_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('system_role.restore_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function storeRolePermission(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['assign_permission'])) return false;
            if(isset($request->permission_id)){
                foreach ($request->permission_id as  $module_id){
                    $this->roleHasPermission::query()->updateOrCreate([
                        'role_id' => $request->uid,
                        'permission_id' => $module_id,
                    ],[
                        'role_id' => $request->uid,
                        'permission_id' => $module_id
                    ]);
                }
                $this->roleHasPermission::query()->where('role_id', $request->uid)
                    ->whereNotIn('permission_id', $request->permission_id)
                    ->delete();
            }
            else{
                $this->roleHasPermission::query()->where('role_id', $request->uid)->delete();
            }
            return redirect()->back();
        }
        catch (\Exception $e){
            return redirect()->back();
        }

    }

    function viewPermissionByRoleId($roleId){
        try {
            if(!GlobalController::user_can(Auth::user()->role_id, ['assign_permission','create_user_role','update_user_role'])) return false;
            $items = DB::select('SELECT
                pg.id,
                pg.weight,
                ' . (App::getLocale() == 'en' ? 'pg.name_en' : 'pg.name_kh') . ' as permission_group,
                pg.`parent_id`,
                sp.id AS permission_id,
                ' . (App::getLocale() == 'en' ? 'sp.name_en' : 'sp.name_kh') . ' as permission_name,
                IF(prm.permission_id IS NULL, 0, 1) AS is_can
                FROM `sys_permission_groups` pg
                INNER JOIN `sys_permissions` sp
                ON sp.`permission_group_id` = pg.`id`
                LEFT JOIN(
                    SELECT
                    *
                    FROM `sys_role_has_permissions`
                    WHERE role_id = ' . $roleId . '
                ) prm
                ON prm.permission_id = sp.`id`
                where sp.record_status_id =1
                and pg.record_status_id=1
                ');

            $data = $this->arrayToTree($items); // $this->permissionGroup_::with(['subGroup.permission_','permission_'])->get();
            $arr_permission = array();
            foreach ($data as $item) {
                $arr_permission[$item->weight]['name'] = $item->permission_group;
                $arr = array(
                    'id' => $item->permission_id,
                    'name' => $item->permission_name,
                    'is_can' => $item->is_can
                );
                $arr_child = array();
                if (@$item->children) {
                    foreach ($item->children as $v) {
                        $arr_child[$v->weight]['name'] = $v->permission_group;
                        $arrc = array(
                            'id' => $v->permission_id,
                            'name' => $v->permission_name,
                            'is_can' => $v->is_can
                        );
                        $arr_child[$v->weight]['permissions'][] = $arrc;
                    }
                }
                $arr_permission[$item->weight]['permissions'][] = array_merge($arr, $arr_child);
            }
            return response()->json(['success' => true, 'message' => __('system_role.get_permission_success'), 'data' => $arr_permission]);
        }   catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('system_role.get_permission_fail'), 'errors' => $e->getMessage()]);
        }
    }

    function arrayToTree(array $items, $parentId = 0) {
        $tree = [];

        foreach ($items as $item) {
            if ($item->parent_id == $parentId) {
                $children = $this->arrayToTree($items, $item->id);
                if ($children) {
                    $item->children = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }

}
