<?php

class ProductController extends Controller
{
    public $layout = 'dashboard';
    public $activeSideNav = array('manage_products');
    public $pageTitle = 'Published Products';

    public function actionIndex()
    {
        $productdDataCriteria = new CDbCriteria;
        $productdDataCriteria->alias = 'pi';
        $productdDataCriteria->join = 'INNER JOIN {{product}} AS p ON p.id = pi.product_id';
        $productdDataCriteria->condition = 'p.status NOT IN (' . Product::STATUS_DELETED . ')';
        $productdDataCriteria->order = 'id DESC';
        $pagination = array('pageSize' => 50);
        $advanceSearchParams = array();

        if ($_SERVER['REQUEST_METHOD'] == 'GET') {
            if (!empty($_GET['search']['pageSize'])) {
                $advanceSearchParams['search']['pageSize'] = (int) trim($_GET['search']['pageSize']);
            }
            if (!empty($_GET['search']['vendor'])) {
                $advanceSearchParams['search']['vendor'] = (int) trim($_GET['search']['vendor']);
            }

            if (!empty($_GET['search']['mpn'])) {
                $advanceSearchParams['search']['mpn'] = (string) trim($_GET['search']['mpn']);
            }

            if (!empty($_GET['search']['description'])) {
                $advanceSearchParams['search']['description'] = (string) trim($_GET['search']['description']);
            }

            if (!empty($_GET['search']['sku'])) {
                $advanceSearchParams['search']['sku'] = (string) trim($_GET['search']['sku']);
            }

            if (!empty($_GET['search']['status'])) {
                $advanceSearchParams['search']['status'] = (int) trim($_GET['search']['status']);
            }

            if (!empty($_GET['search']['product_status'])) {
                $advanceSearchParams['search']['product_status'] = (int) trim($_GET['search']['product_status']);
            }

            if (!empty($_GET['batchId'])) {
                $advanceSearchParams['batchId'] = trim($_GET['batchId']);
            }

            if (isset($advanceSearchParams['search']['pageSize'])) {
                $pagination = array('pageSize' => $advanceSearchParams['search']['pageSize']);
            }

            if (isset($advanceSearchParams['search']['vendor'])) {
                $productdDataCriteria->addCondition('p.vendor_id = ' . $advanceSearchParams['search']['vendor']);
            }

            if (isset($advanceSearchParams['search']['mpn'])) {
                $productdDataCriteria->addCondition('pi.mpn LIKE "%' . $advanceSearchParams['search']['mpn'] . '%"');
            }

            if (isset($advanceSearchParams['search']['description'])) {
                $productdDataCriteria->addCondition('pi.description LIKE "%' . $advanceSearchParams['search']['description'] . '%"');
            }

            if (isset($advanceSearchParams['search']['sku'])) {
                $productdDataCriteria->addCondition('pi.sku LIKE "%' . $advanceSearchParams['search']['sku'] . '%"');
            }

            if (isset($advanceSearchParams['batchId'])) {
                $productdDataCriteria->addCondition('p.batch_id = "' . $advanceSearchParams['batchId'] . '"');
            }

            if (isset($advanceSearchParams['search']['product_status'])) {
                $productdDataCriteria->addCondition('p.product_status = "' . $advanceSearchParams['search']['product_status'] . '"');
            }

            if (isset($advanceSearchParams['search']['status'])) {
                if ($advanceSearchParams['search']['status'] == Product::STATUS_ACTIVE) {
                    $productdDataCriteria->addCondition('
						p.platform_1_rest_status IN (
						' . Product::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS . ')

						OR

						p.platform_2_rest_status IN (
						' . Product::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS . ')

						OR

						p.platform_3_rest_status IN (
						' . Product::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS . ')
					');
                } elseif ($advanceSearchParams['search']['status'] == Product::STATUS_ERROR) {
                    $productdDataCriteria->addCondition('
						p.platform_1_rest_status NOT IN (
						' . Product::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS . ')

						OR

						p.platform_2_rest_status NOT IN (
						' . Product::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS . ')

						OR

						p.platform_3_rest_status NOT IN (
						' . Product::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS . ',
						' . Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS . ')
					');
                }
            }
        }

        $productdDataProvider = new CActiveDataProvider('ProductInfo', array(
            'criteria' => $productdDataCriteria,
            'pagination' => $pagination
        ));

        $product = new Product;
        $productInfo = new ProductInfo;

        $productData = ProductInfo::model()->findAll($productdDataCriteria);
        $productIds = CHtml::listData($productData, 'product_id', 'product_id');

        $productCountPublish = Product::countPublishedData(['p_ids' => $productIds]);

		$cronAction = CronProductActionStatus::model()->find(array(
			'condition' => 'status = :status OR status = :status1',
			'params' => array(
				':status' => CronProductActionStatus::STATUS_IN_PROGRESS,
				':status1' => CronProductActionStatus::STATUS_COMPLETED
			),
			//'order' => 'id desc',
			'limit' => 1
		)); 

        $actionLogs = ActionLog::model()->findAll();
		$actionLogsProvider = new CArrayDataProvider($actionLogs, array(
			'pagination' => array('pageSize' => 10)
		));
        
        $batchId = isset($_GET['batchId'])
            ? str_replace('BTC', '', $_GET['batchId']) : '';

        $this->render('index', array(
            'productdDataProvider' => $productdDataProvider,
            'advanceSearchParams' => $advanceSearchParams,
            'product' => $product,
            'productInfo' => $productInfo,
            'productCountPublish' => $productCountPublish,
            'productIds' => $productIds,
            'batchId' => $batchId,
            'cronAction' => $cronAction,
            'actionLogsProvider' => $actionLogsProvider
        ));
    }

    public function actionGetPublisedData($id)
    {
        $data = ProductInfo::model()->find([
            'condition' => 'product_id = :product_id',
            'params' => [':product_id' => $id]
        ]);

        if (!$data) {
            throw new CHttpException(403, 'Invalid request.');
        }

        $responseData = $data->attributes;

        $responseData['price'] = ZCommon::formatWithDecimal($data['sbb_price']);
        $responseData['cost'] = ZCommon::formatWithDecimal($data['cost']);
        $responseData['msrp'] = ZCommon::formatWithDecimal($data['msrp']);
        $responseData['status'] = $data->product->status;

        echo CJSON::encode($responseData);
        exit;
    }

    public function actionDeleteData()
    {
        $productIds = !empty($_POST['product_ids'])
            ? $_POST['product_ids'] : '';

        if ($productIds == '') {
            echo CJSON::encode(array(
                'status' => 'error',
                'message' => 'Nothing to delete, No selected data.'
            ));
        }

        $error = 0;

        $productDeleteFeeds = [];

        foreach ($productIds as $productId) {
            $productData = Product::model()->findByPk($productId);

            if (!$productData->save(false)) {
                $error++;
                break;
            } else {
                $productDeleteFeeds[] = $productData->attributes;
            }
        }

        $cronAction = CronProductActionStatus::createNewCronProductAction(CronProductActionStatus::TYPE_DELETE,$productIds);
        if(!$cronAction){
        	$error++;
        }
        //product delete on woocommerce
        /*Product::apisBatchDeleteData($productDeleteFeeds, [
            'success_status' => Product::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS,
            'success_error' => Product::REST_STATUS_PUBLISH_DELETE_DATA_ERROR
        ]);*/

        // if (Yii::app()->params['website_published_product_switch'] == true) {
        // 	$googleMerchant = new GoogleMerchant;
        // 	$wooCommerce = new WooCommerce;

        // 	if (!empty($productDeleteFeeds)) {
        // 		// request item delete to api
        // 		$googleMerchBatchDelete = $googleMerchant->batchDelete($productDeleteFeeds);

        // 		// set item success status and report
        // 		foreach ($googleMerchBatchDelete as $googleMerchBatchDeleteData) {
        // 			$productDelete = Product::model()->findByPk($googleMerchBatchDeleteData->batchId);

        // 			if (!empty($googleMerchBatchDeleteData->batchId)) {
        // 				$productDelete->rest_id_google_merchant = null;
        // 				$productDelete->report_google_merchant = 'Delete Success';
        // 				$productDelete->save(false);
        // 			}
        // 		}

        // 		// request item delete to api
        // 		$batchDeleteWC = $wooCommerce->batchDelete($productDeleteFeeds);

        // 		// set item success status and report
        // 		if ($batchDeleteWC) {
        // 			foreach ($batchDeleteWC->delete as $batchDeleteWCData) {
        // 				if (!empty($batchDeleteWCData->id) && isset($batchDeleteWCData->attributes)) {
        // 					$productId = $batchDeleteWCData->attributes[0]->options[0];
        // 					$productDelete = Product::model()->findByPk($productId);

        // 					$productDelete->rest_id_woo_commerce = null;
        // 					$productDelete->report_woo_commerce = 'Delete Success';
        // 					$productDelete->save(false);
        // 				}
        // 			}
        // 		}

        // 		// set item error status and report
        // 		foreach ($productDeleteFeeds as $productDeleteFeed) {
        // 			$product = Product::model()->findByPk($productDeleteFeed['id']);

        // 			if (!empty($product->rest_id_google_merchant)) {
        // 				$product->report_google_merchant = 'API Delete error';
        // 			}

        // 			if (!empty($product->rest_id_woo_commerce)) {
        // 				$product->report_woo_commerce = 'API Delete error';
        // 			}

        // 			if (!empty($product->rest_id_woo_commerce) || !empty($product->rest_id_google_merchant)) {
        // 				$product->status = Product::STATUS_API_ERROR_DELETE;
        // 			}

        // 			$product->save(false);
        // 		}
        // 	}
        // }

        if ($error <= 0) {
            echo CJSON::encode([
                'status' => 'ok',
                'message' => 'Selected data successfully deleted.'
            ]);
            exit;
        } else {
            echo CJSON::encode([
                'status' => 'error',
                'message' => 'Selected data failed to delete.'
            ]);
            exit;
        }
    }

    public function actionEditData()
    {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            throw new CHttpException(403, 'Invalid request.');
        }

        if (!isset($_POST['ProductInfo'])) {
            throw new CHttpException(403, 'Invalid request. Form is missing.');
        }

        $productFeed = [];

        $postData = $_POST['ProductInfo'];

        $productData = ProductInfo::model()->find([
            'condition' => 'product_id = :product_id',
            'params' => [':product_id' => $postData['product_id']]
        ]);

        if (!$productData) {
            throw new CHttpException(403, 'Invalid request. Product data not exists.');
        }

        $productData->mpn = trim($postData['mpn']);
        $productData->sbb_price = (float) $postData['sbb_price'];
        $productData->cost = (float) $postData['cost'];
        $productData->msrp = (float) $postData['msrp'];
        $productData->description = $postData['description'];
        $productData->sku = $postData['sku'];
        $productData->ean = $postData['ean'];
        $productData->weight = $postData['weight'];
        $productData->width = $postData['width'];
        $productData->length = $postData['length'];
        $productData->height = $postData['height'];
        // $productData->quantity = (int) $postData['quantity'];

        $mpnExist = ProductInfo::model()->findAll([
            'alias' => 'pi',
            'join' => 'inner join {{product}} as p on p.id = pi.product_id',
            'condition' => 'pi.mpn = :mpn AND p.id <> :id AND p.status not in (
				' . Product::STATUS_DELETED . ', 
				' . Product::STATUS_INACTIVE . ')',
            'params' => [
                ':mpn' => $productData->mpn,
                ':id' => $postData['product_id']
            ]
        ]);

        if ($mpnExist) {
            echo CJSON::encode([
                'status' => 'error',
                'message' => 'Unable to save, product MPN already exists.'
            ]);
            exit;
        }

        $productInfo = $productData->product;

        $normalizedLockPricing = VendorNormalizedPricingLock::model()->find([
            'condition' => 'mpn = :mpn AND status = :status',
            'params' => [
                ':mpn' => trim($productData->mpn),
                ':status' => VendorNormalizedPricingLock::STATUS_ACTIVE,
            ]
        ]);

        if ($normalizedLockPricing) {
            $normalizedLockPricing->price = $productData->sbb_price;
            $normalizedLockPricing->save(false);
        }

        if ($productData->save(false)) {
            $productFeed[] = $productData->attributes
                + $productInfo->attributes
                + ['brand' => $productInfo->vendor->name];

            Product::apisBatchInsertEditData($productFeed, [
                'success_status' => Product::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS,
                'success_error' => Product::REST_STATUS_PUBLISH_EDIT_DATA_ERROR
            ]);

            echo CJSON::encode([
                'status' => 'ok',
                'message' => 'Product changes successfully saved and published.'
            ]);
            exit;
        } else {
            echo CJSON::encode([
                'status' => 'error',
                'message' => 'Unable to save parsed data.'
            ]);
            exit;
        }
    }

