<?php

namespace Modules\Seo\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Modules\Seo\Models\BingSubmit;

class BingController extends Controller {

    public function cronSubmitUrl(Request $request) {
        $submited = BingSubmit::pluck('product_id')->toArray();
        $query = DB::table('product')->where('status', '=', 'ACTIVE')->select('id', 'slug');
        if (!empty($submited)) {
            $query->whereNotIn('id', $submited);
        }
        $products = $query->limit(Config::get('seo::bing.limit'))->get();
        $params = [
            'apikey' => Config::get('seo::bing.api_key')
        ];
        $dataSend = [
            'siteUrl' => Config::get('seo::bing.site_url'),
            'urlList' => []
        ];
        $routeName = Route::has('productShort') ? 'productShort' : 'product';
        $dataInsert = [];
        foreach ($products as $product) {
            array_push($dataSend['urlList'], route($routeName, ['slug' => $product->slug, 'id' => $product->id]));
            array_push($dataInsert, [
                'product_id' => $product->id,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        }
        $headers = [ 'Content-Type: application/json' ];
        $retVal = $this->triggerSyncRequest(Config::get('seo::bing.api_url') . '/SubmitUrlBatch?' . http_build_query($params), 'POST', $dataSend, $headers);

        if (array_key_exists('d', $retVal) && !empty($dataInsert)) {
            BingSubmit::insert($dataInsert);
        }
        return response()->json($retVal);
    }

    public function getUrlQuota(Request $request) {
        $params = [
            'siteUrl' => Config::get('seo::bing.site_url'),
            'apikey' => Config::get('seo::bing.api_key')
        ];
        $retVal = $this->triggerSyncRequest(Config::get('seo::bing.api_url') . '/GetUrlSubmissionQuota?' . http_build_query($params));
        return response()->json($retVal);
    }

}

?>