<?php

namespace Themes\Pro\modunawa\app\Http\Controllers\Shop;

use App\Http\Controllers\Controller;
use App\Services\CallApiService;

class CartController extends Controller
{
    private $callApiService;

    public function __construct(CallApiService $callApiService)
    {
        $this->callApiService = $callApiService;
    }

    public function store()
    {
        if (empty(request('item_id'))) {
            notify()->error('상품을 선택해주세요', 'Error', 'bottomRight');
            return redirect()->back();
        }

        if ((int)request('cart_qty') < 1) {
            notify()->error('수량 에러', 'Error', 'bottomRight');
            return redirect()->back();
        }

        $item = $this->callApiService->callApi([
            'url' => 'item-pick',
            'data' => [
                'Page' => [
                    ['Id' => (int)request('item_id') ]
                ]
            ],
        ])['Page'][0];

        $cartPick = $this->callApiService->callApi([
            'url' => 'cart-pick',
            'data' => [
                'Page' => [
                    ['ItemId' => (int)request('item_id'), 'MemberBuyerId' => session('member')['MemberBuyerId'] ]
                ]
            ],
        ]);

        if ($this->callApiService->verifyApiError($cartPick)) {
            $id = 0;
            $cartQty = (int)request('cart_qty');
        } else {
            $cart = $cartPick['Page'][0];
            $id = $cart['Id'];
            $cartQty = (int)$cart['CartQty'] + request('cart_qty');
        }
        $cartAmt = $item['SalesPrc'] * $cartQty;

        $response = $this->callApiService->callApi([
            'url' => 'cart-act',
            'data' => [
                'Page' => [
                    [
                        'Id' => $id,
                        'ItemId' => $item['Id'],
                        'Checked' => '0',
                        'CartQty' => (string)$cartQty,
                        'CartPrc' => (string)$item['SalesPrc'],
                        'CartAmt' => (string)$cartAmt,
                    ]
                ]
            ],
        ]);

//        dd($response);

        if ($this->callApiService->verifyApiError($response)) {
            notify()->error($response['body'], 'Error', 'bottomRight');
            return redirect()->back();
        }

        notify()->success(_e('Action completed'), 'Success', 'bottomRight');

        if (request('purchase')) {
            return redirect()->route('checkout.index');
        }
        return redirect()->back();
    }
}