    public function actionGetDetails()
    {
        $options = [];

        if (!empty($_POST['product_ids'])) {
            $productIds = urldecode($_POST['product_ids']);
            $options['p_ids'] = CJSON::decode($productIds, true);
        }

        $response = array(
            'published_total' => 0,
            'published_vendors_count' => [
                Vendor::INDEX_GEO_VISION => 0,
                Vendor::INDEX_MOTOBIX => 0,
                Vendor::INDEX_FLIR => 0,
                Vendor::INDEX_ACTI => 0
            ],
            'pubished_websites_count' => [
                Product::WEBSITE_WOO_COMMERCE => 0,
                Product::WEBSITE_GOOGLE_MERCHANT => 0,
                Product::WEBSITE_GSS => 0
            ],
            'published_status_count' => [
                Product::STATUS_ACTIVE => 0,
                Product::STATUS_ERROR => 0
            ],
            'published_files_html' => ''
        );

        $publishedCount = Product::countPublishedData($options);
        $publishedCountortPublishedCountWebsites = Product::countWebsites($options);
        $publishedCountVendors = Product::countVendors($options);
        $publishedCountStatuses = Product::countStatuses($options);
        $publishedHtmlFileList = Product::getHtmlFileList($options);

        $response['published_files_html'] = $publishedHtmlFileList;
        $response['published_total'] = $publishedCount;

        $response['pubished_websites_count'][Product::WEBSITE_WOO_COMMERCE] = $publishedCountortPublishedCountWebsites[Product::WEBSITE_WOO_COMMERCE];
        $response['pubished_websites_count'][Product::WEBSITE_GOOGLE_MERCHANT] = $publishedCountortPublishedCountWebsites[Product::WEBSITE_GOOGLE_MERCHANT];
        $response['pubished_websites_count'][Product::WEBSITE_GSS] = $publishedCountortPublishedCountWebsites[Product::WEBSITE_GSS];
        //looks wrong (12/15/2020)
        //$response['pubished_websites_count'][Product::WEBSITE_GSS] = $publishedCountortPublishedCountWebsites[Product::WEBSITE_GOOGLE_MERCHANT];
        
        $response['pubished_vendors_count'][Vendor::INDEX_GEO_VISION] = $publishedCountVendors[Vendor::INDEX_GEO_VISION];
        $response['pubished_vendors_count'][Vendor::INDEX_MOTOBIX] = $publishedCountVendors[Vendor::INDEX_MOTOBIX];
        $response['pubished_vendors_count'][Vendor::INDEX_FLIR] = $publishedCountVendors[Vendor::INDEX_FLIR];
        $response['pubished_vendors_count'][Vendor::INDEX_ACTI] = $publishedCountVendors[Vendor::INDEX_ACTI];

        $response['published_status_count'][Product::STATUS_ACTIVE] = $publishedCountStatuses[Product::STATUS_ACTIVE];
        $response['published_status_count'][Product::STATUS_ERROR] = $publishedCountStatuses[Product::STATUS_ERROR];

        echo CJSON::encode($response);
        exit;
    }

