<?php

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

use App\Http\Controllers\Controller;
use App\Services\CallApiService;
use App\Services\MessageSendService;
use Themes\Pro\point2u\app\Services\MsqMarketApiService;
use Unirest\Request;

class ContactUsController 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()
    {
        return view('views.contact-us');
    }

    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' => 7,
            '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' => '요청 사항'
            ],
        ];

        $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;
    }
}
