<?php

namespace App\Http\Controllers\Admin;

use App\Models\ProjectRole;
use App\Models\ProjectRoleRight;
use App\Models\Right;
use Illuminate\Http\Request;

class ProjectRoleRightController extends BaseController
{
    protected $model;

    protected $department;

    protected $model_name = '权限管理';

    protected $pre_uri = '/admin/ProjectRoleRight/';

    protected $view_path = 'admin.project-role-rights.';

    protected $redirect_index = '/admin/ProjectRoleRight/index';

    public function __construct()
    {
        parent::__construct();
        $this->model = new ProjectRole();
    }

    public function index()
    {
        $rights = Right::all();
        $project_roles = ProjectRole::all();
        $project_role_rights = ProjectRoleRight::all();
        $items = [];
        foreach($rights as $right) {
            $item = [$right];
            foreach($project_roles as $project_role) {
                $has_right = $project_role_rights->where('right_id', $right->id)->where('project_role_id', $project_role->id)->first() != null;
                array_push($item, ['right_id' => $right->id, 'role_id' => $project_role->id, 'has' => $has_right]);
            }
            array_push($items, $item);
        }
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'index', compact('model', 'model_name','pre_uri', 'items', 'project_roles'));
    }

    public function change(Request $request)
    {
        // 赋予权力
        if($request->input('has') == 2) {
            ProjectRoleRight::updateOrCreate([
                'project_role_id' => $request->input('role_id'),
                'right_id' => $request->input('right_id')
            ]);
        } else {
            // 取消权利
            ProjectRoleRight::where([
                ['project_role_id', $request->input('role_id')],
                ['right_id', $request->input('right_id')]
            ])->delete();
        }
        return response()->json(['status' => 'success', 'info' => '操作成功']);
    }
}