    public function actionOverwrite()
    {
        $postProductIds = $_POST['product_ids']; 
        
        //$productFeeds = [];

        /*foreach ($postProductIds as $postProductId) {
            $product = Product::model()->findByPk($postProductId);

            $tmpData = $product->attributes;
            $tmpData += $product->productInfo->attributes;
            $tmpData['brand'] = $product->vendor_id;

            $productFeeds[] = $tmpData;

        }*/
        $cronAction = CronProductActionStatus::createNewCronProductAction(CronProductActionStatus::TYPE_OVERWRITE,$postProductIds);
        if(!$cronAction){
        	$error++;
        }
        //product woocommerce overwrite
        /*Product::apisBatchOverwrite($productFeeds, [
            'success_status' => Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS,
            'success_error' => Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS
        ]);*/
    }

    public function actionRePublish()
    {
        $errors = 0;
        $success = 0;

		$postProductIds = (isset($_POST['product_ids'])) ? $_POST['product_ids'] : '';

        if (!empty($postProductIds)) {

	        $cronAction = CronProductActionStatus::createNewCronProductAction(CronProductActionStatus::TYPE_RE_PUBLISH,$postProductIds);
	        if(!$cronAction){
	        	$error++;
	        }

            echo CJSON::encode([
                'success' => 'ok',
                'message' => 'Product republishing successfully done.'
            ]);

            exit;
        }

        throw new CHttpException(403, 'Invalid request.');
    }

    public function actionTestMate()
    {
    }

    public function actionLockPricing()
    {
        $productIds = $_POST['product_ids'];

        $lockItems = 0;

        foreach ($productIds as $productId) {
            $product = Product::model()->findByPk($productId);
            $productInfo = $product->productInfo;

            $normalizedLockPricing = VendorNormalizedPricingLock::model()->find([
                'condition' => 'mpn = :mpn AND status = :status',
                'params' => [
                    ':mpn' => trim($productInfo->mpn),
                    ':status' => VendorNormalizedPricingLock::STATUS_ACTIVE,
                ]
            ]);

            if (!$normalizedLockPricing) {
                $normalizedLockPricing = new VendorNormalizedPricingLock;
            }

            $normalizedLockPricing->mpn = trim($productInfo->mpn);
            $normalizedLockPricing->price = (float) $productInfo->sbb_price;
            $normalizedLockPricing->status = VendorNormalizedPricingLock::STATUS_ACTIVE;
            $normalizedLockPricing->date_created = date('Y-m-d H:i:s');

            if ($normalizedLockPricing->save(false)) {
                $lockItems++;
            }
        }

        echo CJSON::encode([
            'status' => 'ok',
            'message' => 'Successfully lock pricing. (' . $lockItems . ' items)'
        ]);
        exit;
    }

    public function actionUnLockPricing()
    {
        $productIds = $_POST['product_ids'];

        $unLockItems = 0;

        foreach ($productIds as $productId) {
            $product = Product::model()->findByPk($productId);
            $productInfo = $product->productInfo;

            $normalizedLockPricing = VendorNormalizedPricingLock::model()->find([
                'condition' => 'mpn = :mpn AND status = :status',
                'params' => [
                    ':mpn' => trim($productInfo->mpn),
                    ':status' => VendorNormalizedPricingLock::STATUS_ACTIVE,
                ]
            ]);

            if (!$normalizedLockPricing) {
                continue;
            }

            $normalizedLockPricing->status = VendorNormalizedPricingLock::STATUS_DELETED;

            if ($normalizedLockPricing->save(false)) {
                $unLockItems++;
            }
        }

        echo CJSON::encode([
            'status' => 'ok',
            'message' => 'Successfully unlock pricing. (' . $unLockItems . ' items)'
        ]);
        exit;
    }

