<?php

namespace App\Controllers\Front\Order;

use App\Controllers\Front\FrontController;
use App\Models\OrderModel;
use App\Models\ProductModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class OrderController extends FrontController
{
    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']);

        //Default 회원정보 Category
        $this->_category = DEFAULTS['CATEGORY_ORDER'];
        $this->isRole('index');
    }

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

    public function getFields(string $action = ""): array
    {
        switch ($action) {
            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;
        }
    }
    public function getFieldFilters(): array
    {
        return ['product_uid', "type", "status"];
    }
    public function getFieldBatchFilters(): array
    {
        return ["status"];
    }

    //View관련
    protected function view_process($entity)
    {
        //권한체크
        $this->isRole('view', $entity);
        return parent::view_process($entity);
    }

    //Index관련
    protected function index_process()
    {
        //권한체크
        $this->isRole('index');
        return parent::index_process();
    }
    protected function index_setCondition()
    {
        //세션에 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_setCondition();
    }
}
