<?php
namespace App\Controllers\manage;

use App\Controllers\BaseController;
use App\Models\manage\PermitModel;

class Permit extends BaseController
{

    private $permitModel;

    public function __construct()
    {
        $this->permitModel = new PermitModel();
    }

    public function lists(): string
    {
        $usrLevel = $this->permitModel->getUsrLevel();

        $this->data['usrLevel'] = $usrLevel;

        return view("pages/manage/permit/lists", $this->data);
    }


    // 메뉴권한목록조회
    public function getMenuAuthList()
    {
        $usrLevel = $this->request->getGet('usr_level');

        $lists = $this->permitModel->getMenuAuthList($usrLevel);

        if (!empty($lists)) {
            foreach ($lists as $k => $d) {
                $state = [];

                if ($d['state'] === "selected") {
                    $state['selected'] = true;
                    $lists[$k]['state'] = $state;
                } else {
                    $state['selected'] = false;
                    $lists[$k]['state'] = $state;
                }

            }
        }

        return $this->response->setJSON($lists);
    }


    // 메뉴권한정보저장
    public function saveMenuAuth()
    {
        try {
            $usrLevel = $this->request->getPost('usr_level');

            if (empty($usrLevel)) {
                return $this->response->setJSON([
                    'code' => '1',
                    'msg' => '그룹 데이터 누락'
                ]);
            }

            $menuArr = explode(',', $this->request->getPost('mnu_cd'));
            if (empty($menuArr)) {
                return $this->response->setJSON([
                    'code' => '1',
                    'msg' => '메뉴 데이터 누락'
                ]);
            } else {

                // DELETE menu_perms
                $this->permitModel->deleteMenuPermit($usrLevel);

                foreach ($menuArr as $m) {

                    $data = [
                        'mnuId' => $m,
                        'usrLevel' => $usrLevel,
                        'usrSq' => session('usr_sq'),
                    ];

                    // INSERT menu_perms
                    $this->permitModel->saveMenuAuth($data);

                }

            }

            return $this->response->setJSON([
                'code' => '0',
                'msg' => 'success'
            ]);

        } catch (\Exception $e) {
            return $this->response->setJSON([
                'code' => '9',
                'msg' => $e->getMessage(),
            ]);
        }
    }
}