<?php

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

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

class PrivacyController extends Controller
{
    private $callApiService;

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

    public function index()
    {
        $limit = (int)request('limit', 10);
        $page = (int)request('page', 1);

        $policyPage = $this->callApiService->callApi([
            'url' => 'simple-join-page',
            'data' => [
                'QueryVars' => [
                    'QueryName' => 'post-member-user',
                    'SimpleFilter' => "post_type_id = 12 and mx.status = '0'"
                ],
                'PageVars' => [
                    'Desc' => 'Id',
                    'Limit' => $limit,
                    'Offset' => ($page - 1) * $limit
                ]
            ]
        ]);

        $policy = $policyPage['Page'][0];
        if (empty($policy)) {
            notify()->error(__('개인정보 보호정책이 존재하지 않습니다'), 'Error', 'bottomRight');
            return redirect()->back();
        }

        if (empty($policy['PostSlug'])) {
            $key = $policy['Id'];
        } else {
            $key = $policy['PostSlug'];
        }

        return redirect()->route('privacy.show', $key);
    }

    public function show($slug)
    {
        $postPick = $this->pickPost([ 'PostSlug' => $slug ]);

        if ($this->callApiService->verifyApiError($postPick)) {
            $postPick = $this->pickPost([ 'Id' => (int)$slug ]);
        }
        if ($this->callApiService->verifyApiError($postPick)) {
            return redirect()->back();
        }

        $post = $postPick['Page'][0];

        if ($post['Status'] === '1') {
            notify()->error(__('개인정보 보호정책이 존재하지 않습니다'), 'Error', 'bottomRight');
            return redirect()->back();
        }

        $policyPage = $this->callApiService->callApi([
            'url' => 'simple-join-page',
            'data' => [
                'QueryVars' => [
                    'QueryName' => 'post-member-user',
                    'SimpleFilter' => "post_type_id = 12 and mx.status = '0'"
                ],
                'PageVars' => [
                    'Desc' => 'Id',
                    'Limit' => 9999,
                    'Offset' => 0
                ]
            ]
        ]);


        $currKey = collect($policyPage['Page'])->search(function($policy) use ($post) {
            return $policy['Id'] === $post['Id'];
        });

        $title = __('개인정보 보호정책');

        //dd(count($policyPage['Page']));
        return view('views.policy-or-privacy', compact('policyPage', 'currKey', 'post', 'title'));
    }

    public function pickPost($page)
    {
        return $this->callApiService->callApi([
            'url' => 'post-pick',
            'data' => [
                'Page' => [ $page ],
            ]
        ]);
    }
}