    public function actionDownloadQuickbook()
    {
        // $brand = $_POST["search"]["vendor"];
        $brand = $_POST["selected_brand_qb"];
        $data = [];

        $data[] = [
            'Brand Name',
            'SKU',
            'MPN',
            'MSRP',
            'Cost',
            'SBB Price',
            'Description',
            'QB Description',
            'GTIN',
            'Width',
            'Length',
            'Height',
            'Weight',
            'Quantity',
            'Status'
        ];

        $productdDataCriteria = new CDbCriteria;
        $productdDataCriteria->alias = 'pi';
        $productdDataCriteria->join = 'INNER JOIN {{product}} AS p ON p.id = pi.product_id';
        if ($brand == "") {
            $productdDataCriteria->condition = 'p.status NOT IN (' . Product::STATUS_DELETED . ')';
        } else {
            $productdDataCriteria->condition = 'p.status NOT IN (' . Product::STATUS_DELETED . ') AND pi.brand_name="' . $brand . '"';
        }
        $productdDataCriteria->order = 'pi.brand_name ASC, pi.mpn';
        $productData = ProductInfo::model()->findAll($productdDataCriteria);

        foreach ($productData as $productDataValue) {
            $data[] = [
                $productDataValue->brand_name, // Brand Name
                $productDataValue->sku, // SKU
                $productDataValue->mpn, // MPN
                ZCommon::formatWithDecimal($productDataValue->msrp), // MSRP
                ZCommon::formatWithDecimal($productDataValue->cost), // Cost
                ZCommon::formatWithDecimal($productDataValue->sbb_price), // SBB Price
                $productDataValue->description, // Description
                $productDataValue->description, // QB Description
                '', // GTIN
                $productDataValue->width, // Width
                $productDataValue->length, // Length
                $productDataValue->height, // Height
                $productDataValue->weight, // Weight
                $productDataValue->quantity, // Quantity
                '' // 'Not available'
            ];
        }

        $filename = $brand . '_Published_Products';
        $filename .= '_' . date('Y_m_d_H_i_s');
        $filename .= '.csv';

        $f = fopen(LookUp::TEMP_FOLDER . "/" . $filename, "w");

        foreach ($data as $dataval) {
            fputcsv($f, $dataval);
        }

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        readfile(LookUp::TEMP_FOLDER . '/' . $filename);
    }

    // Uncomment the following methods and override them if needed
    /*
    public function filters()
    {
        // return the filter configuration for this controller, e.g.:
        return array(
            'inlineFilterName',
            array(
                'class'=>'path.to.FilterClass',
                'propertyName'=>'propertyValue',
            ),
        );
    }

    public function actions()
    {
        // return external action classes, e.g.:
        return array(
            'action1'=>'path.to.ActionClass',
            'action2'=>array(
                'class'=>'path.to.AnotherActionClass',
                'propertyName'=>'propertyValue',
            ),
        );
    }
    */

    public function actionSetProductsStatus()
    {
        $affectedProducts = 0;
        $selectedProductIDs = !empty($_POST['product_ids']) ? $_POST['product_ids'] : [];

        $products = [];

        foreach ($selectedProductIDs as $selectedProductID) {
            $product = Product::model()->findByPk($selectedProductID);
            $product->product_status = $_POST['product_status_id'];

            if ($product->save(false)) {
                /*$tmpProduct = $product->attributes;
                $tmpProduct += $product->productInfo->attributes;
                $tmpProduct['brand'] = $product->vendor->name;

                $products[] = $tmpProduct;*/

                $affectedProducts++;
            }
        }

        if ($affectedProducts > 0) {
            /*Product::apisBatchInsertEditData($products, [
                'success_status' => Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS,
                'success_error' => Product::REST_STATUS_PUBLISH_EDIT_STATUS_ERROR
            ]);*/

            /*$productLabelStatus = Product::getProductStatusLabel($_POST['product_status_id']);

            if ($_POST['product_status_id'] == Product::PRODUCT_STATUS_NOT_EOL) {
                $productLabelStatus = 'Not EOL';
            }*/
            $cronType = ($_POST['product_status_id'] == Product::PRODUCT_STATUS_NOT_EOL ? CronProductActionStatus::TYPE_SET_NOT_EOL : CronProductActionStatus::TYPE_SET_EOL); 
            
	        $cronAction = CronProductActionStatus::createNewCronProductAction($cronType,$selectedProductIDs);
	        if(!$cronAction){
	        	$error++;
	        }

            echo CJSON::encode([
                'status' => 'ok',
                'message' => 'Successfully set products(' . $affectedProducts . ') status to ' . $productLabelStatus . '.'
            ]);
            exit;
        } else {
            echo CJSON::encode([
                'status' => 'error',
                'message' => 'Unable to update selected products.'
            ]);
            exit;
        }
    }

    public function actionTest()
    {
        Dev::pvx(var_duProduct::getSBBProductsCategoryId('MobOtix'));
    }

    public function actionGetProductDataGssPricing($productId)
    {
        $this->layout = 'none';

        $productData = Product::model()->findByPk($productId);

        if (!$productData) {
            throw new CHttpException(403, 'Invalid data, Product data is not exists.');
        }

        $productLevels = ProductPricingTierLookup::model()->findAll([
            'condition' => 'status IN (' .  PricingGroup::STATUS_ACTIVE . ') and product_id = :product_id',
            'params' => [
                ':product_id' => $productData->id
            ]
        ]);

        $isPublished = true;

        foreach ($productLevels as $productLevel) {
            if ($productLevel->woocommerce_status == 0) {
                $isPublished = false;
                break;
            }
        }

        $this->render('../reviewVendorSpreadsheet/getParsedDataGssPricing', [
            'productLevels' => $productLevels,
            'isPublished' => $isPublished,
            'productData' => $productData
        ]);
    }

