<?php

namespace App\Http\Controllers\Admin\Page;

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

class PopupController extends Controller
{
    use CommonTrait;

    private Popup $popupModel;

    public function __construct(Popup $popup)
    {
        $this->popupModel = $popup;
    }

    /**
     * 팝업 관리
     * @method GET
     * @see /admin/page/popup
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->activated = $request->get('activated');

        $popupData = $this->popupModel->data($params);

        if ($popupData->total > 0) {
            $num = listNum($popupData->total, $params->page, $params->perPage);
            foreach ($popupData->list as $i => $row) {
                $row->num = $num--;
                $row->deviceStr = MAP_DEVICE_TYPE[$row->device];
                $row->activatedStr = ($row->activated == '1' ? '활성' : '비활성');
                $row->creater = $row->user->find($row->user_id);
                $row->updater = $row->user->find($row->updated_user_id);
                $row->editURL = route('admin.page.popup.edit', $row->id);

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

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

    /**
     * 팝업 등록
     * @method GET
     * @see /admin/page/popup
     */
    public function create()
    {
        return view('admin.page.popup.write', [
            'actionURL' => route('admin.page.popup.store'),
            'popupData' => null,
            'popupID' => null
        ]);
    }

    /**
     * 팝업 수정
     * @method GET
     * @see /admin/page/popup/{pk}/edit
     */
    public function edit(int $popupID)
    {
        return view('admin.page.popup.write', [
            'actionURL' => route('admin.page.popup.update', $popupID),
            'popupData' => $this->popupModel->find($popupID),
            'popupID' => $popupID
        ]);
    }

    /**
     * 팝업 등록 저장
     * @method POST
     * @see /admin/page/popup
     */
    public function store(Request $request, FileLib $fileLib)
    {
        $rules = [
            'subject' => 'required|string',
            'start_date' => 'required|date',
            'end_date' => 'required|date',
            'is_center' => 'required|numeric|in:1,2',
            'left' => 'required_if:is_center,2|present',
            'top' => 'required_if:is_center,2|present',
            'width' => 'required|numeric',
            'height' => 'required|numeric',
            'device' => 'required|numeric|in:0,1,2',
            'disable_hours' => 'required|numeric',
            'activated' => 'required|in:0,1',
            'content' => 'string|nullable'
        ];

        $attributes = [
            'subject' => '제목',
            'start_date' => '시작일',
            'end_date' => '종료일',
            'is_center' => '화면 위치',
            'left' => '좌측 위치',
            'top' => '상단 위치',
            'width' => '가로 크기',
            'height' => '세로 크기',
            'device' => '표시기기',
            'disable_hours' => '닫기 유효시간',
            'activated' => '활성화 여부',
            'content' => '내용'
        ];

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

        $this->popupModel->insert([
            'user_id' => UID,
            'start_date' => $posts['start_date'],
            'end_date' => $posts['end_date'],
            'is_center' => $posts['is_center'],
            'left' => $posts['left'],
            'top' => $posts['top'],
            'width' => $posts['width'],
            'height' => $posts['height'],
            'device' => $posts['device'],
            'subject' => $posts['subject'],
            'content' => $posts['content'],
            'disable_hours' => $posts['disable_hours'],
            'activated' => $posts['activated'],
            'ip_address' => IP_ADDRESS,
            'user_agent' => USER_AGENT,
            'updated_user_id' => null,
            'updated_at' => null,
            'created_at' => now(),
        ]);

        $message = '팝업이 새로 등록되었습니다.';
        return redirect()->route('admin.page.popup.index')->with('message', $message);
    }

    /**
     * 팝업 수정 저장
     * @method PUT
     * @see /admin/page/popup/{pk}
     */
    public function update(Request $request, FileLib $fileLib)
    {
        $popupID = $request->post('popup_id');

        $rules = [
            'popup_id' => 'required|numeric|exists:tb_popup,id',
            'subject' => 'required|string',
            'start_date' => 'required|date',
            'end_date' => 'required|date',
            'is_center' => 'required|numeric|in:1,2',
            'left' => 'required_if:is_center,2|present',
            'top' => 'required_if:is_center,2|present',
            'width' => 'required|numeric',
            'height' => 'required|numeric',
            'device' => 'required|numeric|in:0,1,2',
            'disable_hours' => 'required|numeric',
            'activated' => 'required|in:0,1',
            'content' => 'string|nullable'
        ];

        $attributes = [
            'popup_id' => '번호',
            'subject' => '제목',
            'start_date' => '시작일',
            'end_date' => '종료일',
            'is_center' => '화면 위치',
            'left' => '좌측 위치',
            'top' => '상단 위치',
            'width' => '가로 크기',
            'height' => '세로 크기',
            'device' => '표시기기',
            'disable_hours' => '닫기 유효시간',
            'activated' => '활성화 여부',
            'content' => '내용'
        ];

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

        $this->popupModel->find($popupID)->update([
            'start_date' => $posts['start_date'],
            'end_date' => $posts['end_date'],
            'is_center' => $posts['is_center'],
            'left' => $posts['left'],
            'top' => $posts['top'],
            'width' => $posts['width'],
            'height' => $posts['height'],
            'device' => $posts['device'],
            'subject' => $posts['subject'],
            'content' => $posts['content'],
            'disable_hours' => $posts['disable_hours'],
            'activated' => $posts['activated'],
            'ip_address' => IP_ADDRESS,
            'user_agent' => USER_AGENT,
            'updated_user_id' => UID,
            'updated_at' => now()
        ]);

        $message = '팝업 정보가 수정되었습니다.';
        return redirect()->route('admin.page.popup.edit', $popupID)->with('message', $message);
    }

    /**
     * 팝업 삭제
     * @method DELETE
     * @see /admin/page/popup/destroy
     */
    public function destroy(Request $request)
    {
        try {

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

            if ($chk) {
                foreach ($chk as $popupID) {
                    $popup = $this->popupModel->findOrNew($popupID);

                    if(!$popup->exists)
                    {
                        throw new Exception($popupID . "번 팝업은 존재하지 않습니다.");
                    }

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

                    $popup->delete();
                }
            }

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