<?php

namespace app\controller;

use App\model\Ip2locationDb11Model;
use app\server\GuzzleServer;
use GuzzleHttp\RequestOptions;
use itbdw\Ip\IpLocation;
use support\Db;
use support\Request;

class Index
{

    public function test()
    {
        return json([
            'msg' => 'test'
        ]);
    }

    public function index(Request $request, $checkIp = null)
    {
        //$ip = $request->getRealIp();

        $header = $request->header();

        $ip = $header['x-real-ip'];

        if ($checkIp) {
            $ip = gethostbyname($checkIp);
        }

        $filepath = '/usr/src/myapp/lib/qqwry.dat';

        $location = IpLocation::getLocation($ip, $filepath);

        return json(['ip' => $ip, 'location' => $location]);
    }

    public function location(Request $request, $checkIp = null)
    {
        //$ip = $request->getRealIp();

        $header = $request->header();

        $ip = $header['x-real-ip'];

        if ($checkIp) {
            $ip = gethostbyname($checkIp);
        }

        $ipNum = ip2long($ip);


        $record = Ip2locationDb11Model::query()->where(
            'ip_from', '<=', $ipNum
        )->where(
            'ip_to', '>=', $ipNum
        )->first();

        if ($record) {
            $record = $record->toArray();
            $mapUrl = "https://www.google.com/maps/search/{$record['latitude']},{$record['longitude']}";
        } else {
            $record = [];
            $mapUrl = '';
        }

        return json(['ip' => $ip, 'record' => $record, 'map' => [
            'google' => $mapUrl
        ]], JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
    }

    public function translate(Request $request)
    {
        $p  = $request->get('p');
        $sl = $request->get('sl', 'auto');
        $tl = $request->get('tl', 'zh-cn');

        $client = GuzzleServer::getClient();

        $url = "https://clients5.google.com/translate_a/t?client=dict-chrome-ex&sl={$sl}&tl={$tl}&q={$p}";

        $proxyList = [
            0 => 'woon:woon@146.56.181.114:6666',
            1 => 'woon:woon@107.189.31.119:6666',
            2 => 'woon:woon@132.145.81.233:6666',
            3 => 'woon:woon@45.66.131.147:6666',
        ];

        $proxy = $proxyList[array_rand($proxyList)];

        $response = $client->post($url, [
            'timeout' => 10,
            'proxy'   => $proxy
        ]);

        $response = $response->getBody()->getContents();

        $responseArr = json_decode($response, true);

        return json($responseArr);

    }
}
