<?php

namespace App\Controllers\Front;

use App\Models\BoardModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class BoardController extends FrontController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_model = new BoardModel();
        $this->_viewDatas['className'] = 'Board';
        $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']);
        // echo var_export($this->_viewDatas['layout'], true);
        // exit;
    }
    public function getFields(string $action = ""): array
    {
        $fields = ['title', "passwd", "content"];
        switch ($action) {
            case "index":
            case "excel":
                return ['title', "board_file", "created_at", "view_cnt"];
                break;
            case "view":
                return ['title', "board_file", "view_cnt", "created_at", "content"];
                break;
            default:
                return $fields;
                break;
        }
    }
    public function getFieldFilters(): array
    {
        return [];
    }
    public function getFieldBatchFilters(): array
    {
        return parent::getFieldBatchFilters();
    }

    //권한체크
    protected function isRole($action)
    {
        $this->_category = $this->request->getVar('category') ?: throw new \Exception("분류를 지정하지 않으셨습니다.");
        parent::isRole($action);
    }

    //Insert관련
    protected function insert_form_process()
    {
        //권한체크
        $this->isRole('insert');
        parent::insert_form_process();
        $this->_viewDatas['forms'] = ['attributes' => ['method' => "post",], 'hiddens' => [
            'category_uid' => $this->_category,
            'category' => $this->_category
        ]];
    }
    protected function insert_process()
    {
        //권한체크
        $this->isRole('insert');
        return parent::insert_process();
    }
    //Update관련
    protected function update_form_process($entity)
    {
        //본인이 작성한글인지 최종확인용 정상접속이 아닌 위회해서 수정을 시도방지용
        if (!$this->_viewDatas[SESSION_NAMES['ISLOGIN']] || $entity->user_uid != $this->_viewDatas['auth'][AUTH_FIELDS['ID']]) {
            throw new \Exception("작성자 본인글인지 여부가 확인되지 않습니다.");
        }
        //권한체크
        $this->isRole('update');
        $entity = parent::update_form_process($entity);
        $this->_viewDatas['forms'] = ['attributes' => ['method' => "post",], 'hiddens' => [
            'category' => $this->_category
        ]];
        return $entity;
    }
    protected function update_process($entity)
    {
        //본인이 작성한글인지 최종확인용 정상접속이 아닌 위회해서 수정을 시도방지용
        if (!$this->_viewDatas[SESSION_NAMES['ISLOGIN']] || $entity->user_uid != $this->_viewDatas['auth'][AUTH_FIELDS['ID']]) {
            throw new \Exception("작성자 본인글인지 여부가 확인되지 않습니다.");
        }
        return parent::update_process($entity);
    }
    //Reply관련($entity는 부모의것임을 주의)
    protected function reply_form_process($entity)
    {
        //권한체크
        $this->isRole('reply');
        $entity = parent::reply_form_process($entity);
        $this->_viewDatas['forms'] = ['attributes' => ['method' => "post",], 'hiddens' => [
            'category_uid' => $entity->category_uid,
            'category' => $this->_category
        ]];
        return $entity;
    }
    //Delete 관련
    protected function delete_process($entity)
    {
        //본인이 작성한글인지 최종확인용 정상접속이 아닌 위회해서 삭제 시도 방지용
        if (!$this->_viewDatas[SESSION_NAMES['ISLOGIN']] || $entity->user_uid == $this->_viewDatas['auth'][AUTH_FIELDS['ID']]) {
            throw new \Exception("작성자 본인글인지 여부가 확인되지 않습니다.");
        }
        return parent::delete_process($entity);
    }
    //View관련
    protected function view_process($entity)
    {
        //권한체크
        $this->isRole('view');
        //조회수 올리기
        $entity = $this->_model->addViewCount($entity);
        $entity = parent::view_process($entity);
        $this->_viewDatas['forms'] = ['attributes' => ['method' => "post",], 'hiddens' => [
            'category' => $this->_category
        ]];
        return $entity;
    }
    //Index관련
    protected function index_process()
    {
        //권한체크
        $this->isRole('index');
        parent::index_process();
        $this->_viewDatas['forms'] = ['attributes' => ['method' => "post",], 'hiddens' => [
            'category' => $this->_category
        ]];
    }
    //Category 및 Status 조건추가
    protected function index_setCondition()
    {
        $this->_model->where("category_uid", $this->_viewDatas['category']->getPrimaryKey());
        $this->_model->where("status", DEFAULTS['STATUS']);
        parent::index_setCondition();
    }
    //Download관련
    public function download_process($field, $entity): array
    {
        $entity = parent::download_process($field, $entity);
        //권한체크
        $this->isRole('download', $entity);
        list($filename, $uploaded_filename) = explode(DEFAULTS['DELIMITER_FILE'], $entity->$field);
        if (!is_file(PATHS['UPLOAD'] . "/" . $uploaded_filename)) {
            throw new \Exception("파일이 확인되지 않습니다.\n" . PATHS['UPLOAD'] . "/" . $uploaded_filename);
        }
        return array($filename, $uploaded_filename);
        return parent::download_process($field, $entity);
    }
}
