<?php

namespace Themes\kbgolf\pro\app\Http\Controllers\Page;

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

class SiseController extends Controller
{
    private $callApiService;

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

    public function index($siseType, $area=null, $memberbershipname=null)
    {

        // siseType별로 title 변수 생성
        switch ($siseType) {
            case 'golf':
                $title_dir = "골프";
                $title = "골프회원권 시세";
                break;
            case 'condo':
                $title_dir = "콘도";
                $title = "콘도회원권 시세";
                break;
            default:
                $title_dir = "휘트니스";
                $title = "휘트니스회원권 시세";
        }

        $query = "post_type_id = 59 and pc1='$siseType'";
        if($area){
            if($area != 'all'){
                $query .= " and pc2='$area'";
            }
        }
        if($memberbershipname){
            $query .= " and postTitle like '%$memberbershipname%'";
        }
        // dd($query);
        $limit = (int)request('limit', 4);
        $page = (int)request('page', 1);

        // api 호출 request
        $siseList = $this->callApiService->callApi([
            'url' => 'post-page',
            'data' => [
                'PageVars' => [
                    'Query' => $query,
                    'Desc' => 'created_on',
                    'Limit' => $limit,
                    'Offset' => ($page - 1) * $limit
                ]
            ]
        ]);

        // dd($siseList);

        // 등락 계산
        if (isset($siseList['Page']) && !empty($siseList['Page'])) {
            foreach ($siseList['Page'] as &$sise) {
                if (isset($sise['Pc3'], $sise['Pc4'])) {
                    $sise['fluctuation'] = (float)$sise['Pc3'] - (float)$sise['Pc4'];
                } else {
                    $sise['fluctuation'] = 0;
                }
            }
        }

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

        // pagenation
        $totalcnt = $siseList['PageVars']['QueryCnt'];
        $siseItems['Page'] = new LengthAwarePaginator(
            $siseList['Page'],
            $totalcnt,
            $limit,
            $page,
            ['path' => request()->url()]
        );

        return view('views.page.sise', compact('siseList', 'siseItems', 'title', "title_dir", "siseType", "area"));
    }

}
