<?php
namespace App\Controllers\manage;

use App\Controllers\BaseController;
use App\Models\manage\SmsModel;

class Sms extends BaseController
{
    private $smsModel;
    public function __construct()
    {
        $this->smsModel = new SmsModel();
    }

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


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

        $data = [
            'start_dt' => $this->request->getGet('start_dt'),
            'end_dt' => $this->request->getGet('end_dt'),
            'srchType' => $this->request->getGet('srchType'),
            'srchTxt' => $this->request->getGet('srchTxt'),
        ];

        $totalCount = $this->smsModel->getTotalCount($data);
        $datas = $this->smsModel->getSmsList($start, $end, $data);

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

    // 엑셀다운로드 - 내역
    public function excel()
    {
        $data = [
            'start_dt' => $this->request->getGet('start_dt'),
            'end_dt' => $this->request->getGet('end_dt'),
            'srchType' => $this->request->getGet('srchType'),
            'srchTxt' => $this->request->getGet('srchTxt'),
        ];

        $datas = $this->smsModel->getExcelList($data);

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



    // sms 발송 - 화면
    public function smsSendView(): string
    {
        return view("pages/manage/sms/smsSendView", $this->data);
    }


    // sms 발송
    public function sendSms()
    {
        try {

            $msgType = $this->request->getPost('msg_type');
            $body = $this->request->getPost('msg_body');
            $len = strlen(iconv('UTF-8', 'EUCKR', $body));

            $data = [
                'dest_phone' => $this->request->getPost('dest_phone'),
                'dest_name' => $this->request->getPost('dest_name'),
                'send_phone' => $this->request->getPost('send_phone'),
                'send_name' => $this->request->getPost('send_name'),
                'subject' => '문자발송',
                'msg_body' => $this->request->getPost('msg_body'),
                'msg_type' => $len > 80 && $msgType == 0 ? "5" : $msgType,
                'ect2' => 'S12',
                'etc3' => $this->request->getPost('memo'),
            ];

            $this->smsModel->sendSms($data);


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

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