    public function actionCreateUpdatePriceSettingGss()
    {
        $countAffectedProducts = 0;

        $pricingGroupId = !empty($_POST['pricing_group_id']) ? $_POST['pricing_group_id'] : '';
        //$pricingType = !empty($_POST['pricing_type']) ? $_POST['pricing_type'] : '';
        $productIds = !empty($_POST['product_ids']) ? $_POST['product_ids'] : [];

        $products = Product::model()->findAll([
            'condition' => 'id IN (' . implode(', ', $productIds) . ') and status = :status',
            'params' => [
                ':status' => PricingGroup::STATUS_ACTIVE,
            ]
        ]);

        //delete gss price on productpricingtierlookup. when gss price is empty
        if ($pricingGroupId == '') {
            foreach ($products as $product) {
                $productInfo = $product->productInfo;

                $productDataPriceExisting = ProductPricingTierLookup::model()->findAll([
                    'condition' => 'product_id = :product_id AND status = :status',
                    'params' => [
                        ':product_id' => $product->id,
                        ':status' => PricingGroup::STATUS_ACTIVE
                    ]
                ]);

                foreach ($productDataPriceExisting as $productDataPriceExistingData) {
                    if ($productDataPriceExistingData->woocommerce_status == ProductPricingTierLookup::WC_STATUS_SUCCESS) {
                        $productDataPriceExistingData->woocommerce_status = 0;
                    }

                    $productDataPriceExistingData->status = ProductPricingTierLookup::STATUS_DELETED;
                    $productDataPriceExistingData->save(false);
                }

                $countAffectedProducts++;
            }

            echo CJSON::encode([
                'status' => 'ok',
                'message' => 'GSS Product (' . $countAffectedProducts . ') pricing levels successfully apply.'
            ]);
            exit;
        }

        // if ($pricingType == '') {
        // 	echo CJSON::encode([
        // 		'status' => 'error',
        // 		'message' => 'Select Pricing Type between Markup or Markdown.'
        // 	]); exit;
        // }

        if (count($productIds) <= 0) {
            echo CJSON::encode([
                'status' => 'error',
                'message' => 'No Product selected.'
            ]);
            exit;
        }


        $pricingGroup = PricingGroup::model()->findByPk($pricingGroupId);

        if (!$pricingGroup) {
            throw new CHttpException(403, 'Invalid request, price group not exists.');
        }

        $pricingGroupPrices = $pricingGroup->getPrices();

        if (count($pricingGroupPrices) <= 0) {
            echo CJSON::encode([
                'status' => 'error',
                'message' => 'Pricing Group don\'t have any price levels.'
            ]);
            exit;
        }

        $transaction = Yii::app()->db->beginTransaction();

        try {
            foreach ($products as $product) {
                $productInfo = $product->productInfo;

                $productDataPriceExisting = ProductPricingTierLookup::model()->findAll([
                    'condition' => 'product_id = :product_id AND status = :status',
                    'params' => [
                        ':product_id' => $product->id,
                        ':status' => PricingGroup::STATUS_ACTIVE
                    ]
                ]);

                foreach ($productDataPriceExisting as $productDataPriceExistingData) {
                    $productDataPriceExistingData->status = PricingGroup::STATUS_INACTIVE;
                    $productDataPriceExistingData->save(false);
                }

                foreach ($pricingGroupPrices as $pricingGroupPrice) {
                    if ($pricingGroupPrice->vendor_id == $product->vendor_id) {
                        $productDataPrice = ProductPricingTierLookup::model()->find([
                            'condition' => 'product_id = :product_id
								AND selected_price_type = :selected_price_type
								AND pricing_tier_id = :pricing_tier_id',
                            'params' => [
                                ':product_id' => $product->id,
                                ':selected_price_type' => $pricingGroupPrice->default_type,
                                ':pricing_tier_id' => $pricingGroupPrice->id,
                            ]
                        ]);

                        if (!$productDataPrice) {
                            $productDataPrice = new ProductPricingTierLookup;
                        }

                        $productDataPrice->product_id = $product->id;
                        $productDataPrice->selected_price_type = $pricingGroupPrice->default_type;
                        //$productDataPrice->cost_markup_computed = $productInfo->cost * (1 + ($pricingGroupPrice->cost_markup / 100)); // old wrong formula 02-16-21
                        $productDataPrice->cost_markup_computed = $productInfo->cost / (1 - ($pricingGroupPrice->cost_markup / 100));
                        $productDataPrice->msrp_markdown_computed = $productInfo->msrp * (1 - ($pricingGroupPrice->msrp_markdown / 100));
                        $productDataPrice->pricing_tier_id = $pricingGroupPrice->id;
                        $productDataPrice->group_id = $pricingGroup->id;
                        $productDataPrice->status = PricingGroup::STATUS_ACTIVE;
                        $productDataPrice->woocommerce_status = 0;
                        $productDataPrice->save(false);
                    }
                }

                $countAffectedProducts++;
            }

            $transaction->commit();

            echo CJSON::encode([
                'status' => 'ok',
                'message' => 'GSS Product (' . $countAffectedProducts . ') pricing levels successfully apply.'
            ]);
            exit;
        } catch (Exception $e) {
            $transaction->rollBack();
            Dev::pvx($e->getMessage());
        }

        throw new CHttpException(403, 'Invalid request.');
    }

    public function actionUpdatePriceSetting()
    {
        $transaction = Yii::app()->db->beginTransaction();

        try {
            $errors = 0;
            $affectedDataCount = 0;

            $productIds = isset($_POST['product_ids']) ? $_POST['product_ids'] : [];

            if (count($productIds) <= 0) {
                echo CJSON::encode([
                    'status' => 'error',
                    'message' => 'Please select products.'
                ]);
                exit;
            }

            if (
                $_POST['price_setting']['type'] == SettingSalesPrice::SALES_PRICE_SETTING_COST
                || $_POST['price_setting']['type'] == SettingSalesPrice::SALES_PRICE_SETTING_MSRP
            ) {
                $productData = Product::model()->findAll([
                    'condition' => 'id IN (' . implode(', ', $productIds) . ')',
                ]);

                $apiProductFeeds = [];

                $salesMarginCostMarkup = (float) $_POST['price_setting']['sales_margin_cost_markup'];
                $salesMarginMsrpMarkDown = (float) $_POST['price_setting']['sales_margin_msrp_markdown'];

                $salesDollor = (int) $_POST['price_setting']['dollor'];

                foreach ($productData as $product) {
                    $productInfo = $product->productInfo;
                    // $normalizedLockPricing = VendorNormalizedPricingLock::model()->find([
                    // 	'condition' => 'mpn = :mpn AND status = :status',
                    // 	'params' => [
                    // 		':mpn' => trim($vendorNormalizedInfo->mpn),
                    // 		':status' => VendorNormalizedPricingLock::STATUS_ACTIVE,
                    // 	]
                    // ]);

                    // if ($normalizedLockPricing) {
                    // 	continue;
                    // }

                    $salesBasedPrice = (float) ($_POST['price_setting']['type'] == SettingSalesPrice::SALES_PRICE_SETTING_COST)
                        ? $productInfo->cost : $productInfo->msrp;

                    if ($_POST['price_setting']['type'] == SettingSalesPrice::SALES_PRICE_SETTING_COST) {
                        $salesMarginCostMarkupDivision = $salesMarginCostMarkup / 100;
                        $tmpPrice = ($salesBasedPrice / 1 - $salesMarginCostMarkupDivision) + $salesDollor;
                        $salesMargin = $salesMarginCostMarkup;
                    } elseif ($_POST['price_setting']['type'] == SettingSalesPrice::SALES_PRICE_SETTING_MSRP) {
                        $tmpPrice = ($salesBasedPrice * (1 - ($salesMarginMsrpMarkDown / 100))) + $salesDollor;
                        $salesMargin = $salesMarginMsrpMarkDown;
                    }

                    $productInfo->sbb_price = (float) $tmpPrice;

                    if ($productInfo->save(false)) {
                        /*$apiProductFeeds[] = $product->attributes
                            + $productInfo->attributes
                            + ['brand' => $product->vendor->name];*/

                        $affectedDataCount++;
                    } else {
                        $errors++;
                    }
                }

                if (count($affectedDataCount) > 0) {
                	$cronAction = CronProductActionStatus::createNewCronProductAction(createNewCronProductAction::TYPE_PRICE_SETTING,$postProductIds);
			        if(!$cronAction){
			        	$error++;
			        }
                    /*Product::apisBatchInsertEditData($apiProductFeeds, [
                        'success_status' => Product::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS,
                        'success_error' => Product::REST_STATUS_PUBLISH_EDIT_DATA_ERROR
                    ]);*/
                }
            } else {
                throw new Exception('Error: price setting invalid type.');
            }

            if ($errors <= 0) {
                $transaction->commit();

                echo CJSON::encode([
                    'status' => 'ok',
                    'message' => 'Price setting successfully applied. affected products (' . $affectedDataCount . ').'
                ]);
                exit;
            } else {
                throw new Exception('Error: price setting cannot be saved.');
            }
        } catch (Exception $e) {
            $transaction->rollBack();
            echo CJSON::encode(array(
                'status' => 'error',
                'message' => $e->getMessage()
            ));
            exit;
        }

        throw CHtttpError(403, 'Invalid request.');
    }

