<?php

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

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

class ContactUsCustomController extends Controller
{
    private $callApiService;

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

    public function getSetup()
    {
        return $this->callApiService->callApi([
            'url' => 'setup-get',
            'data' => [
                'SetupCode' => 'contact-us',
                'BrandCode' => 'main',
                'LangType' => getLocale()
            ]
        ]);
    }

    public function index($id=null)
    {

        $query = "post_type_id = 58";
        $limit = (int)request('limit', 12);
        $page = (int)request('page', 1);

        if($id != null){
            $query .= " and mx.id = '$id'";
        }

        // dd($query);

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

        // date 포맷 변경
        if (isset($contactUsCustomList['Page']) && !empty($contactUsCustomList['Page'])) {
            foreach ($contactUsCustomList['Page'] as &$contactUsCustom) {
                if (isset($contactUsCustom['OfficialDate'])) {
                    $OfficialDate = DateTime::createFromFormat('Ymd', $contactUsCustom['OfficialDate']);
                    $date = $OfficialDate->format('Y.m.d');
                    $contactUsCustom['date'] = $date;
                }
                if(isset($contactUsCustom['Pc1'])){
                    $Pc1Length = mb_strlen($contactUsCustom['Pc1'], 'UTF-8');
                    if($Pc1Length > 2){
                        $contactUsCustom['maskedName'] = mb_substr($contactUsCustom['Pc1'], 0, $Pc1Length - 2, 'UTF-8') . 'OO';
                    }else{
                        $contactUsCustom['maskedName'] = mb_substr($contactUsCustom['Pc1'], 0, $Pc1Length - 1, 'UTF-8') . 'O';
                    }
                }
            }
        }

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

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

        return view('views.page.contactus-custom-list', compact('contactUsCustomList', 'contactUsCustomItems'));
    }

    public function store()
    {
        $rules = [
            'captcha' => 'required|captcha',
            'Pc2' => 'required|regex:/^010(?:-?\d{4}){2}$/',
        ];
        $validator = validator()->make(request()->all(), $rules);
        if ($validator->fails()) {
            notify()->error('보안 체크 숫자 입력이 틀렸습니다. 다시 올바르게 입력해서 문의하기 해주세요', 'Error', 'bottomRight');
            return redirect()->to('/contactus-custom')->withInput();
        }

        $request = array_merge([
            'Id' => 0,
            'PostTypeId' => 58,
            'Status' => '2',
            'MemberId' => session('member')['MemberId'] ?? 0,
        ], request()->all());

        $response = $this->callApiService->callApi([
            'url' => 'post-act',
            'data' => [
                'Page' => [
                    $request
                ]
            ],
        ]);

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

        $redirectTo = redirect()->to('/');

        $contactUs = $this->getSetup();
        $contactUs['Fields'] = [
            [
                'Name' => 'Pc1',
                'Caption' => '신청자 이름'
            ],
            [
                'Name' => 'Pc2',
                'Caption' => '연락처'
            ],
            [
                'Name' => 'Pc3',
                'Caption' => '거래 구분'
            ],
            [
                'Name' => 'Pc4',
                'Caption' => '회원권 구분'
            ],
            [
                'Name' => 'Pc5',
                'Caption' => '회원권명'
            ],
            [
                'Name' => 'Pc6',
                'Caption' => '희망 가격'
            ],
            [
                'Name' => 'Pt1',
                'Caption' => '요청 사항'
            ],
            [
                'Name' => 'Pc7',
                'Caption' => '상태'
            ],
        ];

        $msg = '[kbgolf] 고객지원 요청내용입니다.\n';
        foreach($contactUs['Fields'] ?? [] as $fields) {
            $msg .= $fields['Caption'] . ': ' . $request[$fields['Name']] . '\n';
        }

        if ($contactUs['OkMobile']) {
            $toMobiles = preg_replace('/\s+/', '', explode(',', $contactUs['ToMobile']));
            foreach($toMobiles ?? [] as $toMobile) {
                $this->messageSendService->send($msg, $msg, $toMobile);
            }
        }

        $toMails = preg_replace('/\s+/', '', explode(',', $contactUs['ToMail']));
        foreach($toMails ?? [] as $toMail) {
            \Mail::send('views.emails.contact-us', ['request' => $request, 'contactUs' => $contactUs],
                function ($message) use ($toMail) {
                    $message->to($toMail);

                    $message->subject('[kbgolf] 고객지원 요청내용입니다.');
                }
            );
        }

        notify()->success('성공적으로 문의하였습니다', 'Success', 'bottomRight');
        return $redirectTo;
    }
}
