<?php

namespace App\Http\Controllers\Frontend;

use Cache;
use Carbon\Carbon;
use App\Models\Message;
use App\Models\Product;
use App\Models\Setting;
use App\Models\CoreEvent;
use Illuminate\Http\Request;

class MessageController extends FrontendController
{
    use \App\Traits\ControllerTrait;

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $title = self::title('message', 'system');

        $product = null;
        $productId = $request->input('product_id');
        if ($productId && $productId > 0) {
            $product = Product::with('description')->where('id', $productId)->flag()->first();
            if ($product->description->title) {
                $title = $product->description->title. ' - ' . $title;
            }
        }
        $seo   = self::meta($title);

        return view('theme::message', compact('seo', 'product'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function store(Request $request)
    {
        $web = trans("language::web");
        $str = trans("language::system.no_null");
        $config = Setting::where('lang', 'single')->lists('value', 'name');
        $messageVerifyType = $config['message_verify_type'] ?? 1;
        $systems = trans("language::system");

        if ($messageVerifyType == 1) {
            $this->validate($request, [
                'email'   => 'required|email',
                'captcha' => 'required|captcha:' . $request->get('key', 'default') . ',math',
            ],[
                'email.required'       => (isset($web['email']) ? $web['email'] : '' . 'E-mail') . ' ' . $str,
                'captcha.required'     => (isset($web['captcha']) ? $web['captcha'] : '' . 'Captcha') . ' ' . $str,
                'email.email'          => 'E-mail format is wrong',
                'captcha.captcha'      => 'Captcha is wrong',
            ]);
        } else {
            $this->validate($request, [
                'email'   => 'required|email',
                'g-recaptcha-response' => 'required',
            ],[
                'email.required'       => (isset($web['email']) ? $web['email'] : '' . 'E-mail') . ' ' . $str,
                'g-recaptcha-response.required' => 'Please verify with the machine',
                'email.email'          => 'E-mail format is wrong',
            ]);

            $reCaptchaSecret = $config['re_captcha_secret'] ?? null;

            if (!$reCaptchaSecret) {
                return back()->withInput()->with('error', $systems['message_error']);
            }

            $client = new \GuzzleHttp\Client(['timeout' => 10.0]);

            try {
                $res = $client->request('POST', config('system.re_captcha_url').'/recaptcha/api/siteverify', [
                    'form_params' => [
                        'secret' => $reCaptchaSecret,
                        'response' => $request->input('g-recaptcha-response'),
                        'remoteip' => $request->getClientIp()
                    ]
                ]);

                $content = json_decode($res->getBody()->getContents(), true);

                if (!$content['success']) {
                    return back()->withInput()->with('error', $systems['message_error']);
                }
            } catch (\Exception $e) {}
        }

        $cacheKey = Carbon::now()->format('Y-m-d') . $request->getClientIp();
        $cacheNum = Cache::get($cacheKey) ?: 0;

        // 单个 ip 每天超过 4 次不允许继续提交留言
        if ($cacheNum >= 4) {
            return back()->withInput()->with('error', $systems['message_error']);
        }

        $request->merge(['lang' => config('lang')]);
        $data = $request->all();
        $data['ip'] = $request->getClientIp();
        $data['referer'] = $request->server('HTTP_REFERER');
        $result  = Message::create($data);

        if ($result) {
            Cache::put($cacheKey, $cacheNum + 1, 60 * 24);
            $coreEvent = CoreEvent::create([
                'lang' => $data['lang'],
                'event' => 'form_submit',
                'device' => isMobile($request) ? 'mobile' : 'pc',
                'ip' => $data['ip']
            ]);
            event(new \App\Events\MessageEvent($result, $coreEvent));

            if ($config['wx_push'] == 1) {
                $client = new \GuzzleHttp\Client();
                $client->post(config('setting.api_url') . '/wechat-message', [
                    'headers' => [
                        'token' => $config['apptoken'],
                        'Accept' => 'application/json'
                    ],
                    'form_params' => [
                        'type' => 3,
                        'title' => '询盘通知',
                        'name' => $data['name'],
                        'contact' => $data['phone']
                    ]
                ]);
            }

            return redirect($data['referer'])->with('success', $systems['message_success']);
        }

        return back()->withInput()->with('error', $systems['message_error']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
