<?php
namespace App\Models\manage;

use CodeIgniter\Model;

class DeptModel extends Model
{

    public function getTotalCount($data)
    {
        $params = [];

        $sql = "SELECT
                    COUNT(*) AS cnt
                FROM
                    departments AS a	
                WHERE 1=1 ";

        if (!empty($data["srchDepth"])) {
            $sql .= "AND a.depth = ?";
            array_push($params, $data["srchDepth"]);
        }

        if (!empty($data["srcDeptNm"])) {
            $sql .= "AND a.dept_nm LIKE CONCAT('%', ?, '%')";
            array_push($params, $data["srcDeptNm"]);
        }

        if (!empty($data["srcDeptHead"])) {
            $sql .= "AND a.dept_head IN (select usr_sq from users where usr_nm LIKE CONCAT('%', ?, '%'))";
            array_push($params, $data["srcDeptHead"]);
        }

        if (!empty($data["useYn"])) {
            $sql .= "AND a.use_yn = ?";
            array_push($params, $data["useYn"]);
        }

        $query = $this->db->query($sql, $params ?: []);

        return $query->getRow()->cnt;
    }

    public function getDeptList($start, $end, $data)
    {
        $params = [];

        $sql = "SELECT
                    dept_sq
     		        , (select dept_nm from departments where dept_sq = a.pdept_sq) as pdept_nm
     		        , pdept_sq
		 			, dept_nm
					, dept_desc
					, (select usr_nm from users where usr_sq = a.dept_head) as dept_head_nm
					, dept_head
					, case when a.use_yn = 'Y' then '예' when a.use_yn = 'N' then '아니요' end as use_yn_nm
					, use_yn		
					, case when a.depth = 0 then '컨펌스' when a.depth = 1 then '본부' when a.depth = 2 then '팀' end as depth_nm
					, depth
					, insert_tm
					, (select usr_nm from users where usr_sq = a.insert_usr) insert_usr
					, update_tm
					, (select usr_nm from users where usr_sq = a.update_usr) update_usr
					, lft
					, rgt
                FROM
                    departments AS a	
                WHERE 
                    1=1 ";

        if (!empty($data["srchDepth"])) {
            $sql .= "AND a.depth = ? ";
            array_push($params, $data["srchDepth"]);
        }

        if (!empty($data["srcDeptNm"])) {
            $sql .= "AND a.dept_nm LIKE CONCAT('%', ?, '%') ";
            array_push($params, $data["srcDeptNm"]);
        }

        if (!empty($data["srcDeptHead"])) {
            $sql .= "AND a.dept_head IN (select usr_sq from users where usr_nm LIKE CONCAT('%', ?, '%'))";
            array_push($params, $data["srcDeptHead"]);
        }

        if (!empty($data["useYn"])) {
            $sql .= "AND a.use_yn = ? ";
            array_push($params, $data["useYn"]);
        }

        $sql .= "ORDER BY a.insert_tm DESC    
                LIMIT ?, ?
                ";



        $params[] = (int) $start;
        $params[] = (int) $end;

        $query = $this->db->query($sql, $params);

        return $query->getResultArray();

    }


    public function getUserCount()
    {
        $sql = "SELECT COUNT(*) AS cnt FROM users WHERE use_yn = 'Y' ";

        $query = $this->db->query($sql);

        return $query->getRow()->cnt;
    }

    public function getUserList($start, $end)
    {
        $sql = "SELECT usr_sq, usr_id, usr_nm FROM users WHERE use_yn = 'Y' ORDER BY usr_sq DESC LIMIT ?, ?";


        $params[] = (int) $start;
        $params[] = (int) $end;

        $query = $this->db->query($sql, $params);

        return $query->getResultArray();
    }

    // 상위조직 조회
    public function getPdept()
    {
        $sql = "SELECT dept_sq, dept_nm FROM departments" .
            " WHERE depth = 1" .
            " AND use_yn = 'Y'";

        $query = $this->db->query($sql);

        return $query->getResultArray();
    }

    // 조직관리 INSERT
    public function insertDept($data)
    {

        $sql = "select ifnull(rgt,1) lft from departments where dept_sq = ?";
        $query = $this->db->query($sql, [$data[0]]);
        $lft = $query->getRowArray();

        $data[] = $lft["lft"];
        $data[] = $lft["lft"];

        $sql = "INSERT INTO departments
            (pdept_sq, dept_nm, dept_desc, dept_head ,use_yn, depth, insert_tm, insert_usr, update_tm, update_usr, lft, rgt)" .
            "VALUES (?, ?, ?, ?, ?, ?, now(), ?, now(), ?, ?, ?)";

        $this->db->query($sql, $data);

        if ($this->db->transStatus() === false) {
            return [
                'success' => false,
                'msg' => '저장실패',
            ];
        }

        // 성공
        return [
            'success' => true,
        ];
    }

    // 조직관리 UPDATE
    public function updateDept($data)
    {
        $sql = "UPDATE departments SET" .
            "    pdept_sq = CASE depth WHEN '0' THEN pdept_sq ELSE ? END," .
            "    dept_nm = ?," .
            "    dept_desc = ?," .
            "    dept_head = ?," .
            "    use_yn = ?," .
            "    depth = CASE depth WHEN '0' THEN depth ELSE ? END," .
            "    update_tm = now()," .
            "    update_usr = ?" .
            " WHERE dept_sq = ?";

        $this->db->query($sql, $data);

        if ($this->db->transStatus() === false) {
            return [
                'success' => false,
                'msg' => '저장실패',
            ];
        }

        // 성공
        return [
            'success' => true,
        ];
    }
}