    public function actionSyncGoogleMerchantProductsImage()
    {
        $productIds = $_POST['product_ids'];

        $cronAction = CronProductActionStatus::createNewCronProductAction(CronProductActionStatus::TYPE_SYNC_GOOGLE_PRODUCT_IMAGE,$productIds);
       
        echo CJSON::encode([
            'status' => 'ok',
            'message' => 'Synching google merchant products(' . $affectedProducts . ') image from sbb and gss successfully finished'
        ]);
        exit;
    }
    //action type cron job syncing data woocommerce to web app
    public function actionSyncWoocommerceData(){
        //check if cron switch is on
        $cronState = Yii::app()->db->createCommand('SELECT `value`, `serialized_options` FROM gss_system_settings WHERE `key` = "woocommerceSyncCron"')->queryRow();
        // If nothing to process
        if( $cronState['value'] == 0 ) exit('CRON IS OFF'); 
        //get new published vendor
        $syncingVendorFiles = VendorFile::model()->findAll(array(
            'condition' => 'sync_status = :sync_status and status = :status',
            'params' => array(
                ':sync_status' => VendorFile::SYNC_STATUS_SYNCING,
                ':status' => VendorFile::STATUS_PUSHED
            ),
            'limit' => 1
        ));
        if(empty($syncingVendorFiles)){
            echo 'No vendor files with for syncing status.'; exit;
        }

        try{
            foreach($syncingVendorFiles as $syncingVendorFile){
                //get categories product on both woocommerce
                $pageArr = unserialize($cronState['serialized_options']);
                $products = Product::apisBatchSyncProduct($syncingVendorFile->vendor_id, $pageArr['page']);
                if(!empty($products['gssProducts'])){
                    //syncing gss products
                    foreach ($products['gssProducts'] as $gssProduct) {
                        $transaction = Yii::app()->db->beginTransaction();
                        $product = Product::model()->find(array(
                            'alias' => 'p',
                            'join' => 'INNER JOIN {{product_info}} AS pi ON p.id = pi.product_id',
                            'condition' => 'pi.sku = :sku',
                            'params' => [
                                ':sku' => $gssProduct->sku,
                            ]
                        ));

                        /*$sbbProductId = null;
                        if (false !== $key = array_search($gssProduct->sku, $products['sbbProducts'])) {
                            $sbbProductId = $products['sbbProducts'][$key]->id;
                        }*/
                        //update product rest api i
                        if(empty($product)){
                            //saving new product if not exist (gss).
                            $settingDefaultValue = SettingDefaultValue::model()->find(array(
                                'condition' => 'status = 1'
                            ));
                            if (!empty($settingDefaultValue['width'])) {
                                $width = $settingDefaultValue['width'];
                            } else {
                                $width = isset($dataValue['width']) ? trim($dataValue['width']) : 0;
                            }

                            if (!empty($settingDefaultValue['length'])) {
                                $length = $settingDefaultValue['length'];
                            } else {
                                $length = isset($dataValue['length']) ? trim($dataValue['length']) : 0;
                            }

                            if (!empty($settingDefaultValue['height'])) {
                                $height = $settingDefaultValue['height'];
                            } else {
                                $height = isset($dataValue['height']) ? trim($dataValue['height']) : 0;
                            }

                            if (!empty($settingDefaultValue['weight'])) {
                                $weight = $settingDefaultValue['weight'];
                            } else {
                                $weight = isset($dataValue['weight']) ? trim($dataValue['weight']) : 0;
                            }

                            if (!empty($settingDefaultValue['quantity'])) {
                                $quantity = $settingDefaultValue['quantity'];
                            } else {
                                $quantity = isset($dataValue['quantity']) ? trim($dataValue['quantity']) : 0;
                            }

                            $product = new Product;
                            $product->vendor_id = $syncingVendorFile->vendor_id;
                            $product->batch_id = VendorFile::generateBatchId($syncingVendorFile->id);
                            $product->platform_2_rest_id = $gssProduct->id;
                            $product->platform_1_rest_id = $sbbProductId;
                            $product->product_status = Product::PRODUCT_STATUS_EOL;
                            if($product->save(false)){
                                $productInfo = new ProductInfo;
                                $productInfo->product_id = $product->id;
                                $productInfo->brand_name = Vendor::getVendorNameLabel($syncingVendorFile->id);
                                $productInfo->mpn = $gssProduct->name;
                                $productInfo->sku = $gssProduct->sku;
                                $productInfo->msrp = $gssProduct->sale_price;
                                $productInfo->cost = $gssProduct->regular_price;
                                $productInfo->description = $gssProduct->description;
                                $productInfo->width = $width;
                                $productInfo->length = $length;
                                $productInfo->height = $height;
                                $productInfo->weight = $weight;
                                if($productInfo->save(false)){
                                    $transaction->commit();
                                }else{
                                    $transaction->rollback();
                                    $error[] = 'Product ID '.$product->id.' Not saved.';
                                }
                            }   
                        }
                        /*$tmpData = $product->attributes + $productInfo->attributes; 
                        $tmpData['brand'] = $syncingVendorFile->vendor->name;

                        $productFeeds[] = $tmpData;*/
                    }
                }
                if(!empty($products['sbbProducts'])){
                    //syncing gss products
                    foreach ($products['sbbProducts'] as $sbbProduct) {
                        $transaction = Yii::app()->db->beginTransaction();
                        $product = Product::model()->find(array(
                            'alias' => 'p',
                            'join' => 'INNER JOIN {{product_info}} AS pi ON p.id = pi.product_id',
                            'condition' => 'pi.sku = :sku',
                            'params' => [
                                ':sku' => $sbbProduct->sku,
                            ]
                        ));
                        //update product if exist
                        $gssProductId = null;
                        if (false !== $key = array_search($sbbProduct->sku, $products['gssProducts'])) {
                            $gssProductId = $products['gssProducts'][$key]->id;
                        }
                        if(empty($product)){
                            //saving new product if not exist (sbb).
                            $settingDefaultValue = SettingDefaultValue::model()->find(array(
                                'condition' => 'status = 1'
                            ));
                            if (!empty($settingDefaultValue['width'])) {
                                $width = $settingDefaultValue['width'];
                            } else {
                                $width = isset($dataValue['width']) ? trim($dataValue['width']) : 0;
                            }

                            if (!empty($settingDefaultValue['length'])) {
                                $length = $settingDefaultValue['length'];
                            } else {
                                $length = isset($dataValue['length']) ? trim($dataValue['length']) : 0;
                            }

                            if (!empty($settingDefaultValue['height'])) {
                                $height = $settingDefaultValue['height'];
                            } else {
                                $height = isset($dataValue['height']) ? trim($dataValue['height']) : 0;
                            }

                            if (!empty($settingDefaultValue['weight'])) {
                                $weight = $settingDefaultValue['weight'];
                            } else {
                                $weight = isset($dataValue['weight']) ? trim($dataValue['weight']) : 0;
                            }

                            if (!empty($settingDefaultValue['quantity'])) {
                                $quantity = $settingDefaultValue['quantity'];
                            } else {
                                $quantity = isset($dataValue['quantity']) ? trim($dataValue['quantity']) : 0;
                            }

                            $product = new Product;
                            $product->vendor_id = $syncingVendorFile->vendor_id;
                            $product->batch_id = VendorFile::generateBatchId($syncingVendorFile->id);
                            $product->platform_2_rest_id = $gssProduct->id;
                            $product->platform_1_rest_id = $sbbProductId;
                            $product->product_status = Product::PRODUCT_STATUS_EOL;
                            if($product->save(false)){
                                $productInfo = new ProductInfo;
                                $productInfo->product_id = $product->id;
                                $productInfo->brand_name = Vendor::getVendorNameLabel($syncingVendorFile->id);
                                $productInfo->mpn = $sbbProduct->name;
                                $productInfo->sku = $sbbProduct->sku;
                                $productInfo->msrp = $sbbProduct->sale_price;
                                $productInfo->cost = $sbbProduct->regular_price;
                                $productInfo->description = $sbbProduct->description;
                                $productInfo->width = $width;
                                $productInfo->length = $length;
                                $productInfo->height = $height;
                                $productInfo->weight = $weight;
                                if($productInfo->save(false)){
                                    $transaction->commit();
                                }else{
                                    $transaction->rollback();
                                    $error[] = 'Product ID '.$product->id.' Not saved.';
                                }
                            }   
                        }
                        /*$tmpData = $product->attributes + $productInfo->attributes; 
                        $tmpData['brand'] = $syncingVendorFile->vendor->name;

                        $productFeeds[] = $tmpData;*/
                    }
                }
                if(empty($products['gssProducts']) && empty($products['sbbProducts'])){
                    //change sync status of vendorfile 
                    $syncingVendorFile->setSyncStatusSynced();
                    $pageArr['page'] = 1;
                    Yii::app()->db->createCommand()->update('gss_system_settings', array(
                            'serialized_options' => serialize($pageArr),
                        ), '`key` = "woocommerceSyncCron"');
                    echo 'All product synced';
                    exit;
                }
                $pageArr['page'] = $pageArr['page'] + 1;
                Yii::app()->db->createCommand()->update('gss_system_settings', array(
                        'serialized_options' => serialize($pageArr),
                    ), '`key` = "woocommerceSyncCron"');
                /*Product::apisBatchInsertEditData($productFeeds, [
                    'success_status' => Product::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS,
                    'success_error' => Product::REST_STATUS_PUBLISH_ADD_DATA_ERROR
                ]);*/
                break;
            }
        } catch (Exception $e) {
            //$transaction->rollBack();
            Dev::pvx($e);
        }
    }


