<?php
namespace App\Controllers\manage;

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

class User extends BaseController
{
    private $userModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
    }

    public function user(): string
    {

        $userLevel = $this->userModel->getUserLevel();
        $bonbuList = $this->userModel->getBonbuList();
        $teamList = $this->userModel->getTeamList();
        $deptCode = $this->userModel->getDeptCode();

        $this->data['userLevel'] = $userLevel;
        $this->data['bonbuList'] = $bonbuList;
        $this->data['teamList'] = $teamList;
        $this->data['deptCode'] = $deptCode;

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


    public function getUserList()
    {

        $start = (int) $this->request->getGet('start') ?: 0;
        $end = (int) $this->request->getGet('length') ?: 10;

        $data = [
            'srchLevel' => $this->request->getGet('srchLevel') ?: '',
            'srchBonbu' => $this->request->getGet('srchBonbu') ?: '',
            'srchTeam' => $this->request->getGet('srchTeam') ?: '',
            'useYn' => $this->request->getGet('useYn') ?: '',
            'srchType' => $this->request->getGet('srchType') ?: '',
            'srchTxt' => $this->request->getGet('srchTxt') ?: '',
        ];

        $totalCount = $this->userModel->getTotalCount($data);


        $datas = $this->userModel->getUserList($start, $end, $data);

        return $this->response->setJSON(body: [
            'recordsTotal' => $totalCount,
            'recordsFiltered' => $totalCount,
            'data' => $datas,
        ]);

    }


    // 유저정보저장
    public function saveUser()
    {
        try {

            $type = $this->request->getPost('type');



            if ($type == 'create') {

                $data = [
                    $this->request->getPost('addUserId'), // 아이디                
                    $this->request->getPost('addUserPswd') ?: '', // 비밀번호
                    $this->request->getPost('addUserDept'), // 소속조직
                    $this->request->getPost('addUserNm'), // 이름
                    $this->request->getPost('addUserLevel'), // 등급
                    $this->request->getPost('addUserPosition'), // 직급
                    $this->request->getPost('addUserTel1') ?: '', // 연락처
                    $this->request->getPost('addUserTel2') ?: '', // 연락처2
                    $this->request->getPost('addUserAddr1'), // 주소
                    $this->request->getPost('addUserAddr2'), // 상세주소
                    session('usr_sq'),  // 저장유저
                    $this->request->getPost('addUseYn'), // 사용여부
                    $this->request->getPost('addSmsYn'), // SMS 인증여부

                ];

                // INSERT users
                $this->userModel->insertUser($data);


            } else if ($type == 'update') {

                $addUserPswd = trim($this->request->getPost('addUserPswd') ?? '');
                $usrSq = $this->request->getPost('usr_sq');   // hidden으로 넘어오는 PK라고 가정

                $data = [
                    $this->request->getPost('addUserNm'),       // usr_nm
                    $this->request->getPost('addUserDept'),     // dept_sq
                    $this->request->getPost('addUserLevel'),    // usr_level
                    $this->request->getPost('addUserPosition'), // usr_position
                    $this->request->getPost('addUserTel1') ?: '', // usr_tel1
                    $this->request->getPost('addUserTel2') ?: '', // usr_tel2
                    $this->request->getPost('addUserAddr1'),   // usr_addr1
                    $this->request->getPost('addUserAddr2'),   // usr_addr2
                    session('usr_sq'),                         // update_usr
                    $this->request->getPost('addUseYn'),       // use_yn
                    $this->request->getPost('addSmsYn'),       // sms_auth_yn
                ];

                // 비번/PK 같이 넘김
                $this->userModel->updateUser($data, $addUserPswd, $usrSq);

            }

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

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

    // 유저 삭제
    public function removeuser()
    {
        try {

            $data = [
                session('usr_sq'),
                $this->request->getPost('usr_sq')
            ];


            $this->userModel->removeUser($data);


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

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


    // SMS 인증여부 일괄저장
    public function saveSms()
    {
        try {

            $useYn = $this->request->getPost('useYn') ?: 'Y';

            // UPDATE users
            $this->userModel->updateUserSmsYn($useYn);

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

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

    // 엑셀다운로드
    public function excel()
    {
        try {

            $data = [
                'srchLevel' => $this->request->getGet('srchLevl') ?: '',
                'srchBonbu' => $this->request->getGet('srchBonbu') ?: '',
                'srchTeam' => $this->request->getGet('srchTeam') ?: '',
                'useYn' => $this->request->getGet('useYn') ?: '',
                'srchType' => $this->request->getGet('srchType') ?: '',
                'srchTxt' => $this->request->getGet('srchTxt') ?: '',
                'addSmsYn' => $this->request->getPost('addSmsYn'),
            ];

            $datas = $this->userModel->getExcelUserList($data);

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

        } catch (\Exception $e) {
            $e->getPrevious()->getTraceAsString();
        }
    }
}
