<?php

namespace Wave\Http\Controllers\CMS;

use App\Http\Controllers\Controller;
use App\Models\PermissionGroup;
use App\Models\PermissionRole;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Yajra\DataTables\Facades\DataTables;

class SecurityController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application cms dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $roles = Role::whereIn('id', [
                Role::IT_PERSONNEL_ROLE,
                Role::NUMSTATION_MANAGER_ROLE,
                Role::NUMSTATION_STAFF_ROLE,
            ])->get();
        $permissionGroups = PermissionGroup::where('platform', 'admin')->get();
        return view('theme::cms.securities.index', [
            'roles' => $roles,
            'permissionGroups' => $permissionGroups,
        ]);
    }

    public function groupListTable()
    {
        $roles = Role::query()
            ->select('*')
            ->whereIn('id', [
                Role::IT_PERSONNEL_ROLE,
                Role::NUMSTATION_MANAGER_ROLE,
                Role::NUMSTATION_STAFF_ROLE,
            ]);

        return Datatables::of($roles)
            ->escapeColumns(['id'])
            ->addColumn('status', function ($role) {
                $status = $role->status;
                if ($status == 'active') {
                    $status = '<span class="success item-list-note">' . ucwords($status) . '</span>';
                }
                else if ($status == 'inactive') {
                    $status = '<span class="failed item-list-note">' . ucwords($status) . '</span>';
                }

                return $status;
            })
            ->addColumn('actions', function ($role) {
                if (auth()->user()->userRole->hasAccess('manage-security-group')) {
                    $suspendAction = '<a class="failed item-list-note suspend-role" href="#" data-action="' . route('cms.securities.suspend', $role->id) . '">' . __("Suspend") . '</a>';
                    $activateAction = '<a class="primary-text activate-role" href="#" data-action="' . route('cms.securities.activate', $role->id) . '">' . __("Activate") . '</a>';
                    $viewAction = '<a href="#" class="primary-text view-edit-action" data-type="view">' . __("View") . '</a>';
                    $editAction = '<a href="#" class="primary-text view-edit-action" data-type="edit">' . __("Edit") . '</a>';
                    $actions = $viewAction . '<span class="long-pipe">|</span>' . $editAction . '<span class="long-pipe">|</span>' . ($role->status == 'active' ? $suspendAction : $activateAction);
                    return $actions;
                }
                return '';
            })
            ->make(true);
    }

    public function suspend(Role $role)
    {
        $role->status = 'inactive';
        $role->save();

        $role->users()->update([
            'status' => 'inactive',
        ]);

        return response()->json([
            'success' => true,
            'message' => __("Role has successfully suspended!"),
        ]);
    }

    public function activate(Role $role)
    {
        $role->status = 'active';
        $role->save();

        return response()->json([
            'success' => true,
            'message' => __("Role has successfully activated!"),
        ]);
    }

    public function updateRolePermission(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'role_permissions' => 'required|array',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        $permissionsGroup = $request->role_permissions ? collect($request->role_permissions) : collect();
        $permissionsGroup = $permissionsGroup->map(function ($item) {
            $permissionArr = explode('-', $item);
            return collect([
                'role_id' => $permissionArr[0],
                'permission_id' => $permissionArr[1],
            ]);
        })->groupBy(static function ($item) {
            return $item['role_id'];
        })->map(function ($permission) {
            return $permission->flatMap(static function ($item) use ($permission) {
                return [
                    'role_id' => $item['role_id'],
                    'role_permissions' => $permission->toArray(),
                ];
            });
        });
        
        foreach ($permissionsGroup as $permission) {
            $rolePermissions = [];
            $role = Role::find($permission['role_id']);
            if ($role) {
                $role->rolePermissions()->delete();

                foreach ($permission['role_permissions'] as $rolePermission) {
                    $rolePermissions[] = new PermissionRole($rolePermission);
                }

                $role->rolePermissions()->saveMany($rolePermissions);
            }
        }

        return response()->json([
            'success' => true,
            'message' => __("Role permissions has successfully updated!"),
        ]);
    }
}
