<?php

namespace App\Http\Controllers\Admin;

use App\Models\Setting;
use App\Models\CollectMedia;
use Illuminate\Http\Request;

class GoogleController extends AdminController
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data['siteUrl'] = $request->getScheme() . '://' . secondaryDomain();
        $data['feedpath'] = $data['siteUrl'] . '/sitemap.xml';

        return view('admin.google_push.index', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $media = CollectMedia::orderByRaw("RAND()")->take(1)->first();
        $data = [];
        if ($media) {
            $data['img_path'] = $media->path;
        }
        v($data);

        $siteUrl = $request->getScheme() . '://' . secondaryDomain();
        $httpClient = new \GuzzleHttp\Client();

        $res = $httpClient->post(config('setting.api_url') . '/sitemap/push', [
            'headers' => [
                'token' => 'f1c70427661192277dfcc10357039b6b3827bf446cabd681602d7be6e9341082',
                'Accept' => 'application/json'
            ],
            'form_params' => [
                'siteUrl' => 'https://www.qlcold.com/',
                'feedpath' => 'https://www.qlcold.com/sitemap.xml'
            ]
        ]);

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

        try {
//            // Google站长推送
//            $res = $httpClient->post(config('setting.api_url') . '/sitemap/push', [
//                'headers' => [
//                    'token' => Setting::get('apptoken'),
//                    'Accept' => 'application/json'
//                ],
//                'form_params' => [
//                    'siteUrl' => $siteUrl,
//                    'feedpath' => $siteUrl . '/sitemap.xml'
//                ]
//            ]);

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

            if ($content->status == 'success') {
                return redirect('admin/google-push')->with('success', 'Google推送成功！');
            }
        } catch (\Exception $e) {

        }

        return back()->withInput()->with('error', '提交失败');
    }
}
