<?php
namespace App\Controllers\manage;

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

class Menu extends BaseController
{
    private $menuModel;

    public function __construct()
    {
        $this->menuModel = new MenuModel();
    }

    public function lists(): string
    {
        return view("pages/manage/menu/lists", $this->data);
    }


    // 메뉴목록조회
    public function getMenuList()
    {
        $params = [];


        $total = $this->menuModel->getTotalCount();
        $datas = $this->menuModel->getMenuList($params);

        $lft = 1;

        if (!empty($datas)) {
            foreach ($datas as $k => $v) {

                $menuTp = $v['mnu_tp'];
                $menuCd = $v['mnu_id'];
                $menuPid = $v['mnu_pid'];

                // lft
                $datas[$k]['lft'] = $lft;

                // ROOT vs 나머지 level 계산 (지금처럼 코드 길이 쓰고 싶으면 기존 로직 유지 가능)
                if ($menuPid === 'ROOT') {
                    $datas[$k]['level'] = "0";
                    $datas[$k]['parentLv'] = "";
                    $datas[$k]['expanded'] = true;
                } else {
                    // 예: "M" 제거 후 길이 기반
                    $levelStr = str_replace('M', '', $menuCd);
                    $len = strlen($levelStr);
                    if ($len === 1 || $len === 2)
                        $datas[$k]['level'] = "1";
                    else
                        $datas[$k]['level'] = "2"; // 필요시 더 세분화
                }

                // 아이콘
                switch ($menuTp) {
                    case "A":
                        $datas[$k]['iconCls'] = "ui-icon-play";
                        break;
                    case "P":
                        $datas[$k]['iconCls'] = "ui-icon-document";
                        break;
                    case "D":
                        $datas[$k]['iconCls'] = "ui-icon-folder-open";
                        break;
                }

                if ($menuTp === 'A') {
                    // 액션
                    $datas[$k]['isLeaf'] = true;
                    $datas[$k]['rgt'] = $lft + 1;
                    $lft++;

                } elseif ($menuTp === 'P') {
                    // 화면: 내 자식은 mnu_pid == 내 mnu_id
                    $subCnt = 0;
                    foreach ($datas as $v2) {
                        if ($v2['mnu_pid'] === $menuCd) {
                            $subCnt++;
                        }
                    }

                    $datas[$k]['rgt'] = $lft + ($subCnt * 2) + 1;

                    if ($subCnt === 0) {
                        $datas[$k]['isLeaf'] = true;
                        $lft++;
                    } else {
                        $datas[$k]['isLeaf'] = false;
                    }

                } elseif ($menuTp === 'D') {
                    // 디렉토리: 코드 prefix 로 자식/후손 판단 (자바와 동일)
                    $subCnt = 0;
                    foreach ($datas as $v2) {
                        $subMenuCd = $v2['mnu_id'];
                        if (strpos($subMenuCd, $menuCd) === 0) {
                            $subCnt++;
                        }
                    }

                    $datas[$k]['rgt'] = $lft + ($subCnt * 2) + 1;

                    if ($subCnt === 0) {
                        $datas[$k]['isLeaf'] = true;
                        $lft++;
                    } else {
                        $datas[$k]['isLeaf'] = false;
                    }

                } elseif ($menuTp === 'R') {
                    // 루트
                    $datas[$k]['isLeaf'] = false;
                    $datas[$k]['rgt'] = 1 + ($total * 2) + 1;
                }

                $lft++;
            }
        }


        // $datas = $this->buildTree($datas);

        return $this->response->setJSON(body: [
            'total' => $total,
            'rows' => $datas,
        ]);

    }


    // 메뉴정보저장
    public function saveMenu()
    {
        try {

            $data = [
                'mnu_pid' => $this->request->getPost('mnu_pid'),
                'mnu_id' => $this->request->getPost('mnu_id'),
                'mnu_nm' => $this->request->getPost('mnu_nm'),
                'mnu_url' => $this->request->getPost('mnu_url'),
                'mnu_tp' => $this->request->getPost('mnu_tp'),
                'view_odr' => $this->request->getPost('view_odr'),
                'use_yn' => $this->request->getPost('use_yn'),
                'usr_sq' => session('usr_sq'),
            ];


            // INSERT UPDATE menu
            $this->menuModel->saveMenu($data);

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

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

}