<?php

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

use App\Facades\ProApiCacheFacade;
use App\Helpers\ResponseConverter;
use App\Helpers\Utils;
use App\Http\Controllers\Controller;
use App\Services\CallApiService;
use Illuminate\Http\Request;
// use Illuminate\Support\Facades\Request;

class IndexController extends Controller
{
    private $callApiService;

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

    public function index()
    {
        $contactSuccess = session()->has('contactSuccess');
        $connectionDevice = session()->get('ConnectionDevice');
        $response = ProApiCacheFacade::getCachedResponse('list-type1-book', 'list-type1/home-book');

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

        $widgetTaxo = $response['Book'][0]['Page'];
        $maMainSlider = ProApiCacheFacade::filterWidgetTaxo($widgetTaxo, 'ma-main-slider', $connectionDevice);
        // dd($maMainSlider);

        date_default_timezone_set('Asia/Seoul');
        $today = date('Ymd');
        // $twoWeeksAgo = date('Ymd', strtotime('-2 weeks'));

        $seoHtml = Utils::getSeoHtml('main');

        // 가장 최근 시세 찾기
        $query = "post_type_id = 59";
        $limit = (int)request('limit', 1);
        $page = (int)request('page', 1);
        $recentSise = $this->callApiService->callApi([
            'url' => 'post-page',
            'data' => [
                'PageVars' => [
                    'Query' => $query,
                    'Desc' => 'pc6',
                    'Limit' => $limit,
                    'Offset' => ($page - 1) * $limit
                ]
            ]
        ]);

        // dd($recentSise);

        $recentDate = '';
        foreach($recentSise['Page'] ?? [] as $recent){
            if ($recent) {
                $recentDate = $recent['Pc6'];
                $query .= " and Pc6 = '$recentDate'";
                // dd($query);
            }
        }

        // 메인에 뿌려질 최근 시세리스트
        $limit = (int)request('limit', 30);
        $page = (int)request('page', 1);
        $mainSiseList = $this->callApiService->callApi([
            'url' => 'post-page',
            'data' => [
                'PageVars' => [
                    'Query' => $query,
                    'Asc' => 'post_title',
                    'Limit' => $limit,
                    'Offset' => ($page - 1) * $limit
                ]
            ]
        ]);
        // dd($mainSiseList);

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

        // main yutube List
        $query = "(post_type_id = 40 or post_type_id = 43 or post_type_id = 46) and status ='1' and pt1 !=''";
        $limit = (int)request('limit', 300);
        $page = (int)request('page', 1);
        $mainYoutubeList = $this->callApiService->callApi([
            'url' => 'post-page',
            'data' => [
                'PageVars' => [
                    'Query' => $query,
                    'Desc' => 'created_on',
                    'Limit' => $limit,
                    'Offset' => ($page - 1) * $limit
                ]
            ]
        ]);

        $youtubeTypes = [
            'Page' => [
                'golf' => [],
                'condo' => [],
                'fitness' => []
            ]
        ];

        foreach($mainYoutubeList['Page'] ?? [] as $mainYoutube){
            // dd($mainYoutube);
            if (isset($mainYoutube['PostTypeId'])) {
                $postTypeId = $mainYoutube['PostTypeId'];
                switch ($postTypeId) {
                    case 40:
                        if (count($youtubeTypes['Page']['golf']) < 3) {
                            $youtubeTypes['Page']['golf'][] = $mainYoutube;
                        }
                        break;
                    case 43:
                        if (count($youtubeTypes['Page']['condo']) < 3) {
                            $youtubeTypes['Page']['condo'][] = $mainYoutube;
                        }
                        break;
                    case 46:
                        if (count($youtubeTypes['Page']['fitness']) < 3) {
                            $youtubeTypes['Page']['fitness'][] = $mainYoutube;
                        }
                        break;
                }
            }
        }
        // dd($youtubeTypes);
        // dd($mainYoutubeList);

        // main blog List
        $query = "(post_type_id = 41 or post_type_id = 44 or post_type_id = 50) and status ='1'";
        $limit = (int)request('limit', 999);
        $page = (int)request('page', 1);
        $mainBlogList = $this->callApiService->callApi([
            'url' => 'post-page',
            'data' => [
                'PageVars' => [
                    'Query' => $query,
                    'Desc' => 'created_on',
                    'Limit' => $limit,
                    'Offset' => ($page - 1) * $limit
                ]
            ]
        ]);

        $blogTypes = [
            'Page' => [
                'golf' => [],
                'condo' => [],
                'fitness' => []
            ]
        ];

        foreach($mainBlogList['Page'] ?? [] as &$mainBlog){
            if (isset($mainBlog['PostTypeId'])) {
                $postTypeId = $mainBlog['PostTypeId'];
                switch ($postTypeId) {
                    case 41:
                        if (count($blogTypes['Page']['golf']) < 3) {
                            $mainBlog['PostCode'] = 'golf-blog';
                            $blogTypes['Page']['golf'][] = $mainBlog;

                        }
                        break;
                    case 44:
                        if (count($blogTypes['Page']['condo']) < 3) {
                            $mainBlog['PostCode'] = 'condo-blog';
                            $blogTypes['Page']['condo'][] = $mainBlog;

                        }
                        break;
                    case 50:
                        if (count($blogTypes['Page']['fitness']) < 3) {
                            $mainBlog['PostCode'] = 'fitness-blog';
                            $blogTypes['Page']['fitness'][] = $mainBlog;
                        }
                        break;
                }
            }
        }

        // dd($blogTypes);
        // dd($mainBlogList);

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

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

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

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

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

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

        return view('views.index', compact('seoHtml', 'maMainSlider', 'mainSiseList', 'mainYoutubeList', 'youtubeTypes' ,'mainBlogList', 'blogTypes'));
    }
    // 시세 더보기
    public function loadMoreSise(Request $request)
    {
        $today = date('ymd');
        // dd($today);
        $query = "post_type_id = 59";
        $offset = (int) $request->query('offset', 0);
        $limit = (int) $request->query('limit', 12);
        $siseType = $request->query('siseType', 'golf');
        $siseDate = $request->query('siseDate', $today);
        if($siseType){
            if($siseType != 'golf'){
                $query .= " and pc5='$siseType' and pc6='$siseDate'";
            }else{
                $query .= " and pc5='$siseType'";
            }
        }
        // dd($query);

        $moreSiseList=$this->callApiService->callApi([
            'url' => 'post-page',
            'data' => [
                'PageVars' => [
                    'Query' => $query,
                    'Asc' => 'post_title',
                    'Limit' => $limit,
                    'Offset' => $offset
                ]
            ]
        ]);

        // 등락 계산
        if (isset($moreSiseList['Page']) && !empty($moreSiseList['Page'])) {
            foreach ($moreSiseList['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($moreSiseList)) {
            notify()->error($moreSiseList['body'], 'Error', 'bottomRight');
            return redirect()->back();
        }

        return $moreSiseList;
    }

    // 유튜브 더보기
    public function loadMoreYoutube(Request $request)
    {
        $query = "(post_type_id = 40 or post_type_id = 43 or post_type_id = 46) and status ='1' and pt!=''";
        $offset = (int) $request->query('offset', 0);
        $limit = (int) $request->query('limit', 12);

        $mainYoutubeList=$this->callApiService->callApi([
            'url' => 'post-page',
            'data' => [
                'PageVars' => [
                    'Query' => $query,
                    'Desc' => 'created_on',
                    'Limit' => $limit,
                    'Offset' => $offset
                ]
            ]
        ]);

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

    // 블로그 더보기
    public function loadMoreBlog(Request $request)
    {
        $query = "(post_type_id = 41 or post_type_id = 44 or post_type_id = 50) and status ='1'";
        $offset = (int) $request->query('offset', 0);
        $limit = (int) $request->query('limit', 12);

        $moreBlogList=$this->callApiService->callApi([
            'url' => 'post-page',
            'data' => [
                'PageVars' => [
                    'Query' => $query,
                    'Desc' => 'created_on',
                    'Limit' => $limit,
                    'Offset' => $offset
                ]
            ]
        ]);
        // post_code 만들기
        if (isset($moreBlogList['Page']) && !empty($moreBlogList['Page'])) {
            foreach ($moreBlogList['Page'] as &$mainBlog) {
                if (isset($mainBlog['PostTypeId'])) {
                    switch ($mainBlog['PostTypeId']) {
                        case 41:
                            $mainBlog['PostCode'] = 'golf-blog';
                            break;
                        case 44:
                            $mainBlog['PostCode'] = 'condo-blog';
                            break;
                        default:
                            $mainBlog['PostCode'] = 'fitness-blog';
                    }
                }
            }
        }

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