<?php

namespace App\Controllers\Front;

use App\Controllers\Trait\CartTrait;
use App\Models\OrderModel;
use App\Models\ProductModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class OrderController extends FrontController
{
    use CartTrait;
    const DEFAULT_CATEGORY = "orderinfo";
    private $_productModel = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_model                   = new OrderModel();
        $this->_viewDatas['className']  = 'Order';
        $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']);
    }

    final protected function getProductModel(): ProductModel
    {
        return $this->_productModel = $this->_productModel ?: new ProductModel();
    }

    public function getFields(string $action = ""): array
    {
        switch ($action) {
            case 'beremetal':
                return ["category", "product_uid", "quantity", "price", 'paymentday'];
            case 'virtual':
                return ["category", "cpu", "memory", "disk", "price", 'paymentday'];
                break;
            case "index":
            case "excel":
                return ["type", 'name', "cost", "sale", "quantity", "price", "status"];
                break;
            case "view":
                return ["type", 'name', "cost", "sale", "quantity", "price", "status", "updated_at", "created_at"];
                break;
            default:
                return [];
                break;
        }
    }
    protected function getFieldRule(string $field, array $rules, string $action = ""): array
    {
        switch ($field) {
            case 'category':
                $rules[$field] = "required|min_length[3]";
                break;
            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':
            case 'cpu':
            case 'memory':
            case 'disk':
                $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 ['product_uid', "type", "status"];
    }
    public function getFieldBatchFilters(): array
    {
        return ["status"];
    }

    //가상서버
    protected function virtual_process()
    {
        //가상서버정보
        $protudctDatas = array(
            'category' => 'virtual',
            'name'     => '',
            'content'  => '',
            'cost'     => $this->_viewDatas['fieldDatas']['price'],
            'price'    => $this->_viewDatas['fieldDatas']['price'],
            'sale'     => 0,
            'stock'    => 1,
            'view_cnt' => 1,
            'status'   => 'use',
        );
        //서버부품정보검증
        $titles = array('가상서버');
        //foreach (Product['parts']['virtual']['category'] as $category => $attrs) {
        foreach ([] as $category => $attrs) {
            if (!$this->_viewDatas['fieldDatas'][$category]) {
                throw new \Exception($category . "의 값이 지정되지 않았습니다.");
            } else {
                $protudctDatas[$category . "_model"] = $attrs['label'];
                $protudctDatas[$category . "_cnt"]   = $this->_viewDatas['fieldDatas'][$category];
                array_push(
                    $titles,
                    sprintf(
                        "%s * %s%s,",
                        $protudctDatas[$category . "_model"],
                        $protudctDatas[$category . "_cnt"],
                        $attrs['unit'],
                    ),
                );
            }
        }
        $protudctDatas['name']    = implode(" ", $titles);
        $protudctDatas['content'] = implode("\n", $titles);
        $product                  = $this->getProductModel()->create($protudctDatas);
        return $this->add_procedure($product, 1, $this->_viewDatas['fieldDatas']['paymentday']);
    }
    //실서버
    protected function beremetal_process()
    {
        //상품정보가져오기
        $product = $this->getProductModel()->getEntity([$this->getProductModel()->getPrimaryKey() => $this->_viewDatas['fieldDatas']['product_uid']]);
        //재고수 비교
        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']}이 서로 다릅니다.");
        }
        //결제방식이 월이용권이면 결제일 확인
        $paymentDay = null;
        if ($product->type == 'rental') {
            $paymentDay = $this->request->getVar('paymentday') ?: throw new \Exception("월이용권 상품의 경우는 매월 결제일을 지정해주셔야합니다.");
        }
        return $this->add_procedure($product, $this->_viewDatas['fieldDatas']['quantity'], $paymentDay);
    }

    //주문처리
    protected function insert_process()
    {
        switch ($this->_viewDatas['fieldDatas']['category']) {
            case 'virtual':
                throw new \Exception('가상화서버처리');
                return $this->virtual_process();
                break;
            case 'beremetal':
                throw new \Exception('실서버처리');
                return $this->beremetal_process();
                break;
            default:
                throw new \Exception($this->_viewDatas['fieldDatas']['category'] . "는 알수없는 상품 구분입니다. 다시 확인 부탁드립니다.");
                break;
        }
    }

    //주문취소처리
    public function delete_process($order_uid)
    {
        return $this->cancel_procedure($order_uid);
    }

    //Index관련
    protected function index_process()
    {
        //Category 확인
        $this->setCategory($this->request->getVar('category') ?: self::DEFAULT_CATEGORY);
        parent::index_process();
    }
    protected function index_condition()
    {
        //세션에 Cart정보(order_uids)가 있으면
        $uids = $this->_session->get(SESSION_NAMES['CART']) ?: array('NONE');
        //또는 Login했으면 사용자정보(user_uid)에 맞는 Order정보 가져오기
        if ($this->_session->get(SESSION_NAMES['ISLOGIN'])) {
            $this->_model->where('user_uid', $this->_session->get(SESSION_NAMES['AUTH'])[AUTH_FIELDS['ID']]);
            if (count($uids)) {
                $this->_model->orWhereIn('uid', $uids);
            }
        } elseif (count($uids)) {
            $this->_model->whereIn('uid', $uids);
        }
        parent::index_condition();
    }
}
