<?php
namespace App\Controllers\Article;

use App\Controllers\BaseController;
use App\Models\article\DelChgAptModel;

/**
 * 단지코드관리
 * 2025.12.26
 * 작성자 : yangsh
 */
class DelChgApt extends BaseController
{
    private $model;
    public function __construct()
    {
        $this->model = new DelChgAptModel();
    }

    public function lists(): string
    {
        return view("pages/article/delChgView", $this->data);
    }


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

        $data = [
            'hscpNo' => $this->request->getGet('hscpNo') ?: '',
        ];

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


        $datas = $this->model->getAptLists($start, $end, $data);


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

    // 단지코드 변경
    public function chgAptHscp()
    {
        try {

            $rcptNo = $this->request->getPost('rcpt_no');

            if (empty($rcptNo)) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '접수번호 누락'
                ]);
            }

            $data = [
                'rcptNo' => $rcptNo,
                'hscpNo' => $this->request->getPost('hscp_no'),
            ];

            // 기존 단지코드 있는지 체크
            $exits = $this->model->chkExistAptHscp($data);
            if ($exits) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '이미 존재하는 단지코드'
                ]);
            }

            // 단지코드 저장
            $this->model->saveAptHscp($data);


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


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

    // 아파트단지 삭제
    public function deleteAptHscp()
    {
        try {

            $rcptNo = $this->request->getPost('rcpt_no');

            if (empty($rcptNo)) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '접수번호 누락'
                ]);
            }

            $data = [
                'rcptNo' => $rcptNo,
            ];

            // 단지코드 저장
            $this->model->deleteAptHscp($data);


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


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