<?php
namespace App\Http\Controllers\Frontend;

use App\Models\Page;
use App\Models\Setting;
use App\Models\PageCate;
use App\Models\CoreEvent;
use App\Models\ServiceRecord;
use Carbon\Carbon;
use Illuminate\Http\Request;

class HomeController extends FrontendController
{
    use \App\Traits\ControllerTrait;
    
    /**
     * 前台首页
     * @return Response
     */
    public function index()
    {
        $setting  = Setting::where('lang', 'single')->orWhere('lang', config('lang'))->lists('value', 'name');

        $seo['title']       = isset($setting['site_title']) && $setting['site_title'] ? $setting['site_title'] : isset_field(trans("language::system"), 'china')." ".isset_field($setting, 'meta_keywords')." ".isset_field(trans("language::system"), 'manu_supp')." - "
                            .isset_field($setting, 'title');
        $seo['keywords']    = isset_field($setting, 'meta_keywords');
        $seo['description'] = isset_field($setting, 'meta_description');

        if (str_contains($seo['description'], '{g}')) {
            $keywords = explode(',', str_replace('，', ',', $seo['keywords']));
            $seo['description'] = str_replace(['{g}', '{k1}', '{k2}', '{k3}'], [isset_field($setting, 'title'), $keywords[0] ?? '', $keywords[1] ?? '', $keywords[2] ?? ''], $seo['description']);
        }

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


     public function about()
    {
        $setting  = Setting::where('lang', 'single')->orWhere('lang', config('lang'))->lists('value', 'name');

        $seo['title']       = isset($setting['site_title']) && $setting['site_title'] ? $setting['site_title'] : isset_field(trans("language::system"), 'china')." ".isset_field($setting, 'meta_keywords')." ".isset_field(trans("language::system"), 'manu_supp')." - "
                            .isset_field($setting, 'title');
        $seo['keywords']    = isset_field($setting, 'meta_keywords');
        $seo['description'] = isset_field($setting, 'meta_description');

        if (str_contains($seo['description'], '{g}')) {
            $keywords = explode(',', str_replace('，', ',', $seo['keywords']));
            $seo['description'] = str_replace(['{g}', '{k1}', '{k2}', '{k3}'], [isset_field($setting, 'title'), $keywords[0] ?? '', $keywords[1] ?? '', $keywords[2] ?? ''], $seo['description']);
        }

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

     public function contact()
    {
        $setting  = Setting::where('lang', 'single')->orWhere('lang', config('lang'))->lists('value', 'name');

        $seo['title']       = isset($setting['site_title']) && $setting['site_title'] ? $setting['site_title'] : isset_field(trans("language::system"), 'china')." ".isset_field($setting, 'meta_keywords')." ".isset_field(trans("language::system"), 'manu_supp')." - "
                            .isset_field($setting, 'title');
        $seo['keywords']    = isset_field($setting, 'meta_keywords');
        $seo['description'] = isset_field($setting, 'meta_description');

        if (str_contains($seo['description'], '{g}')) {
            $keywords = explode(',', str_replace('，', ',', $seo['keywords']));
            $seo['description'] = str_replace(['{g}', '{k1}', '{k2}', '{k3}'], [isset_field($setting, 'title'), $keywords[0] ?? '', $keywords[1] ?? '', $keywords[2] ?? ''], $seo['description']);
        }

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



    public function page($path) 
    {
        $page = Page::with('description')->flag()->where('slug', $path)->first();

        if (!$page) {
            return response()->view('theme::404', ['message' => 'Page not found !'], 404);
        }
        $cate = PageCate::where('id', $page->pid)->first();
        $root = $cate->getRoot();
        $cateList = Page::with('description')->where('pid', $page->pid)->flag()->orderBy('orders', 'ASC')->get();
 
        $title = '';
        if ($page->description) {
            $title = $page->description->seo_title ?: $page->description->title;
        }
        
        $seo = self::meta($title, $page->description);
        
        return view('theme::page', compact('page', 'root', 'cateList', 'seo'));
    }

    public function eventSend(Request $request)
    {
        $request->merge(['lang' => config('lang')]);
        $data = $request->all();
        $data['ip'] = $request->getClientIp();
        $data['device'] = isMobile($request) ? 'mobile' : 'pc';

        $result = CoreEvent::create($data);

        $client = new \GuzzleHttp\Client(['timeout'  => 5.0]);
        $params['headers'] = [
            'x-requested-with' => 'XMLHttpRequest',
            'token'            => Setting::get('apptoken'),
        ];

        try {
            $response = $client->request('GET', config('setting.api_url').'/ip-country?ip=' . $data['ip'], $params);
            if ($response->getStatusCode() == 200) {
                $res = json_decode($response->getBody()->getContents(), true);
                $result->update(['country' => $res['country']]);
            }
        } catch (\Exception $e) {
            logger('exception ip-country log: '.$e->getMessage());
        }
    }

    public function service(Request $request)
    {
        $request->merge(['lang' => config('lang')]);
        $data = $request->all();
        $data['ip'] = $request->getClientIp();
        $data['type'] = 3;

        if (preg_match('/^(\+?\d{1,3}[-\s]?)?\d{3,17}$/', $data['content'])) {
            $data['type'] = 1;
        }

        if (preg_match('/^[^\x00-\x20\x7f-\xff]+@[^\x00-\x20\x7f-\xff\.]+\.[^\x00-\x20\x7f-\xff]+$/', $data['content'])) {
            $data['type'] = 2;
        }

        $result = null;
        if (ServiceRecord::where('ip', $data['ip'])->where('created_at', '>', Carbon::now()->startOfDay())->where('created_at', '<', Carbon::now()->endOfDay())->count() < 2) {
            $result = ServiceRecord::create($data);
        }

        if ($result) {
            return response()->json([
                'status' => 'success'
            ]);
        }

        return response()->json([
            'status' => 'error'
        ]);
    }
}
