<?php

namespace App\Controllers\Front\Billing;

use App\Libraries\Adapter\Payment\CookiePayment as PaymentAdapter;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class CardController extends BillingController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_viewDatas['className'] = 'Card';
        $this->_viewPath .= '/' . strtolower($this->_viewDatas['className']);
        $this->_viewDatas['title'] = lang($this->_viewDatas['className'] . '.title');
        $this->_viewDatas['class_icon'] = CLASS_ICONS[strtoupper($this->_viewDatas['className'])];
        helper($this->_viewDatas['className']);
    }

    public function getFields(string $action = ""): array
    {
        switch ($action) {
            case 'update':
                return ["card_quota", "card_number", "card_expiration", "email", "phone"];
                break;
            default:
                return [];
                break;
        }
    }
    protected function getFieldRule(string $field, array $rules, string $action = ""): array
    {
        switch ($field) {
            case "order_uid":
                $rules[$field] = 'required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]';
                break;
            case "card_quota":
                $rules[$field] = 'required|in_list[00,01]';
                break;
            case "card_number":
                $rules[$field] = 'required|regex_match[/^[0-9]{4}[\/-][0-9]{4}[\/-][0-9]{4}[\/-][0-9]{4}/]';
                break;
            case "card_expiration":
                $rules[$field] = 'required|regex_match[/^[0-9]{4}[\/-](0[0-9]|1[0-2])/]';
                break;
            case "email":
                $rules[$field] = 'required|valid_email';
                break;
            case "phone":
                $rules[$field] = 'required|regex_match[/^[0-9]{3}[\/-][0-9]{4}[\/-][0-9]{4}/]';
                break;
            default:
                $rules = parent::getFieldRule($field, $rules, $action);
                break;
        }
        return $rules;
    }
    public function getFieldFilters(): array
    {
        return ['card_quota'];
    }
    public function getFieldBatchFilters(): array
    {
        return parent::getFieldBatchFilters();
    }
    //Field별 Form Option용
    public function getFieldFormOption(string $field): array
    {
        switch ($field) {
            case 'card_quota':
                $options = lang($this->_viewDatas['className'] . '.CARD_QUOTA');
                break;
            default:
                $options = parent::getFieldFormOption($field);
                break;
        }
        if (!is_array($options)) {
            throw new \Exception(__FUNCTION__ . "에서 {$this->_viewDatas['className']}의 Field:{$field}의 FormOptionData가 array가 아닙니다.\n" . var_export($options, true));
        }
        return $options;
    }
    //Field별 Form Datas 처리용
    protected function getFieldFormData(string $field, $entity = null): array
    {
        switch ($field) {
            case 'card_number':
            case 'card_expiration':
                $temps = array();
                foreach ($this->request->getVar($field) as $value) {
                    array_push($temps, $value);
                }
                $this->_viewDatas['fieldDatas'][$field] = implode("-", $temps);
                break;
            default:
                return parent::getFieldFormData($field, $entity);
                break;
        }
        return $this->_viewDatas['fieldDatas'];
    }


    //Update관련
    //카드결제처리
    private function pg_process(): string
    {
        $response = "";
        if (MALLS['card'] == "REAL") {
            //PG사 결제후 정보저장
            $adapter = new PaymentAdapter();
            $adapter->setDatas($this->_viewDatas['fieldDatas']);
            $result = $adapter->execute();
            foreach ($result as $key => $value) {
                $response .= "{$key}:{$value}\n";
            }
        } else {
            foreach ($this->_viewDatas['fieldDatas'] as $key => $value) {
                $response .= "{$key}:{$value}\n";
            }
        }
        return $response;
    }

    //특수한형태의 Field(card_number,card_expiration) 때문에 먼저 데이터를 받아서 변환한후 validation 체크를 하기위해
    protected function update_validate($entity)
    {
        //fieldData 적용
        $this->_viewDatas['fieldDatas'] = array();
        foreach ($this->_viewDatas['fields'] as $field) {
            $this->_viewDatas['fieldDatas'] = $this->getFieldFormData($field, $entity);
        }

        $this->_validation->setRules($this->_viewDatas['fieldRules']);
        if (!$this->_validation->run($this->_viewDatas['fieldDatas'])) {
            throw new \Exception("{$this->_viewDatas['title']}의 검증 오류발생\n" . implode("\n", $this->_validation->getErrors()));
        }
    }
    protected function update_process($entity)
    {
        //카드결제
        $this->_viewDatas['fieldDatas']["response"] = $this->pg_process();
        //Card 결제처리
        $this->_viewDatas['fieldDatas']["type"] = $this->_viewDatas['className'];
        $this->_viewDatas['fieldDatas']["status"] = DEFAULTS['STATUS'];
        return parent::update_process($entity);
    }
}
