<?php

namespace App\Controllers\Trait;

use App\Entities\OrderEntity;
use App\Entities\ProductEntity;
use App\Models\OrderModel;
use App\Models\ProductModel;

trait CartTrait
{
    private $_serverModel = null;
    private $_orderModel = null;
    private function getOrderModel(): OrderModel
    {
        return $this->_orderModel = $this->_orderModel ?: new OrderModel();
    }
    private function getProductModel(): ProductModel
    {
        return $this->_serverModel = $this->_serverModel ?: new ProductModel();
    }

    public function add_procedure(ProductEntity $product, int $quantity, int $paymentDay = null): OrderEntity
    {
        //상품재고감소
        $product = $this->getProductModel()->addCart($product, $quantity);
        //주문추가
        $entity = $this->getOrderModel()->addCart($product, $quantity, $product->type, $paymentDay);
        //주문정보 세션에 넣기
        $order_uids = $this->_session->get(SESSION_NAMES['CART']) ?: array();
        $this->_session->set(SESSION_NAMES['CART'], [...$order_uids, $entity->getPrimaryKey()]);
        $this->_session->setFlashdata(
            "return_message",
            sprintf(
                "%s\n 상품명:%s\n 상품갯수:%s개, 구매금액:%s원\n 장바구니에 담았습니다.",
                $this->_viewDatas['title'],
                $entity->getTitle(),
                $entity->quantity,
                number_format($entity->price),
            ),
        );
        return $entity;
    }

    public function cancel_procedure($uid)
    {
        //주문정보 가져오기
        $entity = $this->getOrderModel()->getEntity([$this->getOrderModel()->getPrimaryKey() => $uid]);
        //상품정보 가져오기
        $product = $this->getProductModel()->getEntity([$this->getProductModel()->getPrimaryKey() => $entity->product_uid]);
        //주문취소
        $entity = $this->getOrderModel()->cancelCart($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);
        $this->_session->setFlashdata("return_message", "{$this->_viewDatas['title']}에서 {$entity->getTitle()} {$entity->quantity}개의 주문을 취소하였습니다.");
    }
}
