<?php

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

use App\Http\Controllers\Controller;
use App\Services\CallApiService;
use App\Services\Shop\ShippingChargeService;
use Carbon\Carbon;
use Unirest\Request;

class CheckoutController extends Controller
{
    private $callApiService;
    private $shippingChargeService;

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

    public function index()
    {
//        dd(session('member'));
//        dump(session()->getOldInput());
        $listType1Book = $this->callApiService->callApi([
            'url' => 'list-type1-book',
            'data' => [
                'Book' => [
                    [
                        'QueryVars' => [
                            'QueryName' => 'pro:shop/company-contact-bd',
                            'IsntPagination' => true,
                        ],
                        'ListType1Vars' => [
                            'OrderBy' => 'sort asc'
                        ],
                        'PageVars' => [
                            'Limit' => 100000
                        ]
                    ],
                    [
                        'QueryVars' => [
                            'QueryName' => 'pro:shop/company-destina-bd',
                            'IsntPagination' => true,
                        ],
                        'ListType1Vars' => [
                            'OrderBy' => 'sort asc'
                        ],
                        'PageVars' => [
                            'Limit' => 100000
                        ]
                    ],
                    [
                        'QueryVars' => [
                            'QueryName' => 'point2u::pro:shop/cart',
                            'SubSimpleFilter' => "image_type = 'thumb'",
                            'IsntPagination' => true,
                        ],
                        'PageVars' => [
                            'Limit' => 100000
                        ]
                    ],
                    [
                        'QueryVars' => [
                            'QueryName' => 'pro/setup',
                            'SimpleFilter' => "setup_code='shipping-charge' and is_default='1'",
                            'IsntPagination' => true,
                        ],
                        'PageVars' => [
                            'Limit' => 100000
                        ]
                    ],
                    [
                        'QueryVars' => [
                            'QueryName' => 'pro/setup',
                            'SimpleFilter' => "setup_code='remit-account'",
                            'IsntPagination' => true,
                        ],
                        'PageVars' => [
                            'Limit' => 100000
                        ]
                    ],
                    [
                        'QueryVars' => [
                            'QueryName' => 'pro/setup',
                            'SimpleFilter' => "setup_code='import-pg'",
                            'IsntPagination' => true,
                        ],
                        'PageVars' => [
                            'Limit' => 100000
                        ]
                    ],
                    [
                        'QueryVars' => [
                            'QueryName' => 'pro/setup',
                            'SimpleFilter' => "setup_code='shop-pay-method'",
                            'IsntPagination' => true,
                        ],
                        'PageVars' => [
                            'Limit' => 100000
                        ]
                    ],
                ]
            ]
        ]);

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

        // 아임포트pg 셋업
        $importPgSetup = json_decode($listType1Book['Book'][5]['Page'][0]['C1'], true);

        $cartList = $listType1Book['Book'][2]['Page'] ?? [];

        $allCartChecked = ! empty($cartList);
        foreach ($cartList as $cart) {
            if ($cart['C9'] === '0') {
                $allCartChecked = false;
            }
        }

        $checkedCartList = collect($cartList)->filter(function ($cart) {
            return $cart['C9'] === '1';
        });

        $checkoutCharge['point_payrate'] = $this->makeItemPointPayrate($checkedCartList);

        // 아이템 이름 구하기
        $checkoutCharge['item_name'] = '';
        $cartCount = $checkedCartList->count();
        if ($cartCount === 1) {
            $checkoutCharge['item_name'] = $cartList[0]['C4'];
        } else if ($cartCount > 1) {
            $checkoutCharge['item_name'] = $cartList[0]['C4'] . '외 ' . ($cartCount - 1) . '개';
        }

        // 배송비 구하기
        $checkoutCharge['sub_total'] = $checkedCartList->sum('C8');
        $checkoutCharge['charge_amt'] = $this->shippingChargeService->calc($listType1Book['Book'][3]['Page'][0], $checkoutCharge['sub_total']);
        $checkoutCharge['total'] = $checkoutCharge['sub_total'] + $checkoutCharge['charge_amt'];
//        $checkoutCharge['half_total'] = $checkoutCharge['total'] / 2;


        return view('views.shop.checkout',
            compact('listType1Book', 'checkoutCharge', 'allCartChecked', 'importPgSetup'))
            ->with('codeTitle', [
                "sort('company-contact-bd')", "sort('company-destina-bd')", "paymethod('sorder')", "situation('sorder')",
            ]);
    }

