<?php

namespace App\Http\Controllers\Admin\Board\File;

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

class DownloadController extends Controller
{
    use AgentTrait;

    private Board $boardModel;
    private PostFile $postFileModel;
    private PostFileDownLog $postFileDownloadLogModel;

    public function __construct(Board $board, PostFile $postFile, PostFileDownLog $postFileDownLog)
    {
        $this->boardModel = $board;
        $this->postFileModel = $postFile;
        $this->postFileDownloadLogModel = $postFileDownLog;
    }

    /**
     * 게시판 > 첨부파일 (다운로드)
     * @method GET
     * @see /admin/board/file/download
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->boardID = $request->get('board_id');

        $postFileLogData = $this->postFileDownloadLogModel->data($params);

        if ($postFileLogData->rows > 0) {
            $num = listNum($postFileLogData->total, $params->page, $params->perPage);
            foreach ($postFileLogData->list as $i => $row) {
                $row->num = $num--;
                $row->postURL = route('board.post.view', [$row->code, $row->post_id]);
                $row->fileLink = route('admin.board.file.download.show', $row->post_file_id);
                $row->editURL = route('admin.board.file.download.edit', $row->id);
                $row->fileSize = byteFormat($row->file_size, 2);
                $row->fileExists = file_exists($row->file_path);
                $row->browser = $this->browser($row->user_agent);
                $row->platform = $this->platform($row->user_agent);
                $row->download = number_format($row->download);
                $row->createdAt = dateBr($row->created_at);

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

        return view('admin.board.file.download.index', [
            'postFileLogData' => $postFileLogData,
            'params' => $params,
            'boardData' => $this->boardModel->all()
        ]);
    }

    /**
     * 게시판 > 첨부파일 (다운로드) 삭제
     * @method DELETE
     * @see /admin/board/file/download/destroy
     */
    public function destroy(Request $request)
    {
        try {

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

            if ($chk) {
                foreach ($chk as $postFileDownLogID) {
                    $postFileDownloadLog = $this->postFileDownloadLogModel->findOrNew($postFileDownLogID);

                    if(!$postFileDownloadLog->exists) {
                        throw new Exception($postFileDownLogID . '번 다운로드 이력은 존재하지 않습니다.');
                    }

                    if(!$postFileDownloadLog->delete()) {
                        throw new Exception($postFileDownLogID . '번 다운로드 기록을 삭제할 수 없습니다.');
                    }
                }
            }

            $message = '다운로드 기록이 삭제되었습니다.';
            return redirect()->route('admin.board.file.download.index')->with('message', $message);
        } catch (Exception $e) {
            return back()->withErrors($e->getMessage())->withInput();
        }
    }

    /**
     * 게시판 > 첨부파일(다운로드) 실행
     * @method GET
     * @see /admin/board/file/download/show/{pk}
     */
    public function show(int $postFileID)
    {
        $fileModel = $this->postFileModel->findOrFail($postFileID);

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

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

    /**
     * 게시판 > 첨부파일(다운로드) 상세 보기
     * @method GET
     * @see /admin/board/file/download/{pk}/edit
     */
    public function edit(int $postFileDownLogID)
    {
        $log = $this->postFileDownloadLogModel->findOrFail($postFileDownLogID);
        $log->device = $this->device($log->user_agent);
        $log->platform = $this->platform($log->user_agent);
        $log->browser = $this->browser($log->user_agent);
        $log->fileLink = route('admin.board.file.download.show', $postFileDownLogID);
        $log->fileSize = byteFormat($log->postFile->file_size, 2);
        $log->download = number_format($log->postFile->download);

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