	// action type ajax
	public function actionGetProgressDetails() {
		$cronAction = CronProductActionStatus::model()->find(array(
			'condition' => 'status = :status OR status = :status1',
			'params' => array(
				':status' => CronProductActionStatus::STATUS_IN_PROGRESS,
				':status1' => CronProductActionStatus::STATUS_COMPLETED,
			),
			'limit' => 1
		));
		if ($cronAction) {
			$countTotalParsed = CronProductActionStatus::countTotalParsed($cronAction->id);
			//$countTotalProcessing = CronProductActionStatus::countTotalParsing($cronAction->id);
			$countTotalDone = CronProductActionStatus::countStatusDone($cronAction->id);
			//Dev::pvx($countTotalDone);

		    if($cronAction->type == CronProductActionStatus::TYPE_SET_EOL || $cronAction->type == CronProductActionStatus::TYPE_SET_NOT_EOL)
		        $spanAction = 'Product Status Update Processing...';
		    if($cronAction->type == CronProductActionStatus::TYPE_RE_PUBLISH)
		        $spanAction = 'Re-Publish Product Processing...';
		    if($cronAction->type == CronProductActionStatus::TYPE_OVERWRITE)
		        $spanAction = 'Overwrite Product Processing...';
		    if($cronAction->type == CronProductActionStatus::TYPE_DELETE)
		        $spanAction = 'Delete Product Processing...';
		    if($cronAction->type == CronProductActionStatus::TYPE_PRICE_SETTING)
		        $spanAction = 'Update SBB Price Setting Processing...';
		    if($cronAction->type == CronProductActionStatus::TYPE_SYNC_GOOGLE_PRODUCT_IMAGE)
		        $spanAction = 'Sync Google Product Image Processing...';

			$response['item_count'] = $countTotalParsed;
			$response['item_done'] = $countTotalDone;
			$response['span_action'] = $spanAction;
			$response['status'] = $cronAction->status;
			
			/*$response['item_count_parsing'] = $countTotalParsing .' / '. $vendorFile->total_product;
			$response['item_count_pushing'] = $countTotalPushed . ' / ' . $countTotalParsed;*/
			
		
		}else{
			$response['status'] = 3;
		}
			echo CJSON::encode($response); exit;
	}

