<?php

namespace App\Http\Controllers\Admin\User\Dormant;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\UserDormantNotify;
use App\Models\DTO\SearchData;
use Exception;

class NotifyController extends Controller
{
    private UserDormantNotify $userDormantNotifyModel;

    public function __construct(UserDormantNotify $userDormantNotify)
    {
        $this->userDormantNotifyModel = $userDormantNotify;
    }

    /**
     * 휴면계정 관리 - 알림 발송 내역
     * @method GET|POST
     * @see /admin/user/dormant/notify
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->startDate = $request->get('start_date');
        $params->endDate = $request->get('end_date');

        $userDormantNotifyData = $this->userDormantNotifyModel->data($params);

        if($userDormantNotifyData->rows > 0) {
            $num = listNum($userDormantNotifyData->total, $params->page, $params->perPage);
            foreach($userDormantNotifyData->list as $i => $row) {
                $row->num = $num--;
                $row->lastLoginAt = dateBr($row->last_login_at, '-');
                $row->dormantAt = dateBr($row->dormant_at, '-');
                $row->createdAt = dateBr($row->created_at, '-');

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

        return view('admin.user.dormant.notify', [
            'userDormantNotifyData' => $userDormantNotifyData,
            'params' => $params
        ]);
    }

    /**
     * 휴면계정 관리 - 알림 발송 내역 삭제
     * @method POST
     * @see /admin/user/dormant/notify/destroy
     */
    public function destroy(Request $request)
    {
        try{

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

            if ($chk) {
                foreach ($chk as $notifyID) {
                    $notify = $this->userDormantNotifyModel->findOrNew($notifyID);

                    if(!$notify->exists) {
                        throw new Exception($notifyID . '번 알림은 존재하지 않습니다.');
                    }

                    $notify->delete();
                }
            }

            $message = '알림 발송 내역이 삭제되었습니다.';
            return redirect()->route('admin.user.dormant.notify.index')->with('message', $message);
        }catch(Exception $e) {
            return back()->withErrors($e->getMessage())->withInput();
        }
    }
}
