<?php

namespace App\Models;

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

class EditorImage extends Model
{
    protected $table = 'tb_editor_image';
    protected $primaryKey = 'id';

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

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

    protected $guarded = [];

    public function post()
    {
        return $this->hasOne(Post::class, 'post_id', 'target_id');
    }

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    public function comment()
    {
        return $this->hasOne(Comment::class, 'comment_id', 'target_id');
    }

    /**
     * 게시글 이미지 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select(
            'tb_editor_image.*',
            'users.sid',
            'users.name',
            'users.email'
        );

        if($params->keyword) {
            switch ($params->field) {
                case 'tb_editor_image.origin_name' :
                case 'tb_editor_image.ip_address' :
                case 'users.name' :
                case 'users.email' :
                    $query->where($params->field, 'LIKE', "%{$params->keyword}%");
                    break;
                case 'tb_editor_image.id' :
                case 'users.id' :
                case 'users.sid' :
                    $query->where($params->field, '=', $params->keyword);
                    break;
            }

            if(in_array($params->field, ['tb_editor_image.target_type=1', 'tb_editor_image.target_type=2'])) {
                if($params->field == "tb_editor_image.target_type=1") {
                    $query->where('tb_editor_image.target_type', '=', 1);
                }
                if($params->field == "tb_editor_image.target_type=2") {
                    $query->where('tb_editor_image.target_type', '=', 2);
                }
                $query->where('tb_editor_image.target_id', '=', $params->keyword);
            }
        }

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

        $query->leftJoin('users', 'users.id', '=', 'tb_editor_image.user_id');
        $query->orderByDesc('tb_editor_image.id');

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

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

    /**
     * Editor 이미지 삭제
     */
    public function deleteFiles(int $targetType, int $targetID): void
    {
        $query = $this->query();
        $files = $query->select('id', 'file_path')->where([
            ['target_type', $targetType],
            ['target_id', $targetID]
        ])->get();

        // 게시물 이미지 파일 삭제
        if($files->count() > 0) {
            foreach($files as $file) {
                $this->remove($file->id);
            }
        }
    }

    /**
     * 에디터 이미지 파일 삭제
     */
    public function remove(int $editorImageID): bool
    {
        return DB::transaction(function() use($editorImageID) {
            $file = $this->findOrNew($editorImageID);

            // 게시글 존재 확인
            if(!$file->exists) {
                return false;
            }

            // 이미지 수 갱신
            if($file->target_type == EDITOR_IMG_TYPE_1) {
                (new Post)->updateImageRows($file->target_id);
            }

            // 파일 삭제
            Storage::delete($file->file_path);
            if(file_exists($file->file_path)) {
                unlink($file->file_path);
            }

            // 이미지 파일 정보 삭제
            return $file->delete();
        });
    }

    /**
     * 에디터 이미지 경로 삭제
     */
    public function truncate(int $targetType, int|string $targetID): void
    {
        $where = match($targetType) {
            EDITOR_IMG_TYPE_1 => [
                ['target_type', $targetType],
                ['target_id', $targetID]
            ],
            EDITOR_IMG_TYPE_2 => function() use ($targetType, $targetID) {
                return [
                    ['target_type', $targetType],
                    ['target_id', 'like', $targetID . '%']
                ];
            }
        };

        if($this->where($where)->delete()) {
            (new FileLib)->removePath(MAP_EDITOR_IMG_TYPE[$targetType], $targetID);
        }
    }

    /**
     * Editor 이미지 정보 입력
     */
    public function register(array $params): bool
    {
        $sql = "
            INSERT INTO tb_editor_image
                (target_type, target_id, user_id, origin_name, file_name, file_path, file_url, file_size, file_type, width, height, ip_address, user_agent, created_at)
            SELECT
                :target_type, :target_id, :user_id, :origin_name, :file_name, :file_path, :file_url, :file_size, :file_type, :width, :height, :ip_address, :user_agent, NOW()
            FROM DUAL WHERE NOT EXISTS
                (SELECT * FROM tb_editor_image WHERE file_name = :file_name LIMIT 1)
        ";

        return DB::insert($sql, $params);
    }
}
