<?php

namespace App\Controllers\Front\Order;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class CartController extends OrderController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_viewDatas['className'] = 'Cart';
        $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 'insert':
                return  ["product_uid", "quantity", "price", 'paymentday'];
                break;
            default:
                return [];
                break;
        }
    }
    protected function getFieldRule(string $field, array $rules, string $action = ""): array
    {
        switch ($field) {
            case 'product_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 'quantity':
            case 'price':
                $rules[$field] = "required|numeric";
                break;
            case 'paymentday':
                $rules[$field] = "if_exist|numeric";
                break;
            default:
                $rules = parent::getFieldRule($field, $rules, $action);
                break;
        }
        return $rules;
    }
    public function getFieldFilters(): array
    {
        return [];
    }
    public function getFieldBatchFilters(): array
    {
        return parent::getFieldBatchFilters();
    }

    //insert관련
    public function insert()
    {
        $msg = "";
        try {
            $this->_viewDatas = $this->init(__FUNCTION__);
            //장바구니정보 검증
            $this->insert_validate();
            //상품정보가져오기
            $product = $this->getProductModel()->getEntity([$this->getProductModel()->getPrimaryKey() => $this->_viewDatas['fieldDatas']['product_uid']]);
            //상품갯수확인
            if (!$this->_viewDatas['fieldDatas']['quantity']) {
                throw new \Exception("상품갯수가 지정되지 않았습니다.");
            }
            //구매금액확인
            if (!$this->_viewDatas['fieldDatas']['price']) {
                throw new \Exception("구매금액이 지정되지 않았습니다.");
            }
            //결제방식이 월이용권이면 결제일 확인
            $paymentDay = null;
            $type = $product->type;
            if ($type == 'rental') {
                $paymentDay = $this->request->getVar('paymentday') ?: throw new \Exception("월이용권 상품의 경우는 매월 결제일을 지정해주셔야합니다.");
            }
            //재고수 비교
            if ($product->stock < $this->_viewDatas['fieldDatas']['quantity']) {
                throw new \Exception("구매수량이 너무 많습니다.\n구매수량:{$this->_viewDatas['fieldDatas']['quantity']}개, 남은 재고수량:{$product->stock}개");
            }
            //구매 금액 비교
            $price = $product->price * $this->_viewDatas['fieldDatas']['quantity'];
            if ($price != $this->_viewDatas['fieldDatas']['price']) {
                throw new \Exception("실 상품금액{$price} 와 구매금액{$this->_viewDatas['fieldDatas']['price']}이 서로 다릅니다.");
            }
            //Transaction 시작
            $this->_model->transStart();
            //주문추가
            $entity = $this->_model->addCart($product, $this->_viewDatas['fieldDatas']['quantity'], $type, $paymentDay);
            //상품재고감소
            $product = $this->getProductModel()->addCart($product, $this->_viewDatas['fieldDatas']['quantity']);
            //주문정보 세션에 넣기
            $order_uids = $this->_session->get(SESSION_NAMES['CART']) ?: array();
            $this->_session->set(SESSION_NAMES['CART'], [...$order_uids, $entity->getPrimaryKey()]);
            //Transaction Commit
            $this->_model->transComplete();
            $msg = sprintf(
                "%s\n 상품명:%s\n 상품갯수:%s개, 구매금액:%s원\n 장바구니에 담았습니다.",
                $this->_viewDatas['title'],
                $entity->getTitle(),
                $entity->quantity,
                number_format($entity->price)
            );
            //Return URL clear -> 장바구니로 바로 이동
            $this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']);
            return redirect()->to(URLS['Order']);
        } catch (\Exception $e) {
            //Transaction Rollback
            $this->_model->transRollback();
            log_message("error", $e->getMessage());
            $msg = sprintf(
                "%s에서 다음 오류로 인해 장바구니에 담기를 실패하였습니다.\n%s",
                $this->_viewDatas['title'],
                $e->getMessage()
            );
            return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
        } finally {
            $this->_session->setFlashdata("return_message", $msg);
        }
    }

    //주문취소(uid -> order_uid)
    public function delete($uid)
    {
        $msg = "";
        try {
            //주문정보 가져오기
            $entity = $this->_model->getEntity([$this->_model->getPrimaryKey() => $uid]);
            //상품정보 가져오기
            $product = $this->getProductModel()->getEntity([$this->getProductModel()->getPrimaryKey() => $entity->product_uid]);
            //Transaction 시작
            $this->_model->transStart();
            //주문취소
            $entity = $this->delete_process($entity);
            //상품반환
            $product = $this->getProductModel()->cancelCart($product, $entity->quantity);
            //주문정보 세션에서 빼기
            $order_uids = $this->_session->get(SESSION_NAMES['CART']) ?: array();
            $temps = array();
            foreach ($order_uids as $order_uid) {
                if ($order_uid != $entity->getPrimaryKey()) {
                    array_push($temps, $order_uid);
                }
            }
            $this->_session->set(SESSION_NAMES['CART'], $temps);
            //Transaction Commit
            $this->_model->transComplete();
            $msg = "{$this->_viewDatas['title']}에서 {$entity->getTitle()} {$entity->quantity}개의 주문을 취소하였습니다.";
            return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
        } catch (\Exception $e) {
            //Transaction Rollback
            $this->_model->transRollback();
            $msg = sprintf(
                "%s에서 다음 오류로 인해 주문취소를 실패하였습니다.\n%s",
                $this->_viewDatas['title'],
                $e->getMessage()
            );
            log_message("error", $e->getMessage());
            return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
        } finally {
            $this->_session->setFlashdata("return_message", $msg);
        }
    }
}
