<?php

namespace lib\Controllers\Client;

use lib\Services\HistoryService;
use lib\Services\OnetimeService;
use lib\Services\PointService;
use lib\Configs\Pagination;
use lib\Helpers\Client\PointHelper;

class PointController extends ClientController
{
    private ?PointService $_pointService = null;
    private ?OnetimeService $_onetimeService = null;
    private ?HistoryService $_historyService = null;
    public function __construct(array $params = [])
    {
        parent::__construct($params);
        $this->setPath('point');
        $this->helper = new PointHelper();
    } //
    public function getPointService(): PointService
    {
        if ($this->_pointService === null) {
            $this->_pointService = new PointService();
        }
        return $this->_pointService;
    }
    public function getOnetimeService(): OnetimeService
    {
        if ($this->_onetimeService === null) {
            $this->_onetimeService = new OnetimeService();
        }
        return $this->_onetimeService;
    }
    public function getHistoryService(): HistoryService
    {
        if ($this->_historyService === null) {
            $this->_historyService = new HistoryService();
        }
        return $this->_historyService;
    }

    //IdcClientPointList.jsp
    //CLI 접속방법 : php index.php site/client/point/index
    //WEB 접속방법 : http://localhost/site/client/point/index
    public function index()
    {
        //전체 고객객정보
        $this->clients = $this->getClientService()->getEntities();
        //사용자코드가 있으면,
        $client_code = $this->request->get('client_code');
        if ($client_code) {
            $this->getPointService()->getModel()->where('client_code', $client_code);
        }
        [$this->total, $this->entities, $this->pagination, $this->curPage, $this->perPage] = $this->getPointService()->getList(
            $this->request->get('curPage'),
            $this->request->get('perPage')
        );
        $this->client_code = $client_code;
        return $this->render(__FUNCTION__);
    }

    //IdcClientPointInsert.jsp
    //CLI 접속방법 : php index.php site/client/point/insert_form
    //WEB 접속방법 : http://localhost/site/client/point/insert_form
    public function insert_form()
    {
        //전체 고객객정보
        $this->clients = $this->getClientService()->getEntities();
        //사용자코드가 있으면,
        $client_code = $this->request->get('client_code');
        if ($client_code) {
            $this->getPointService()->getModel()->where('client_code', $client_code);
        }
        $this->client_code = $client_code;
        return $this->render(__FUNCTION__);
    }

    //IdcPointBuyMK.jsp -> domain_point_buy.php
    //CLI 접속방법 : php index.php site/client/point/insert_form
    //WEB 접속방법 : http://localhost/site/client/point/insert_form
    public function insert()
    {
        try {
            //Client Code 형식
            $client_code = $this->request->get('client_code');
            if (!$client_code) {
                throw new \Exception("고객을 선택하지 않으셨습니다.");
            }
            $this->getClientService()->getModel()->where('Client_Code', $client_code);
            $client = $this->getClientService()->getEntity();
            if (!$client) {
                throw new \Exception("[$client_code]에 해당하는 고객정보가 존재하지 않습니다.");
            }
            //포인트 형식
            $type = $this->request->get('type');
            if (!$type) {
                throw new \Exception("포인트 형식이 정의되지 않았습니다.");
            }
            //포인트 값
            $amount = intval($this->request->get('amount'));
            if (! $amount || $amount < 1) {
                throw new \Exception("포인트 값이 정의되지 않았거나, 포인트값은 1 이상이어야 합니다.");
            }
            //포인트 작업 내용
            $note = $this->request->get('note');
            // //onetime_case 사용용도
            // $onetime_case = $this->request->get('onetime_case', 'point');
            // //onetime_request_date 사용일
            // $onetime_request_date = $this->request->get('onetime_request_date') ?? date("Y-m-d");
            $formDatas = [
                'client_code' => $client_code,
                'type' => $type,
                'title' => date("Y-m-d") . ", [$amount] 포인트, " . DBMS_CLIENT_POINT_TYPE[$type],
                'amount' => $amount,
                'note' => $note
            ];
            $this->getServiceService()->beginTransaction();
            // //포인트 사용내역 onetime에 등록
            // $this->getOnetimeService()->usePointByService($service, $client, $member, $onetime_case, $point, $note, $onetime_request_date);
            // //포인트 사용내역 history에 등록
            // $this->getHistoryService()->usePointByService($service, $client,  $onetime_case, $point, $note, $onetime_request_date);;
            //포인트 사용내역 point에 등록
            $this->getPointService()->getModel()->insert($formDatas);
            if ($type == 'withdrawal') { //사용자 포인트 출금
                $this->getClientService()->withdrawalPoint($this->client, $amount);
            } else { //사용자 포인트 입금
                $this->getClientService()->depositPoint($this->client, $amount);
            }
            $this->getServiceService()->commit();
            $message_key = 'success';
            $message     = "포인트 : [$amount]" . DBMS_CLIENT_POINT_TYPE[$type] . "이 완료되었습니다";
        } catch (\PDOException $e) {
            $this->getServiceService()->rollback();
            $message_key = 'error';
            $message = "실패:" . $e->getMessage();
        } catch (\Exception $e) {
            $message_key = 'error';
            $message = "실패" . $e->getMessage();
        }
        return $this->redirect->to(DBMS_SITE_URL . "/IdcPointList.cup?client_code=$client_code")->with($message_key, ['message' => $message]);
    }
} //Class