	//action cron
	public function actionCronActionProduct(){
		$cronAction = CronProductActionStatus::model()->find(array(
			'condition' => 'status = :status',
			'params' => array(
				':status' => CronProductActionStatus::STATUS_IN_PROGRESS,
			),
		));

		if (empty($cronAction)) {
			echo 'No action to process.'; exit;
		}

		try{
			$cronActionProducts = CronProductActionProductList::model()->findAll(array(
				'condition' => 'status = :status AND action_id = :actionId',
				'params' => array(
					':status' => CronProductActionProductList::STATUS_PENDING,
					':actionId' => $cronAction->id,
				),
				'limit' => 7,
			));

			if(!empty($cronActionProducts)){
				foreach ($cronActionProducts as $cronActionProduct) {
					$product = $cronActionProduct->product;
					$productInfo = $cronActionProduct->productInfo;
					$cronActionProduct->setStatusProcessing();
                    
                    $gssSearch = WooCommerceGSS::getProductBySKU($productInfo->sku);
		            $sbbSearch = WooCommerce::getProductBySKU($productInfo->sku);
                    $product->platform_1_rest_id = $product->platform_1_rest_id ?: $sbbSearch[0]->id;
                    $product->platform_2_rest_id = $product->platform_2_rest_id ?: $gssSearch[0]->id;
					$vendorName = ucwords(strtolower(Vendor::getVendorNameLabel($product->vendor_id)));
                    $productInfo->product_name = (!isset($productInfo->product_name) || $productInfo->product_name == '' ? substr($vendorName.' '.$productInfo->mpn.' '.strip_tags($productInfo->qb_description) ?: strip_tags($productInfo->description), 0, 70) : $productInfo->product_name);
					$tmpData = $product->attributes + $productInfo->attributes;
					$sbbImageChecker = WooCommerce::getImageStatus($vendorName, $productInfo->mpn);
					$gssImageChecker = WooCommerceGSS::getImageStatus($vendorName, $productInfo->mpn);
                    $tmpData['sbbImageStatus'] = $sbbImageChecker['status'];
                    $tmpData['sbbImageLink'] = $sbbImageChecker['link'];
                    $tmpData['gssImageStatus'] = $gssImageChecker['status'];
                    $tmpData['gssImageLink'] = $gssImageChecker['link'];
					$productFeeds[] = $tmpData;
				}
                Dev::pv($productFeeds);

				if($cronAction->type == CronProductActionStatus::TYPE_RE_PUBLISH || $cronAction->type == CronProductActionStatus::TYPE_SET_EOL || $cronAction->type == CronProductActionStatus::TYPE_SET_NOT_EOL || $cronAction->type == CronProductActionStatus::TYPE_PRICE_SETTING){
					$products = Product::apisBatchInsertEditData($productFeeds, [
		                'success_status' => Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS,
		                'success_error' => Product::REST_STATUS_PUBLISH_EDIT_STATUS_ERROR
		            ], false, true);
                    Dev::pv($products);
				}
				if($cronAction->type == CronProductActionStatus::TYPE_DELETE){
					Product::apisBatchDeleteData($productFeeds, [
			            'success_status' => Product::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS,
			            'success_error' => Product::REST_STATUS_PUBLISH_DELETE_DATA_ERROR
			        ]);
				}
				if($cronAction->type == CronProductActionStatus::TYPE_OVERWRITE){
					Product::apisBatchOverwrite($productFeeds, [
			            'success_status' => Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS,
			            'success_error' => Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS
			        ]);
				}
				if($cronAction->type == CronProductActionStatus::TYPE_SYNC_GOOGLE_PRODUCT_IMAGE){
					$sbb = new WooCommerce;

			        $gss = new WooCommerceGSS;

			        $productDataFeeds = [];
			        $sbbProductsImages = [];

			        $gssProductDataFeeds = [];
			        $gssProductsImages = [];

			        $affectedProducts = 0;

			        foreach ($cronActionProducts as $cronActionProduct) {
			            $product = Product::model()->findByPk($cronActionProduct->product_id);

			            if ($product && !empty($product->platform_1_rest_id)) {
			                $sbbProductData = $sbb->getProductData($product->platform_1_rest_id);
			                $sbbProductsImages[$productId] = $sbbProductData->images[0]->src;

			                $productDataFeeds[] = $product->attributes
			                    + $product->productInfo->attributes
			                    + ['brand' => $product->vendor->name]
			                    + ['link' => $sbbProductData->permalink];
			            }

			            if ($product && !empty($product->platform_2_rest_id)) {
			                $gssProductData = $gss->getProductData($product->platform_2_rest_id);
			                $gssProductsImages[$productId] = $gssProductData->images[0]->src;

			                $gssProductDataFeeds[] = $product->attributes
			                    + $product->productInfo->attributes
			                    + ['brand' => $product->vendor->name]
			                    + ['link' => $gssProductData->permalink];
			            }
			        }

                    Product::googleBatchInsertEditData($productDataFeeds, $gssProductDataFeeds, [
                        'sbb_product_images' => $sbbProductsImages,
                        'gss_product_images' => $gssProductsImages,
                        'success_status' => Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS,
                        'success_error' => Product::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS
                    ]);
				}

				foreach ($cronActionProducts as $cronActionProduct) {
					$cronActionProduct->setStatusDone();
				}
			}
			else{
				$cronAction->setStatusCompleted();
				exit;
			}
		}catch(Exception $e){
			Dev::pvx($e);
		}
	}

	public function actionDismissAction(){
		$cronAction = CronProductActionStatus::model()->find(array(
			'condition' => 'status = :status',
			'params' => array(
				':status' => CronProductActionStatus::STATUS_COMPLETED,
			),
		));
		try{
			if($cronAction){
				$response = $cronAction->setStatusNotRunning();
				echo CJSON::encode($response); exit;
			}
		}catch(Exception $e){
			Dev::pvx($e);
		}
	}
}