<?php

namespace App\Http\Controllers\Admin\Page\Banner;

use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\BannerGroup;
use App\Models\DTO\SearchData;
use Exception;

class GroupController extends Controller
{
    private BannerGroup $bannerGroupModel;

    public function __construct(BannerGroup $bannerGroup)
    {
        $this->bannerGroupModel = $bannerGroup;
    }

    /**
     * 배너 그룹 관리
     * @method GET
     * @see /admin/page/banner/group
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $bannerGroupData = $this->bannerGroupModel->data($params);

        if($bannerGroupData->rows > 0) {
            $num = listNum($bannerGroupData->total, $params->page, $params->perPage);
            foreach($bannerGroupData->list as $i => $row) {
                $row->num = $num++;
                $row->bannerCount = $row->banner->count();

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

        return view('admin.page.banner.group.index', [
            'actionURL' => route('admin.page.banner.group.store'),
            'bannerGroupData' => $bannerGroupData
        ]);
    }

    /**
     * 배너 그룹 저장
     * @method POST
     * @see /admin/page/banner/group
     */
    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|unique:tb_banner_group,name',
        ];

        $attributes = [
            'name' => '배너 위치명',
        ];

        $posts = $this->validate($request, $rules, [], $attributes);

        $this->bannerGroupModel->insert([
            'name' => $posts['name'],
            'ip_address' => IP_ADDRESS,
            'user_agent' => USER_AGENT,
            'updated_user_id' => null,
            'updated_at' => null,
            'created_at' => now()
        ]);

        $message = '배너 그룹이 등록되었습니다.';
        return redirect()->route('admin.page.banner.group.index')->with('message', $message);
    }

    /**
     * 배너 그룹 수정
     * @method PUT
     * @see /admin/page/banner/group/{pk}
     */
    public function update(Request $request)
    {
        $chk = $request->post('chk');
        $name = $request->post('name');

        if($chk) {
            foreach($chk as $groupID) {
                $updateData = [
                    'name' => ($name[$groupID] ?? ''),
                    'ip_address' => IP_ADDRESS,
                    'user_agent' => USER_AGENT,
                    'updated_user_id' => UID
                ];

                $rules = [
                    'name' => 'required|string',
                ];

                $attributes = [
                    'name' => '위치명',
                ];

                $validator = Validator::make($updateData, $rules, [], $attributes);
                if($validator->fails()) {
                    return back()->withErrors($validator)->withInput();
                }

                $this->bannerGroupModel->find($groupID)->update($updateData);
            }
        }

        $message = '배너 그룹 정보가 변경되었습니다.';
        return redirect()->route('admin.page.banner.group.index')->with('message', $message);
    }

    /**
     * 배너 그룹 삭제
     * @method DELETE
     * @see /admin/page/banner/group/destroy
     */
    public function destroy(Request $request)
    {
        try {

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

            if ($chk) {
                foreach ($chk as $bannerGroupID) {
                    $bannerGroup = $this->bannerGroupModel->findOrNew($bannerGroupID);

                    if(!$bannerGroup->exists)
                    {
                        throw new Exception($bannerGroupID . "번 배너 그룹은 존재하지 않습니다.");
                    }

                    if($bannerGroup->banner->count() > 0) {
                        throw new Exception($bannerGroupID . "번 배너 그룹은 삭제할 수 없습니다.");
                    }

                    $bannerGroup->delete();
                }
            }

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