<?php
namespace App\Models\board;

use CodeIgniter\Model;
class NoticeModel extends Model
{

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

        $params = [];
        if (!empty($data['srchTxt'])) {

            $keyword = '%' . $data['srchTxt'] . '%';

            switch ($data['srchType']) {
                case '1': // 제목
                    $sql .= " AND a.subject LIKE ? ";
                    $params[] = $keyword;
                    break;

                case '2': // 작성자
                    $sql .= " AND a.insert_nm LIKE ? ";
                    $params[] = $keyword;
                    break;

                default: // 제목 + 작성자
                    $sql .= " AND ( a.subject LIKE ? OR a.insert_nm LIKE ? ) ";
                    $params[] = $keyword;
                    $params[] = $keyword;
                    break;
            }
        }

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

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

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


        $sql = "SELECT 
                SQL_CALC_FOUND_ROWS
                a.bbs_sq, a.`subject`, a.depth, a.hit, a.update_usr, a.insert_nm, a.insert_tm, a.update_nm, a.update_tm
            FROM bbs_main_notice AS a
            WHERE
                a.use_yn = 'Y' ";

        if (!empty($data['srchTxt'])) {

            $keyword = '%' . $data['srchTxt'] . '%';

            switch ($data['srchType']) {
                case '1': // 제목
                    $sql .= " AND a.subject LIKE ? ";
                    $params[] = $keyword;
                    break;

                case '2': // 작성자
                    $sql .= " AND a.insert_nm LIKE ? ";
                    $params[] = $keyword;
                    break;

                default: // 제목 + 작성자
                    $sql .= " AND ( a.subject LIKE ? OR a.insert_nm LIKE ? ) ";
                    $params[] = $keyword;
                    $params[] = $keyword;
                    break;
            }
        }

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

        $params[] = (int) $start; // offset
        $params[] = (int) $end;   // limit

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

        return $query->getResultArray();
    }

    public function getNoticeData($id)
    {

        $sql = "UPDATE bbs_main_notice SET hit = hit +1 WHERE bbs_sq = ? AND use_yn = 'Y'";
        $res = $this->db->query($sql, [$id]);

        $sql = "SELECT 
                    SQL_CALC_FOUND_ROWS
                    a.bbs_sq, a.`subject`, a.content, a.depth, a.hit, a.update_usr, a.insert_nm, a.insert_tm, a.update_nm, a.update_tm
                FROM bbs_main_notice AS a
                WHERE
                    a.use_yn = 'Y'
                    AND a.bbs_sq = ?
                ";

        $query = $this->db->query($sql, [$id]);
        $notice = $query->getRowArray();

        $sql = "SELECT bbs_sq, file_sq, file_name, file_path, file_ext, file_size, img_yn, img_height, img_width, orig_name, cloud_upload_yn FROM bbs_file_notice WHERE bbs_sq = ?" .
            " and use_yn = 'Y'";
        $query = $this->db->query($sql, [$id]);
        $files = $query->getRowArray();

        $sql = "SELECT reply_sq, lft, rgt, content, update_nm, update_tm FROM bbs_reply_notice WHERE bbs_sq = ?" .
            " AND use_yn = 'Y' ORDER BY rgt DESC";
        $query = $this->db->query($sql, [$id]);
        $replys = $query->getResultArray();

        return [
            'notice' => $notice,
            'files' => $files,
            'reply' => $replys,
        ];
    }


    public function getFile($fileSq)
    {
        $sql = "SELECT file_sq, bbs_sq, file_path, file_name, orig_name FROM bbs_file_notice WHERE file_sq = ?";

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

        return $query->getRowArray();
    }

    public function write($data)
    {
        $this->db->transStart();

        $sql = "SELECT lft+1 num FROM bbs_main_notice ORDER BY bbs_sq DESC LIMIT 1";
        $query = $this->db->query($sql);
        $row = $query->getRowArray();
        $num = $row['num'];

        $sql = "INSERT INTO bbs_main_notice"
            . "(bbs_psq, lft, rgt, use_yn, hit, subject, content, insert_usr, insert_nm, insert_tm, depth)"
            . "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)";

        $query = $this->db->query($sql, [0, $num, ($num + 1), 'Y', 0, $data['subject'], $data['content'], $data['insert_usr'], $data['insert_nm'], 0]);

        // 방금 insert된 PK
        $bbs_sq = $this->db->insertID();

        // 2) 첨부파일 정보가 있으면 파일 테이블 INSERT
        if (!empty($data['file'])) {

            $f = $data['file'];

            $sql = "INSERT INTO bbs_file_notice
                (bbs_sq, file_name, file_path, file_ext, file_size, img_yn, img_height, img_width, orig_name, cloud_upload_yn)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

            $this->db->query($sql, [
                $bbs_sq,
                $f['new_name'] ?? '',
                $f['file_path'] ?? '',
                $f['ext'] ?? '',
                $f['size'] ?? 0,
                $f['img_yn'] ?? 'N',
                $f['img_height'] ?? null,
                $f['img_width'] ?? null,
                $f['orig_name'] ?? '',
                'Y'
            ]);
        }

        // 트랜잭션 끝
        $this->db->transComplete();

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

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


    public function modify($data)
    {

        $sql = "UPDATE bbs_main_notice SET
                `subject` = ?, content = ?, update_usr = ?, update_nm = ?, update_tm = NOW()
                WHERE bbs_sq = ?";

        $this->db->query($sql, [$data['subject'], $data['content'], $data['update_usr'], $data['update_nm'], $data['bbs_sq']]);

        if (!empty($data['file'])) {

            $f = $data['file'];

            if (empty($f['file_sq'])) {
                $sql = "INSERT INTO bbs_file_notice
                (bbs_sq, file_name, file_path, file_ext, file_size, img_yn, img_height, img_width, orig_name, cloud_upload_yn)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

                $this->db->query($sql, [
                    $data['bbs_sq'],
                    $f['new_name'] ?? '',
                    $f['file_path'] ?? '',
                    $f['ext'] ?? '',
                    $f['size'] ?? 0,
                    $f['img_yn'] ?? 'N',
                    $f['img_height'] ?? null,
                    $f['img_width'] ?? null,
                    $f['orig_name'] ?? '',
                    'Y'
                ]);
            } else {
                $sql = "UPDATE bbs_file_notice SET
                    file_name = ?, file_path = ?, file_ext = ?, file_size = ?, img_yn = ?, img_height = ?, img_width = ?, orig_name = ?
                    WHERE file_sq = ?
                ";

                $this->db->query($sql, [
                    $f['new_name'] ?? '',
                    $f['file_path'] ?? '',
                    $f['ext'] ?? '',
                    $f['size'] ?? 0,
                    $f['img_yn'] ?? 'N',
                    $f['img_height'] ?? null,
                    $f['img_width'] ?? null,
                    $f['orig_name'] ?? '',
                    $f['file_sq'],
                ]);

            }

        }

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

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


    public function remove($data)
    {
        $sql = "UPDATE bbs_main_notice SET 
                use_yn = 'N', update_usr = ?, update_nm = ?, update_tm = NOW()
                WHERE bbs_sq = ?";

        $this->db->query($sql, [$data['update_usr'], $data['update_nm'], $data['bbs_sq']]);

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

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


}