<?php

namespace App\Http\Traits;

use App\Models\BoardMeta;
use App\Models\DTO\SearchData;

trait BoardTrait
{
    /**
     * 게시판 설정 값 조회
     */
    protected function boardMeta(int $boardID): ?BoardMeta
    {
        return (new BoardMeta)->getAllMeta($boardID);
    }

    /**
     * 시간을 하루 기준으로 시분초 또는 일자로 노출
     */
    protected function shortDate($dateAt): string
    {
        return (round((time() - strtotime($dateAt)) / 86400) >= 1 ? date('Y.m.d', strtotime($dateAt)) : date('H:i', strtotime($dateAt)));
    }

    /**
     * 게시판 Querys 주소 생성
     */
    protected function queryString(?SearchData $params = null)
    {
        parse_str(request()->getQueryString(), $queryString);
        return ('?' . (http_build_query([
            'page' => ($queryString['page'] ?? $params->page ?? 1),
            'per_page' => ($queryString['per_page'] ?? $params->perPage ?? null),
            'sort' => ($queryString['sort'] ?? $params->sort ?? null),
            'category' => ($queryString['category'] ?? $params->category ?? null),
            'field' => ($queryString['field'] ?? $params->field ?? null),
            'keyword' => ($queryString['keyword'] ?? $params->keyboard ?? null)
        ])));
    }

    /**
     * 익명 이름 생성
     */
    protected function createAnonymousName(string $format, int $userID, int $documentID): string
    {
        return preg_replace_callback('/\$((?:DAILY|DOC|DOCDAILY|)NUM)(?::([0-9]))?/', function($matches) use($userID, $documentID) {
            $digits = empty($matches[2]) ? 8 : max(1, min(8, intval($matches[2])));
            switch ($matches[1])
            {
                case 'NUM': return $this->_createHash($userID ?: \IP_ADDRESS, $digits);
                case 'DAILYNUM': return $this->_createHash(($userID ?: \IP_ADDRESS) . ':date:' . date('Y-m-d'), $digits);
                case 'DOCNUM': return $this->_createHash(($userID ?: \IP_ADDRESS) . ':documentID:' . $documentID, $digits);
                case 'DOCDAILYNUM': return $this->_createHash(($userID ?: \IP_ADDRESS) . ':documentID:' . $documentID . ':date:' . date('Y-m-d'), $digits);
            }
        }, $format);
    }

    /**
     * 익명 이름 Hash 처리
     */
    protected function _createHash(string $content, int $digits = 8): string
    {
        return sprintf('%0' . $digits . 'd', hexdec(substr(hash_hmac('sha256', $content, ENCRYPT_KEY), 0, 8)) % pow(10, $digits));
    }
}
