<?php

namespace App\Http\Controllers\Admin\User\Log\Login;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\DTO\SearchData;
use App\Models\User;
use App\Models\LoginLog;

class LogController extends Controller
{
    private User $userModel;
    private LoginLog $loginLogModel;

    public function __construct(User $user, LoginLog $loginLogModel)
    {
        $this->userModel = $user;
        $this->loginLogModel = $loginLogModel;
    }

    /**
     * 로그인 이력 관리
     * @method GET
     * @see /admin/user/log/login
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $userLoginLogData = $this->loginLogModel->data($params);

        if ($userLoginLogData->rows > 0) {
            $num = listNum($userLoginLogData->total, $params->page, $params->perPage);
            foreach ($userLoginLogData->list as $i => $row) {
                $row->num = $num--;
                $row->createdAt = dateBr($row->created_at);
                $userLoginLogData->list[$i] = $row;
            }
        }

        return view('admin.user.log.login.index', [
            'userLoginLogData' => $userLoginLogData,
            'params' => $params
        ]);
    }

    /**
     * 로그인 이력 삭제
     * @method DELETE
     * @see /admin/user/log/login/destroy
     */
    public function destroy(Request $request)
    {
        $chk = $request->post('chk');

        if ($chk) {
            foreach ($chk as $logID) {
                $this->loginLogModel->find($logID)->delete();
            }
        }

        $message = '로그인 이력 정보가 삭제되었습니다.';
        return redirect()->route('admin.user.log.login.index')->with('message', $message);
    }
}
