<?php

namespace App\Services;

use App\Helpers\BoardHelper;
use App\Models\BoardModel;

class BoardService extends CommonService
{
    public function __construct()
    {
        parent::__construct(new BoardModel(), new BoardHelper());
        $this->addClassName('Board');
    }
    public function getFormFields(): array
    {
        return [
            'category',
            'worker_uid',
            'title',
            'status',
            'content',
        ];
    }
    public function getFormFilters(): array
    {
        return [
            'user_uid',
            'worker_uid',
            'category',
            'status',
        ];
    }
    public function getIndexFields(): array
    {
        return [
            'category',
            'title',
            'worker_uid',
            'user_uid',
            'status',
            'created_at',
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['user_uid', 'category', 'status'];
    }
    public function getFormOption(string $field, array $options = []): array
    {
        switch ($field) {
            case 'worker_uid':
                $options = $this->getUserService()->getEntities();
                break;
            default:
                $options = parent::getFormOption($field, $options);
                break;
        }
        if (!is_array($options)) {
            throw new \Exception(__FUNCTION__ . "에서 {$field}의 options 값들이 array가 아닙니다.\n" . var_export($options, true));
        }
        return $options;
    }
    //기본 기능부분
    //Category별 최근 $limit갯수만큼 게시물
    public function getLatest(string $category, array $where = []): array
    {
        //관리자정보
        $userEntities = $this->getUserService()->getEntities();
        $datas     = [];
        foreach ($this->getEntities(['category' => $category, 'status' => STATUS['AVAILABLE'], ...$where]) as $entity) {
            $datas[] = [
                'title' => "<label for=\"view\" data-src=\"/admin/board/view/{$entity->getPK()}\" data-bs-toggle=\"modal\" data-bs-target=\" #modal_action_form\" class=\"text-primary form-label-sm\">{$entity->getTitle()}</label>",
                'created_at' => date('Y-m-d H:m', strtotime($entity->getCreatedAT())),
                'user' => $userEntities[$entity->getUserUID()]->getTitle(),
            ];
        }
        return $datas;
    }
    //요청업무 게시물
    public function getRequestTaskCount(int $worker_uid): int
    {
        $where = [
            'category' => BOARD['CATEGORY']['REQUESTTASK'],
            'worker_uid' => $worker_uid,
            'status' => STATUS['AVAILABLE'],
        ];
        return count($this->getEntities($where));
    }
}
