<?php

namespace App\Http\Controllers\Admin\Board;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Traits\AgentTrait;
use App\Models\Board;
use App\Models\EditorImage;
use App\Models\DTO\SearchData;
use Exception;

class ImageController extends Controller
{
    use AgentTrait;

    private Board $boardModel;
    private EditorImage $editorImageModel;

    public function __construct(Board $board, EditorImage $editorImage)
    {
        $this->boardModel = $board;
        $this->editorImageModel = $editorImage;
    }

    /**
     * 게시판 > 이미지 관리
     * @method GET
     * @see /admin/board/image
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $editorImageData = $this->editorImageModel->data($params);

        if ($editorImageData->rows > 0) {
            $num = listNum($editorImageData->total, $params->page, $params->perPage);
            foreach ($editorImageData->list as $i => $row) {
                $row->num = $num--;
                $row->fileExists = file_exists($row->file_path);
                $row->targetStr = MAP_EDITOR_IMG_TYPE[$row->target_type];
                $row->editURL = route('admin.board.image.edit', $row->id);
                $row->fileLink = route('admin.board.image.show', $row->id);

                $editorImageData->list[$i] = $row;
            }
        }

        return view('admin.board.image.index', [
            'editorImageData' => $editorImageData,
            'params' => $params
        ]);
    }

    /**
     * 게시판 > 이미지 관리 삭제
     * @method DELETE
     * @see /admin/board/image/destroy
     */
    public function destroy(Request $request)
    {
        try {

            $chk = $request->post('chk');
            $fileName = $request->post('file_name');

            if ($chk) {
                foreach ($chk as $editorImageID) {
                    $editorImage = $this->editorImageModel->findOrNew($editorImageID);

                    if(!$editorImage->exists) {
                        throw new Exception($editorImageID . '번 이미지는 존재하지 않습니다.');
                    }

                    if(!$this->editorImageModel->remove($editorImageID)) {
                        throw new Exception($editorImageID . '번 ' . $fileName[$editorImageID] . " 파일을 삭제할 수 없습니다.");
                    }
                }
            }

            $message = '에디터 이미지가 삭제되었습니다.';
            return redirect()->route('admin.board.image.index')->with('message', $message);
        } catch (Exception $e) {
            return back()->withErrors($e->getMessage())->withInput();
        }
    }

    /**
     * 게시판 > 이미지 관리 상세보기
     * @method GET
     * @see /admin/board/image/show/{pk}
     */
    public function show(int $editorImageID)
    {
        $imageModel = $this->editorImageModel->findOrFail($editorImageID);

        if(!file_exists($imageModel->file_path)) {
            return back()->with('message', '해당 파일이 존재하지 않습니다.');
        }

        return response()->download($imageModel->file_path, $imageModel->origin_name);
    }

    /**
     * 게시판 > 이미지 정보 상세 보기
     * @method GET
     * @see /admin/board/image/{pk}/edit
     */
    public function edit(int $editorImageID)
    {
        $image = $this->editorImageModel->findOrFail($editorImageID);
        $image->device = $this->device($image->user_agent);
        $image->platform = $this->platform($image->user_agent);
        $image->browser = $this->browser($image->user_agent);
        $image->fileLink = route('admin.board.image.show', $image->id);
        $image->fileSize = byteFormat($image->file_size, 2);
        $image->download = number_format($image->download);

        return view('admin.board.image.edit', [
            'image' => $image
        ]);
    }
}
