<?php

namespace App\Controllers\Admin;

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

class ProductController extends AdminController
{
    use UpDownloadTrait;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        $this->_model = new ProductModel();
        parent::initController($request, $response, $logger);
        $this->_viewPath .= strtolower($this->_model->getClassName());
    }

    public function getFields(string $action = ""): array
    {
        $fields = ["category_uid", 'name', "photo", "cost", "sale",  "stock", "view_cnt", "status", "content",];
        switch ($action) {
            case "index":
            case "excel":
                return ["category_uid", "user_uid", 'name', "photo", "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_uid", "user_uid", "status"];
    }
    public function getFieldBatchFilters(): array
    {
        return parent::getFieldBatchFilters();
    }
    //Field별 Form Datas 처리용
    protected function getFieldFormData(string $field, $entity = null): array
    {
        switch ($field) {
            case 'photo':
                $this->_viewDatas['fieldDatas'][$field] = $this->upload_image_procedure($field);
                break;
            default:
                return parent::getFieldFormData($field, $entity);
                break;
        }
        return $this->_viewDatas['fieldDatas'];
    }

    protected function insert_process()
    {
        if ($this->_viewDatas['fieldDatas']['cost'] < $this->_viewDatas['fieldDatas']['sale']) {
            throw new \Exception(sprintf(
                "%s가[%s] %s[%s]보다 작습니다.",
                lang($this->_model->getClassName() . '.label.cost'),
                number_format($this->_viewDatas['fieldDatas']['cost']),
                lang($this->_model->getClassName() . '.label.sale'),
                number_format($this->_viewDatas['fieldDatas']['sale']),
            ));
        }
        $this->_viewDatas['fieldDatas']['price'] = $this->_viewDatas['fieldDatas']['cost'] - $this->_viewDatas['fieldDatas']['sale'];
        return parent::insert_process();
    }
}