    public function store()
    {
//        dump(session('member'));
//        dd(request()->all());
        $cart =  $this->callApiService->callApi([
            'url' => 'list-type1-page',
            'data' => [
                'QueryVars' => [
                    'QueryName' => 'point2u::pro:shop/cart',
                    'SimpleFilter' => "mx.checked = '1'",
                    'SubSimpleFilter' => "image_type = 'thumb'",
                    'IsntPagination' => true,
                ],
                'PageVars' => [
                    'Limit' => 100000
                ]
            ],
        ]);

        if ($this->callApiService->verifyApiError($cart) || empty($cart['Page'])) {
            notify()->error($cart['body'] ?? '쇼핑카트가 비어있습니다', 'Error', 'bottomRight');
            return redirect()->route('checkout-failed');
        }

        $bdPage = collect($cart['Page'])->map(function ($cart) {
            return [
                'Id' => 0,
                'CartId' => $cart['Id'],
                'ItemId' => (int)$cart['C1'],
                'SorderPrc' => $cart['C6'],
                'SorderQty' => $cart['C7'],
                'SorderSum' => $cart['C8'],
                'SorderSupply' => '0',
                'SorderVat' => '0',
                'DiscountRate' => '0',
                'CurrPurchPrc' => '0',
                'CurrSalesPrc' => '0',
            ];
        })->toArray();

//        dd($bdPage);

        $status = request('status', '0');
        $situation = request('situation', '');

        $sorderBact = $this->callApiService->callApi([
            'url' => 'sorder-bact',
            'data' => [
                // 무통장 입금을 포함한 주문 성공
                'OkSuccess' => (bool)request('ok_success', false),
                // 무통장 입금을 제외한 결제 성공
                'OkPaid' => (bool)request('ok_paid', false),
                'HdPage' => [
                    [
                        'Id' => 0,
                        'BuyerId' => session('member')['MemberBuyerId'],
//                        'SgroupId' => session('member')['SgroupId'],
//                        'BranchId' => session('member')['BranchId'],
//                        'StorageId' => session('member')['StorageId'],
                        'DealTypeId' => 5,
                        'Status' => $status,
                        'Situation' => $situation,
                        'IsPro' => '1',
                        'CashAmt' => request('cash_amt', '0'),
                        'X1PayAmt' => request('x1_pay_amt'),
                        'X2PayAmt' => request('x2_pay_amt'),

                        'ShipContact' => request('ship_contact'),
                        'ShipMobile' => request('ship_mobile'),
                        'ShipFee' => request('ship_fee'),
                        'ShipZipCode' => request('ship_zip_code'),
                        'ShipAddr1' => request('ship_addr1'),
                        'ShipAddr2' => request('ship_addr2'),
                        'Paymethod' => request('paymethod'),
                        'RemitName' => request('remit_name', ''),
                        'RemitAccount' => request('remit_account', ''),
                    ]
                ],
                'BdPage' => $bdPage
            ]
        ]);

        switch ($status) {
            case 'F':
                notify()->error(request('situation_title', 'Error'), 'Error', 'bottomRight');
                return redirect()->route('checkout-failed');
            default;
                break;
        }

        if ($this->callApiService->verifyApiError($sorderBact)) {
            notify()->error($sorderBact['body'], 'Error', 'bottomRight');
            return redirect()->route('checkout-failed');
        }

        notify()->success(_e('Action completed'), 'Success', 'bottomRight');
        return redirect()->route('checkout-ok')->with(['sorder_id' => $sorderBact['HdPage'][0]['Id']]);
    }

    function makeItemPointPayrate($cartList)
    {
        return collect($cartList)->reduce(function ($total, $cart) {
            $p2uPercentA = (int)$cart['C11'] === 0 ? 50 : $cart['C11'];
            $msqxpPercentA = (int)$cart['C11'] === 0 ? 50 : $cart['C12'];

            $p2uPercentB = (int)$cart['C13'] === 0 ? 30 : $cart['C13'];
            $cashPercentB = (int)$cart['C13'] === 0 ? 70 : $cart['C14'];

            $result = [
                'crypto1' => [
                    'p2up' => (int)($total['crypto1']['p2up'] + ($p2uPercentA * 0.01) * $cart['C6'] * $cart['C7']),
                    'msqxp' => (int)($total['crypto1']['msqxp'] + ($msqxpPercentA * 0.01) * $cart['C6'] * $cart['C7']),
                ],
                'crypto2' => [
                    'p2up' => (int)($total['crypto2']['p2up']  + ($p2uPercentB * 0.01) * $cart['C6'] * $cart['C7']),
                    'cash' => (int)($total['crypto2']['cash']  + ($cashPercentB * 0.01) * $cart['C6'] * $cart['C7']),
                ]
            ];

            return $result;
        }, 0);
    }
}
