<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Models\DTO\SearchData;

class PostHistory extends Model
{
    protected $table = 'tb_post_history';
    protected $primaryKey = 'id';

    public $keyType = 'int';
    public $incrementing = true;
    public $timestamps = true;

    const CREATED_AT = 'created_at';
    const UPDATED_AT = null;

    protected $guarded = [];

    /**
     * 게시물 변경 이력 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select(
            'tb_board.name AS boardName',
            'tb_post_history.id',
            'tb_post_history.board_id',
            'tb_post_history.before_subject',
            'tb_post_history.after_subject',
            'tb_post_history.before_content',
            'tb_post_history.after_content',
            'tb_post_history.ip_address',
            'tb_post_history.user_agent',
            'tb_post_history.created_at',
            'user_1.sid AS sid_1',
            'user_1.name AS name_1',
            'user_2.sid AS sid_2',
            'user_2.name AS name_2'
        );

        if($params->keyword) {
            switch ($params->field) {
                case 'tb_post_history.before_subject' :
                case 'tb_post_history.after_subject' :
                case 'tb_post_history.before_content' :
                case 'tb_post_history.after_content' :
                case 'tb_post_history.ip_address' :
                case 'user_1.name' :
                case 'user_1.email' :
                case 'user_2.name' :
                case 'user_2.email' :
                    $query->where($params->field, 'LIKE', "%{$params->keyword}%");
                    break;
                case 'user_1.id' :
                case 'user_1.sid' :
                case 'user_2.id' :
                case 'user_2.sid' :
                    $query->where($params->field, '=', $params->keyword);
                    break;
            }
        }

        if($params->startDate || $params->endDate) {
            if($params->startDate) {
                $query->where('tb_post_history.created_at', '>=', $params->startDate . ' 00:00:00');
            }
            if($params->endDate) {
                $query->where('tb_post_history.created_at', '<=', $params->endDate . ' 23:59:59');
            }
        }

        if($params->boardID) {
            $query->where('tb_post_history.board_id', '=', $params->boardID);
        }

        $query->join('tb_board', 'tb_board.id', '=', 'tb_post_history.board_id');
        $query->join('tb_post', 'tb_post.id', '=', 'tb_post_history.post_id');
        $query->leftJoin('users AS user_1', 'user_1.id', '=', 'tb_post_history.user_id'); // 수정
        $query->leftJoin('users AS user_2', 'user_2.id', '=', 'tb_post.user_id'); // 작성
        $query->orderByDesc('tb_post_history.id');

        $list = $query->paginate($params->perPage, ['*'], 'page', $params->page);
        $total = $this->count();
        $rows = $list->count();

        return (object)[
            'total' => $total,
            'rows' => $rows,
            'list' => $list
        ];
    }

    /**
     * 게시글 최초 기록
     */
    public function register(Post $post, string $memo): int
    {
        return $this->insert([
            'board_id' => $post->board_id,
            'post_id' => $post->id,
            'user_id' => $post->user_id,
            'before_subject' => $post->subject,
            'after_subject' => null,
            'before_content' => $post->content,
            'after_content' => null,
            'memo' => $memo,
            'ip_address' => IP_ADDRESS,
            'user_agent' => USER_AGENT,
            'created_at' => now()
        ]);
    }

    /**
     * 게시글 수정/삭제 등 기록
     */
    public function updater(Post $post, string $memo): bool
    {
        $sql = '
            INSERT INTO tb_post_history (board_id, post_id, user_id, before_subject, after_subject, before_content, after_content, memo, ip_address, user_agent, created_at)
            SELECT board_id, id, :user_id, :subject, subject, :content, content, :memo, :ip_address, :user_agent, NOW()
            FROM tb_post WHERE id = :post_id;
        ';

        return DB::insert($sql, [
            'post_id' => $post->id,
            'user_id' => $post->user_id,
            'subject' => $post->subject,
            'content' => $post->content,
            'memo' =>  $memo,
            'ip_address' => IP_ADDRESS,
            'user_agent' => USER_AGENT
        ]);
    }
}
