<?php

class GoogleMerchantTest {

    protected $service;
    protected $merchantId = 5752724;
    //dev merchant id //153027410;
    protected $developerKey = 'a537a80524a0fa0716ba9f0efa110373c4440776';
    // dev api //'99c7997e063cb9e5546ee34224b3a8f9587dd9c7'; // private_key_id
    protected $appCredencials = 'content-api-key.json';

    protected $productDimensionUnit = 'cm';
    protected $productWeightUnit = 'kg';
    protected $productChannel = 'online';
    protected $productLanguage = 'en';
    protected $productCountry = 'US';
    protected $productCurrency = 'USD';
    protected $productAvailability = 'in stock';
    protected $productAvailabilityInStock = 'in stock';
    protected $productAvailabilityOutStock = 'out of stock';
    protected $productLink = 'https://securitybestbuy.com/prod_image/';//'http://szsb-gl2x.accessdomain.com/test-google-merchant/';

    public function __construct() {
        putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $this->appCredencials);

        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->setDeveloperKey($this->developerKey);
        $client->addScope(Google_Service_ShoppingContent::CONTENT);

        $this->service = new Google_Service_ShoppingContent($client);
    }
    
    // public function edit($productData) {
    //     $editData = new Google_Service_ShoppingContent_Product([
    //         'title' => $productData['mpn'],
    //         'mpn' => $productData['mpn'],
    //         'gtin' => $productData['ean'],
    //         'link' => $this->productLink,
    //         'description' => $productData['description'],
    //         'contentLanguage' => $this->productLanguage,
    //         'targetCountry' => $this->productCountry,
    //         'channel' => $this->productChannel,
    //         'availability' =>($productFeed['status'] != VendorNormalized::PRODUCT_STATUS_EOL) 
    //             ? $this->productAvailabilityInStock : $this->productAvailabilityOutStock,
    //         'price' => [
    //             'value' => (float) $productData['sbb_price'],
    //             'currency' => $this->productCurrency
    //         ],
    //         'sellOnGoogleQuantity' => $productData['quantity'],
    //         'shippingLength' => array(
    //             'value' => (float) $productData['length'],
    //             'unit' => $this->productDimensionUnit
    //         ),
    //         'shippingHeight' => array(
    //             'value' => (float) $productData['height'],
    //             'unit' => $this->productDimensionUnit
    //         ),
    //         'shippingWidth' => array(
    //             'value' => (float) $productData['width'],
    //             'unit' => $this->productDimensionUnit
    //         ),
    //         'shippingWeight' => array(
    //             'value' => (float) $productData['weight'],
    //             'unit' => $this->productWeightUnit
    //         ),
    //         'customAttributes' => array(array(
    //             'name' => 'sku',
    //             'value' => $productData['sku']
    //         ))
    //     ]);

    //     $editData['offerId'] = $productData['id'];

    //     $result = $this->service->products->insert($this->merchantId, $editData);
    
    //     return $result;
    // }

    public function batchGetProductStatus(){
        $res = $this->service->productstatuses->listProductstatuses(5752724, array('maxResults' => 250));
        return $res;
    }
    public function batchInsertEditData($productFeeds, $params = []) {

        $batchData = [];
        foreach ($productFeeds as $productFeed) {
        	/*$res = $this->service->products->listProducts($this->merchantId, array(
        		'maxResults' => 500,
        	));*/
            $productId = (!empty($productFeed['platform_3_rest_id'])) ? $productFeed['platform_3_rest_id'] : 'online:en:US:'.$productFeed['platform_1_rest_id'];
            //Dev::pvx($this->service->products->listProducts($this->merchantId));

            $brandName = Vendor::getVendorNameLabel($productFeed['vendor_id']);
            $tmpData = array(
                'batchId' => $productFeed['id'],
                'merchantId' => $this->merchantId,
                'method' => 'insert',
                'product' => array(
                    'brand' => $productFeed['brand'],
                    'title' => $productFeed['mpn']. ' - securitybestbuy',
                    'mpn' => $productFeed['mpn'],
                    'gtin' => $productFeed['ean'],
                    'link' => isset($productFeed['link']) ? $productFeed['link'] : '',
                    //'imageLink' => Yii::app()->params['SBB_ProductImages_Url'].$brandName.'/'.$productFeed['id'].'.png',
                    // dev latest 
                    //'imageLink' => Yii::app()->params['SBB_ProductImages_Url'].$brandName.'/'.$productFeed['id'].'.png',
                    //'imageLink' => 'http://szsb-gl2x.accessdomain.com/gss-price-updater/index.php/site/image/name/'. substr(md5(rand()), 1, 10) .'.png',
                    //'imageLink' => 'https://szsb-gl2x.accessdomain.com/sbb-2019-dev/wp-content/uploads/woocommerce-placeholder-2.png',
                    //'imageLink' => 'http://szsb-gl2x.accessdomain.com/gss-price-updater/images/product_default/'. substr(md5(rand()), 1, 8) .'.png',
                    'description' => $productFeed['description'],
                    'contentLanguage' => $this->productLanguage,
                    'targetCountry' => $this->productCountry,
                    'channel' => $this->productChannel,
                    'condition' => 'new',
                    'availability' => (string) ($productFeed['product_status'] != Product::PRODUCT_STATUS_EOL) 
                        ? $this->productAvailabilityInStock : $this->productAvailabilityOutStock,
                    'price' => [
                        'value' => $productFeed['sbb_price'],
                        'currency' => $this->productCurrency
                    ],
                    // 'sellOnGoogleQuantity' => $productFeed['quantity'],
                    'shippingLength' => array(
                        'value' => (float) $productFeed['length'],
                        'unit' => $this->productDimensionUnit
                    ),
                    'shippingHeight' => array(
                        'value' => (float) $productFeed['height'],
                        'unit' => $this->productDimensionUnit
                    ),
                    'shippingWidth' => array(
                        'value' => (float) $productFeed['width'],
                        'unit' => $this->productDimensionUnit
                    ),
                    'shippingWeight' => array(
                        'value' => (float) $productFeed['weight'],
                        'unit' => $this->productWeightUnit
                    ),
                    // 'customAttributes' => array(array(
                    //     'name' => 'sku',
                    //     'value' => $productFeed['sku']
                    // ))
                )
            );
            
            // if (!empty($productFeed['rest_id_google_merchant'])) {
            //     $tmpData['product']['offerId'] = (string) $productFeed['rest_id_google_merchant'];
            // } else {
            $tmpData['product']['offerId'] = $productFeed['platform_1_rest_id'];
            //}
            if (!empty($params['sbb_product_images']) && $params['sbb_product_images'][$productFeed['id']]) {
                $tmpData['product']['imageLink'] = $params['sbb_product_images'][$productFeed['id']];
            }

            try{
                $res = $this->service->products->get($this->merchantId, $productId);
                $description = (!$res && strlen($res->description) >= strlen($productFeed['description'])) ? $res->description : $productFeed['description'];
                $tmpData['product']['description'] = $description;

                if(!empty($res->imageLink) && empty($params['sbb_product_images']) && !$params['sbb_product_images'][$productFeed['id']]);
                    $tmpData['product']['imageLink'] = $res->imageLink;


            }catch(Google_Service_Exception $e){

            }

            if(!isset($tmpData['product']['imageLink']))
                $tmpData['product']['imageLink'] = Yii::app()->params['SBB_ProductImages_Url'].$brandName.'/'.$productFeed['mpn'].'.jpg';
            
            $batchData[] = $tmpData;
        }

        $customBatchRequest = new Google_Service_ShoppingContent_ProductsCustomBatchRequest;
        $customBatchRequest->setEntries($batchData);

        $result = $this->service->products->custombatch($customBatchRequest);
        
        return $result;
    }

    public function batchDelete($productFeeds) {
        $batchData = [];

        foreach ($productFeeds as $productFeed) {
            $batchData[] = array(
                'batchId' => $productFeed['id'],
                'merchantId' => $this->merchantId,
                'method' => 'delete',
                'productId' => $productFeed['platform_3_rest_id']
            );
        }

        $customBatchRequest = new Google_Service_ShoppingContent_ProductsCustomBatchRequest;
        $customBatchRequest->setEntries($batchData);

        $result = $this->service->products->custombatch($customBatchRequest);
        
        return $result;
    }
}