<?php

namespace App\Http\Controllers\Admin\Page;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use App\Http\Traits\CommonTrait;
use App\Models\Document;
use App\Models\DTO\SearchData;
use App\Models\FileLib;
use Exception;

class DocumentController extends Controller
{
    use CommonTrait;

    private Document $documentModel;

    public function __construct(Document $document)
    {
        $this->documentModel = $document;
    }

    /**
     * 문서 관리
     * @method GET
     * @see /admin/page/document
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);

        $documentData = $this->documentModel->data($params);

        if ($documentData->total > 0) {
            $num = listNum($documentData->total, $params->page, $params->perPage);
            foreach ($documentData->list as $i => $row) {
                $row->num = $num--;
                $row->url = route('document', $row->code);
                $row->views = number_format($row->views);
                $row->creater = $row->user->find($row->user_id);
                $row->updater = $row->user->find($row->updated_user_id);
                $row->editURL = route('admin.page.document.edit', $row->id);

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

        return view('admin.page.document.index', [
            'documentData' => $documentData,
            'params' => $params
        ]);
    }

    /**
     * 문서 등록
     * @method GET
     * @see /admin/page/document/create
     */
    public function create()
    {
        return view('admin.page.document.write', [
            'actionURL' => route('admin.page.document.store'),
            'documentData' => [],
            'documentID' => null
        ]);
    }

    /**
     * 문서 수정
     * @method GET
     * @see /admin/page/document/{pk}/edit
     */
    public function edit(int $documentID)
    {
        return view('admin.page.document.write', [
            'actionURL' => route('admin.page.document.update', $documentID),
            'documentData' => $this->documentModel->find($documentID),
            'documentID' => $documentID
        ]);
    }

    /**
     * 문서 등록 저장
     * @method POST
     * @see /admin/page/document
     */
    public function store(Request $request, FileLib $fileLib)
    {
        $rules = [
            'code' => 'string|min:3|max:50|unique:tb_document,code',
            'subject' => 'string|max:150',
            'content' => 'string|nullable',
            'mobile_content' => 'string|nullable'
        ];

        $attributes = [
            'code' => '주소',
            'subject' => '제목',
            'content' => 'PC 내용',
            'mobile_content' => '모바일 내용'
        ];

        $posts = $this->validate($request, $rules, [], $attributes);
        $posts['content'] = $fileLib->saveAsImage($posts['content'], UPLOAD_PATH_DOCUMENT);

        $this->documentModel->insert([
            'user_id' => UID,
            'code' => $posts['code'],
            'subject' => $posts['subject'],
            'content' => $posts['content'],
            'views' => 0,
            'ip_address' => IP_ADDRESS,
            'user_agent' => USER_AGENT,
            'updated_user_id' => null,
            'updated_at' => null,
            'created_at' => now()
        ]);

        $message = '문서가 등록되었습니다.';
        return redirect()->route('admin.page.document.index')->with('message', $message);
    }

    /**
     * 문서 수정 저장
     * @method PUT
     * @see /admin/page/document/{pk}
     */
    public function update(Request $request, FileLib $fileLib)
    {
        $documentID = $request->post('document_id');

        $rules = [
            'document_id' => 'required|numeric|exists:tb_document,id',
            'code' => [
                'string',
                'min:3',
                'max:50',
                Rule::unique('tb_document', 'code')->ignore($documentID, 'id'),
            ],
            'subject' => 'string|max:150',
            'content' => 'string|nullable'
        ];

        $attributes = [
            'document_id' => '번호',
            'code' => '주소',
            'subject' => '제목',
            'content' => '내용'
        ];

        $posts = $this->validate($request, $rules, [], $attributes);
        $posts['content'] = $fileLib->saveAsImage($posts['content'], UPLOAD_PATH_DOCUMENT);

        $this->documentModel->find($documentID)->update([
            'code' => $posts['code'],
            'subject' => $posts['subject'],
            'content' => $posts['content'],
            'ip_address' => IP_ADDRESS,
            'user_agent' => USER_AGENT,
            'updated_user_id' => UID,
            'updated_at' => now()
        ]);

        $message = '문서 정보가 수정되었습니다.';
        return redirect()->route(
            'admin.page.document.edit', $documentID
        )->with('message', $message);
    }

    /**
     * 문서 삭제
     * @method DELETE
     * @see /admin/page/document/destroy
     */
    public function destroy(Request $request)
    {
        try {

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

            if ($chk) {
                foreach ($chk as $documentID) {
                    $document = $this->documentModel->findOrNew($documentID);

                    if(!$document->exists)
                    {
                        throw new Exception($documentID . "번 문서는 존재하지 않습니다.");
                    }

                    // 이미지 삭제
                    $this->deleteImageFromContent($document->content);

                    $document->delete();
                }
            }

            $message = '문서 정보가 삭제되었습니다.';
            return redirect()->route('admin.page.document.index')->with('message', $message);
        } catch (Exception $e) {
            return back()->withErrors($e->getMessage())->withInput();
        }
    }
}
