<?php
namespace App\Models\common;

use CodeIgniter\Model;

class CodeModel extends Model
{
    /**
     * 코드목록 읽어오기(Y만)
     */
    public function getCodeList($category)
    {
        $sql = "SELECT category, category_nm, cd, cd_nm FROM codes" .
            " WHERE category = ?" .
            " AND use_yn = 'Y'" .
            " ORDER BY view_odr";
        $data = [$category];
        $query = $this->db->query($sql, $data);

        return $query->getResultArray();
    }


    public function getCodeLists($data): array
    {
        return $this->db->table('codes')
            ->select('category, category_nm, cd, cd_nm')
            ->whereIn('category', $data)
            ->where('use_yn', 'Y')
            ->orderBy('view_odr')
            ->get()
            ->getResultArray();
    }

    public function getCategoryCodeList($category = [], $useYn = '')
    {
        $this->db->select('category, cd, cd_nm, use_yn');
        $this->db->from('codes');
        $this->db->where_in('category', $category);
        if (!empty($useYn)) {
            $this->db->where('use_yn', $useYn);
        }
        $this->db->order_by('category', 'asc');
        $this->db->order_by('view_odr', 'asc');

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

        //echo $this->db->last_query()."<br>";

        //여기 아래부분을 해줘야 배열을 카테고리로 뽑아쓸수있다 위에는 배열에 배열이담김
        $codes = [];
        foreach ($query->getResultArray() as $row) {
            $codes[$row['category']][] = ['cd' => $row['cd'], 'cd_nm' => $row['cd_nm']];
        }
        return $codes;
    }

    /**
     * 코드 상세
     */
    public function getCodeDetail($category, $code)
    {
        $sql = "SELECT category, category_nm, cd, cd_nm FROM codes" .
            " WHERE category = ? and cd = ?";
        $data = [$category, $code];
        $query = $this->db->query($sql, $data);
        $row = $query->getResultArray();

        return $row;
    }
}