<?php

namespace App\Controllers\Admin;

use App\Controllers\Trait\UpDownloadTrait;
use App\Models\DeviceModel;
use App\Models\ProductModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class ProductController extends AdminController
{
    use UpDownloadTrait;
    private $_deviceModel = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_model = new ProductModel();
        $this->_viewDatas['className'] = 'Product';
        $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
    {
        $fields = ["category", 'type', 'name', "photo", "device", "cost", "sale",  "stock", "view_cnt", "status", "content",];
        switch ($action) {
            case "index":
            case "excel":
                return ["category", "user_uid", 'type', 'name', "cost", "sale", "price", "stock", "view_cnt", "status", "created_at"];
                break;
            case "view":
                return [...$fields, "created_at"];
                break;
            default:
                return $fields;
                break;
        }
    }
    public function getFieldFilters(): array
    {
        return ["category", "user_uid", 'type',  "status"];
    }
    public function getFieldBatchFilters(): array
    {
        return parent::getFieldBatchFilters();
    }
    //Field별 Form Datas 처리용
    protected function getFieldFormData(string $field, $entity = null): array
    {
        switch ($field) {
            case 'photo':
                $file = $this->upload_image_procedure($field);
                if (!is_null($file)) {
                    $this->_viewDatas['fieldDatas'][$field] = $file;
                }
                break;
            default:
                return parent::getFieldFormData($field, $entity);
                break;
        }
        return $this->_viewDatas['fieldDatas'];
    }

    private function calculate_price(): int
    {
        if ($this->_viewDatas['fieldDatas']['cost'] < $this->_viewDatas['fieldDatas']['sale']) {
            throw new \Exception(sprintf(
                "%s가[%s] %s[%s]보다 작습니다.",
                lang($this->_viewDatas['className'] . '.label.cost'),
                number_format($this->_viewDatas['fieldDatas']['cost']),
                lang($this->_viewDatas['className'] . '.label.sale'),
                number_format($this->_viewDatas['fieldDatas']['sale']),
            ));
        }
        return $this->_viewDatas['fieldDatas']['cost'] - $this->_viewDatas['fieldDatas']['sale'];
    }

    //가상서버
    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->_model->create($protudctDatas);
        //return $this->add_procedure($product, 1, $this->_viewDatas['fieldDatas']['paymentday']);
    }
    //실서버
    protected function beremetal_process()
    {
        //상품정보가져오기
        $product = $this->_model->getEntity([$this->_model->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 device_process()
    {
        switch ($this->_viewDatas['fieldDatas']['category']) {
            case 'virtual':
                return $this->virtual_process();
                break;
            case 'beremetal':
                return $this->beremetal_process();
                break;
            default:
                throw new \Exception($this->_viewDatas['fieldDatas']['category'] . "는 알수없는 상품 구분입니다. 다시 확인 부탁드립니다.");
                break;
        }
    }

    //Insert관련
    protected function insert_validate()
    {
        parent::insert_validate();
    }
    protected function insert_process()
    {
        $this->device_process();
        $this->_viewDatas['fieldDatas']['price'] = $this->calculate_price();
        return parent::insert_process();
    }
    //Update관련
    protected function update_process($entity)
    {
        $this->_viewDatas['fieldDatas']['price'] = $this->calculate_price();
        return parent::update_process($entity);
    }
}
