<?php

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

use App\Helpers\ResponseConverter;
use App\Http\Controllers\Controller;
use App\Services\CallApiService;
use Illuminate\Pagination\LengthAwarePaginator;

class OrderController extends Controller
{
    private $callApiService;

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

    public function list()
    {
        $limit = (int)request('limit', 5);
        $page = (int)request('page', 1);
        $status = request('filter', '');

        $listType1Book = $this->callApiService->callApi([
            'url' => 'list-type1-book',
            'data' => [
                'Book' => [
                    [
                        'QueryVars' => [
                            'QueryName' => 'pro:shop/sorder',
                            'IsntPagination' => false,
                            'SimpleFilter' => $status === '' ? '' : "mx.status = '$status'"
                        ],
                        'ListType1Vars' => [
                            'OrderBy' => 'mx.sorder_no desc'
                        ],
                        'PageVars' => [
                            'Limit' => $limit,
                            'Offset' => ($page - 1) * $limit
                        ]
                    ],
                    [
                        'QueryVars' => [
                            'QueryName' => 'pro:shop/sorder-bd',
                            'IsntPagination' => true,
                            'SimpleFilter' => "",
                            'SubSimpleFilter' => "image_type = 'thumb'",
                        ],
                        'PageVars' => [
                            'Limit' => 100000
                        ]
                    ],
                ]
            ]
        ]);

//        dump($listType1Book);

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

        $orderCharge['count'] = collect($listType1Book['Book'][0]['Page'])->count();

        $hd = $listType1Book['Book'][0];
        $orderPage = ResponseConverter::joinFor($hd['Page'], $listType1Book['Book'][1]['Page']);
        $hd['Page'] = new LengthAwarePaginator($orderPage, $hd['PageVars']['QueryCnt'],
            $limit, $page, ['path' => request()->url()]);
//        dump($hd);

        return view('views.my-page.order-list', compact('orderCharge', 'hd'))->with('codeTitle', [
            "status('sorder')",
        ]);
    }
}
