<?php
namespace App\Models\manage;

use CodeIgniter\Model;

class AreasModel extends Model
{

    // 지역 목록 조회
    public function getAreaList($sido = '', $gugun = '')
    {

        if (!empty($gugun)) {
            $gugun = substr($gugun, '0', '5');

            $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm" .
                " FROM region_codes a" .
                " LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,5),'00000')" .
                " WHERE a.region_cd LIKE concat(?, '%')" .
                " AND a.region_cd NOT LIKE '%00000'" .
                " AND a.region_cd LIKE '%00'" .
                " AND a.use_yn = 'Y'" .
                " ORDER BY a.region_nm ASC";

            $query = $this->db->query($sql, [$gugun]);

        } else if (!empty($sido)) {
            $chk_sido = substr($sido, '0', '2');

            if ($chk_sido === '36') {
                $sido = substr($sido, '0', '4');
                $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm " .
                    "FROM region_codes a " .
                    "LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,4),'000000') " .
                    "WHERE a.region_cd LIKE concat(?, '%') " .
                    "AND a.region_cd NOT LIKE '%000000' " .
                    "AND a.region_cd LIKE '%00' " .
                    "AND a.use_yn = 'Y' " .
                    "AND EXISTS (SELECT 'x' FROM region_codes c WHERE c.region_cd LIKE CONCAT(SUBSTR(a.region_cd,1,5),'%') AND c.region_cd > CONCAT(SUBSTR(a.region_cd,1,5),'00000')) " .
                    "ORDER BY a.region_nm ASC";
            } else {
                $sido = substr($sido, '0', '2');
                $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm" .
                    " FROM region_codes a" .
                    " LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,2),'00000000')" .
                    " WHERE a.region_cd LIKE concat(?, '%')" .
                    " AND a.region_cd NOT LIKE '%00000000'" .
                    " AND a.region_cd LIKE '%00000'" .
                    " AND a.use_yn = 'Y'" .
                    " AND EXISTS (SELECT 'x' FROM region_codes c WHERE c.region_cd LIKE CONCAT(SUBSTR(a.region_cd,1,5),'%') AND c.region_cd > CONCAT(SUBSTR(a.region_cd,1,5),'00000'))" .
                    " ORDER BY a.region_nm ASC";
            }

            $query = $this->db->query($sql, [$sido]);
        } else {
            $sql = "SELECT a.region_cd, a.region_nm " .
                "FROM region_codes a " .
                "WHERE (a.region_cd LIKE '%00000000' " .
                "AND a.use_yn = 'Y') " .
                "OR region_cd = 3611000000;";

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


        return $query->getResultArray();


    }

    // 소속본부조회
    public function getBonbuList()
    {
        $sql = "SELECT dept_sq, pdept_sq, dept_nm, dept_desc, dept_head, use_yn, depth, insert_tm, insert_usr, update_tm, update_usr, lft, rgt" .
            "  FROM departments" .
            " WHERE depth = 1" .
            "   AND use_yn = 'Y'" .
            " ORDER BY lft";

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


        return $query->getResultArray();
    }

    // 소속팀 조회
    public function getTeamList()
    {
        $sql = "SELECT dept_sq, pdept_sq, dept_nm" .
            "  FROM departments" .
            " WHERE depth = 2" .
            "   AND use_yn = 'Y'" .
            " ORDER BY dept_nm";

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


        return $query->getResultArray();
    }

    // 유저 조회
    public function getUserList()
    {
        $sql = "SELECT 
                    a.usr_sq, a.usr_id, a.usr_nm, a.dept_sq
                FROM users a
                WHERE 
                        a.usr_level IN ('3','4','40','5','50','6','60','61','62','7','8','70')
                        AND a.use_yn = 'Y'
                        AND EXISTS (
                        SELECT 'x' FROM departments a1 INNER JOIN departments a2 ON a2.lft BETWEEN a1.lft AND a1.rgt AND a2.use_yn = 'Y' 
                        WHERE 1=1 AND a2.dept_sq = a.dept_sq AND a1.use_yn = 'Y'
                )
                ORDER BY a.usr_level DESC, a.usr_nm ASC ";

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

        return $query->getResultArray();
    }

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

        $sql = "SELECT
                    COUNT(*) AS cnt
                FROM
                    region_codes AS a	
                WHERE
                    a.use_yn = 'Y'		
                    AND a.region_cd NOT LIKE '%00000000'
                    AND a.region_cd NOT LIKE '%00000' ";

        if (!empty($data['region'])) {
            $sql .= "AND a.region_cd LIKE CONCAT({$data['region']} ,'%') ";
        }

        if (!empty($data['srcUserteam'])) {
            $sql .= "AND a.dept_sq = {$data['srcUserteam']} ";
        } else if (!empty($data['srcUserbonbu'])) {
            $sql1 = "SELECT lft, rgt FROM departments WHERE dept_sq = {$data['srcUserbonbu']}";
            $res = $this->db->query($sql1);
            $lft = $res->getRowArray();

            $sql2 = "SELECT dept_sq FROM departments WHERE lft >= {$lft['lft']} AND rgt <= {$lft['rgt']}";
            $res2 = $this->db->query($sql2);
            $list = $res2->getResultArray();

            $deptArr = [];
            foreach ($list as $d) {
                array_push($deptArr, $d['dept_sq']);
            }

            if (!empty($deptArr)) {
                $in = implode(",", array_map("intval", $deptArr));
                $sql .= " AND a.dept_sq IN ($in) ";
            }
        }

        if (!empty($data['positionYn'])) {
            if ($data['positionYn'] === "Y") {
                $sql .= "AND a.dept_sq IS NOT NULL OR a.dept_sq != 0 ";
                $sql .= "AND a.usr_sq IS NOT NULL OR a.usr_sq != 0 ";
            } else {
                $sql .= "AND a.dept_sq IS NULL OR a.dept_sq = 0 ";
                $sql .= "AND a.usr_sq IS NULL OR a.usr_sq = 0 ";
            }
        }


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

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


    public function getSvcArea($start, $end, $data)
    {

        $sql = "SELECT
                    region_cd, region_nm, dept_sq, (SELECT dept_nm FROM departments where dept_sq = a.dept_sq) dept_nm, (SELECT pdept_sq FROM departments where dept_sq = a.dept_sq) pdept_sq, usr_sq
                FROM
                    region_codes AS a	
                WHERE
                    a.use_yn = 'Y'		
                    AND a.region_cd NOT LIKE '%00000000'
                    AND a.region_cd NOT LIKE '%00000' ";

        if (!empty($data['region'])) {
            $sql .= "AND a.region_cd LIKE CONCAT({$data['region']} ,'%') ";
        }

        if (!empty($data['srcUserteam'])) {
            $sql .= "AND a.dept_sq = {$data['srcUserteam']} ";
        } else if (!empty($data['srcUserbonbu'])) {
            $sql1 = "SELECT lft, rgt FROM departments WHERE dept_sq = {$data['srcUserbonbu']}";
            $res = $this->db->query($sql1);
            $lft = $res->getRowArray();

            $sql2 = "SELECT dept_sq FROM departments WHERE lft >= {$lft['lft']} AND rgt <= {$lft['rgt']}";
            $res2 = $this->db->query($sql2);
            $list = $res2->getResultArray();

            $deptArr = [];
            foreach ($list as $d) {
                array_push($deptArr, $d['dept_sq']);
            }

            if (!empty($deptArr)) {
                $in = implode(",", array_map("intval", $deptArr));
                $sql .= " AND a.dept_sq IN ($in) ";
            }
        }

        if (!empty($data['positionYn'])) {
            if ($data['positionYn'] === "Y") {
                $sql .= "AND a.dept_sq IS NOT NULL OR a.dept_sq != 0 ";
                $sql .= "AND a.usr_sq IS NOT NULL OR a.usr_sq != 0 ";
            } else {
                $sql .= "AND a.dept_sq IS NULL OR a.dept_sq = 0 ";
                $sql .= "AND a.usr_sq IS NULL OR a.usr_sq = 0 ";
            }
        }

        $sql .= "LIMIT {$start}, {$end}";

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

        return $query->getResultArray();
    }


    // 이력관리정보저장
    public function saveRegion($regionCd, $team, $user)
    {

        $sql = "UPDATE region_codes SET ";
        $sql .= "dept_sq = {$team}, ";
        $sql .= "usr_sq = {$user} ";
        $sql .= "WHERE region_cd = '{$regionCd}'";

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

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

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

}