<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\View;
use App\Models\CoupangLib;
use App\Models\Visit;
use App\Models\SearchKeyword;

class MainController extends Controller
{
    protected CoupangLib $coupangLib;

    public function __construct(Request $request)
    {
        $this->coupangLib = new CoupangLib();

        $visit = new Visit();
        $visit->register($request); // 방문자 수 기록

        View::share('visitorTodayCount', $visit->todayCount());
        View::share('visitorYesterdayCount', $visit->yesterdayCount());
        View::share('visitorTotalCount', $visit->totalCount());
    }

    /**
     * 메인페이지
     */
    public function index()
    {
        $products = $this->coupangLib->getAllCoupangPL();
        $banners = [
            [
                'title' => '쿠팡',
                'href' => '4fC52',
                'src' => '594227?subId=&traceId=V0-301-879dd1202e5c73b2-I594227&w=728&h=90'
            ],
            [
                'title' => '골드박스',
                'href' => '4hyv3',
                'src' => '608229?subId=&traceId=V0-301-969b06e95b87326d-I608229&w=728&h=90'
            ],
            [
                'title' => '로켓와우',
                'href' => '4hyGv',
                'src' => '630877?subId=&traceId=V0-301-bae0f72e5e59e45f-I630877&w=728&h=90'
            ],
            [
                'title' => '로켓직구',
                'href' => '4hyLY',
                'src' => '630871?subId=&traceId=V0-301-50c6c2b97fba9aee-I630871&w=728&h=90'
            ],
            [
                'title' => '로켓 프레시',
                'href' => '4hyPc',
                'src' => '630888?subId=&traceId=V0-301-371ae01f4226dec2-I630888&w=728&h=90'
            ],
            [
                'title' => '로켓 패션',
                'href' => '4hyTb',
                'src' => '630872?subId=&traceId=V0-301-5a8c79a76485eb21-I630872&w=728&h=90'
            ],
            [
                'title' => '로켓 가전/디지털',
                'href' => '4hyXH',
                'src' => '683768?subId=&traceId=V0-301-5f9bd61900e673c0-I683768&w=728&h=90'
            ],
            [
                'title' => '로켓 도서',
                'href' => '4hy6s',
                'src' => '683764?subId=&traceId=V0-301-f5c692db558def48-I683764&w=728&h=90'
            ],
            [
                'title' => '로켓 홈인테리어',
                'href' => '4hzeh',
                'src' => '684135?subId=&traceId=V0-301-2f679fc6bd8f2e58-I684135&w=728&h=90'
            ],
            [
                'title' => '로켓 주방용품',
                'href' => '4hzuu',
                'src' => '684137?subId=&traceId=V0-301-2b8ef06377ec8f50-I684137&w=728&h=90'
            ]
        ];

        shuffle($banners);

        return view(layout('main'), [
            'products' => $products,
            'banners' => $banners
        ]);
    }

    /**
     * 쿠팡 상품 검색
     */
    public function search(Request $request, SearchKeyword $searchKeywordModel)
    {
        if (RateLimiter::tooManyAttempts('search:' . $request->ip(), 50)) {
            return '짧은 시간동안 너무 많은 요청을 하였습니다. 잠시 후 다시 시도해주세요.';
        }

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

        $products = [];
        if($keyword) {
            $products = $this->coupangLib->getSearch($keyword);

            $searchKeywordModel->insert([
                'keyword' => $keyword,
                'ip_address' => $request->ip(),
                'user_agent' => $request->userAgent(),
                'created_at' => now()
            ]);
        }

        return view(layout('search'), [
            'products' => $products,
            'keyword' => $keyword
        ]);
    }

    /**
     * 쿠팡 카테고리 별 Best 상품 조회
     */
    public function category(Request $request)
    {
        $categoryID = $request->route('categoryID');

        if (!$categoryID) {
            abort(400);
        }

        if(!array_key_exists($categoryID, CATEGORIES)) {
            abort(403);
        }

        $categories = $this->coupangLib->getBestCategories($categoryID);

        return view(layout('category'), [
            'categories' => $categories
        ]);
    }

    /**
     * 쿠팡 PL 조회
     * @see /recommend
     */
    public function recommend(Request $request)
    {
        $brandID = $request->route('brandID');

        if (!$brandID) {
            abort(400);
        }

        if(!array_key_exists($brandID, BRANDS)) {
            abort(403);
        }

        $recommend = $this->coupangLib->getCoupangPL($brandID);

        return view(layout('recommend'), [
            'recommend' => $recommend
        ]);
    }

    /**
     * 쿠팡 골드박스 상품 조회
     * @see /goldbox
     */
    public function goldBox()
    {
        $goldBox = $this->coupangLib->getGoldBox();

        return view(layout('goldBox'), [
            'goldBox' => $goldBox
        ]);
    }

    /**
     * 쿠팡 이벤트/프로모션
     * @see /event
     */
    public function event()
    {
        $event = array_reverse([
            1 => 'https://link.coupang.com/a/4cA18',
            2 => 'https://link.coupang.com/a/4cCEp',
            3 => 'https://link.coupang.com/a/4cCOa',
            4 => 'https://link.coupang.com/a/4cGuZ',
            5 => 'https://link.coupang.com/a/4cGzi',
            6 => 'https://link.coupang.com/a/4cGCW',
            7 => 'https://link.coupang.com/a/4cGGX',
            8 => 'https://link.coupang.com/a/4cGLN',
            9 => 'https://link.coupang.com/a/4cGQA',
            10 => 'https://link.coupang.com/a/4cGVd',
            11 => 'https://link.coupang.com/a/4cGX7',
            12 => 'https://link.coupang.com/a/4cGbT'
        ], true);

        return view(layout('event'), [
            'event' => $event
        ]);
    }
}
