<?php

/**
 * This is the model class for table "{{product}}".
 *
 * The followings are the available columns in table '{{product}}':
 * @property integer $id
 * @property integer $vendor_id
 * @property integer $status
 * @property string $date_created
 * @property string $date_updated
 *
 * The followings are the available model relations:
 * @property Vendor $vendor
 * @property ProductInfo[] $productInfos
 */
class Product extends CActiveRecord
{
    const STATUS_ACTIVE = 1;
    const STATUS_INACTIVE = 2;
    const STATUS_DELETED = 3;
    const STATUS_ERROR = 4;
    const STATUS_API_ERROR_PUBLISH = 5;
    const STATUS_API_ERROR_EDIT = 6;
    const STATUS_API_ERROR_DELETE = 7;
    const STATUS_API_ERROR_RE_PUBLISH = 8;
    const WEBSITE_SBB = 1;
    const WEBSITE_WOO_COMMERCE = 1;
    const WEBSITE_GOOGLE_MERCHANT = 2;
    const WEBSITE_GSS = 3;
    const WEBSITE_GOOGLE_MERCHANT_GSS = 4;
    const PRODUCT_STATUS_NOT_EOL = 1;
    const PRODUCT_STATUS_EXISTING = 1;
    const PRODUCT_STATUS_EOL = 2;
    const REST_STATUS_PENDING = 0;
    const REST_STATUS_PUBLISH_ADD_DATA_SUCCESS = 1;
    const REST_STATUS_PUBLISH_ADD_DATA_ERROR = 2;
    const REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS = 3;
    const REST_STATUS_PUBLISH_DELETE_DATA_ERROR = 4;
    const REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS = 5;
    const REST_STATUS_PUBLISH_EDIT_DATA_ERROR = 6;
    const REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS = 7;
    const REST_STATUS_PUBLISH_EDIT_STATUS_ERROR = 8;
    const REST_STATUS_DISABLED = 9;
    const GOOGLE_MERCHANT_STATUS_PENDING = 0;
    const GOOGLE_MERCHANT_STATUS_APPROVED = 1;
    const GOOGLE_MERCHANT_STATUS_DISAPPROVED = 2;
    const GOOGLE_MERCHANT_STATUS_ERROR = 3;
    const GOOGLE_MERCHANT_STATUS_NOT_CHECKED = 0;
    const GOOGLE_MERCHANT_STATUS_CHECKED = 1;


    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{product}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('vendor_id', 'required'),
            array('vendor_id, status', 'numerical', 'integerOnly' => true),
            array('date_created, date_updated', 'safe'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, vendor_id, status, date_created, date_updated', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'vendor' => array(self::BELONGS_TO, 'Vendor', 'vendor_id'),
            'productInfo' => array(self::HAS_ONE, 'ProductInfo', 'product_id'),
            'productInfos' => array(self::HAS_MANY, 'ProductInfo', 'product_id'),
            'cronActionProduct' => array(self::HAS_MANY, 'CronProductActionProductList', 'product_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'vendor_id' => 'Vendor',
            'status' => 'Status',
            'date_created' => 'Date Created',
            'date_updated' => 'Date Updated',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria();

        $criteria->compare('id', $this->id);
        $criteria->compare('vendor_id', $this->vendor_id);
        $criteria->compare('status', $this->status);
        $criteria->compare('date_created', $this->date_created, true);
        $criteria->compare('date_updated', $this->date_updated, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Product the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function beforeSave()
    {
        if ($this->isNewRecord) {
            $this->date_created = date('Y-m-d H:i:s');
            $this->date_updated = date('Y-m-d H:i:s');
        } else {
            $this->date_updated = date('Y-m-d H:i:s');
        }

        return true;
    }

    public static function getStatusList($withColor = false)
    {
        if (!$withColor) {
            return [
                self::STATUS_ACTIVE => 'Active',
                self::STATUS_INACTIVE => 'Inactive',
                self::STATUS_DELETED => 'Deleted',
                self::STATUS_ERROR => 'Errors'
            ];
        } else {
            return [
                self::STATUS_ACTIVE => '<span class="label label-primary">Active</span>',
                self::STATUS_INACTIVE => '<span class="label label-default">Inactive</span>',
                self::STATUS_DELETED => '<span class="label label-warning">Deleted</span>',
                self::STATUS_ERROR => '<span class="label label-danger">Errors</span>'
            ];
        }
    }

    public static function getStatusLabelWithColor($idx)
    {
        return self::getStatusList(true)[$idx];
    }

    public static function getStatusLabel($idx)
    {
        return self::getStatusList()[$idx];
    }

    public static function getStatusLabelShort($idx)
    {
        $list = [
            self::WEBSITE_SBB => 'SBB',
            self::WEBSITE_GOOGLE_MERCHANT => 'SBB Google',
            self::WEBSITE_GSS => 'GSS',
            self::WEBSITE_GOOGLE_MERCHANT_GSS => 'GSS Google'
        ];

        return $list[$idx];
    }

    public static function getWebsiteLabel($index)
    {
        $list = self::getWebsiteList();

        return $list[$index];
    }

    public static function getWebsiteList()
    {
        return [
            self::WEBSITE_SBB => 'SBB Website',
            self::WEBSITE_GOOGLE_MERCHANT => 'SBB Google Merchant',
            self::WEBSITE_GSS => 'GSS Website',
            self::WEBSITE_GOOGLE_MERCHANT_GSS => 'GSS Google Merchant',
        ];
    }

    public static function countStatuses($options = [])
    {
        $additionalConditions = '';

        if (isset($options['p_ids'])) {
            if (count($options['p_ids']) > 0) {
                $additionalConditions .= ' AND id IN (' . implode(', ', $options['p_ids']) . ')';
            } else {
                $additionalConditions .= ' AND id IN (NULL)';
            }
        }

        $query = '
			SELECT 
			platform_1_rest_status,
			platform_2_rest_status,
			platform_3_rest_status,
			platform_4_rest_status FROM {{product}}
			WHERE status NOT IN (' . self::STATUS_DELETED . ')
			' . $additionalConditions . '
		';

        $command = Yii::app()->db->createCommand($query);
        $results = $command->queryAll();

        $formatedData = [
            self::STATUS_ACTIVE => 0,
            self::STATUS_ERROR => 0
        ];

        $successStatus = [
            self::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS,
            self::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS,
            self::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS,
            self::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS
        ];

        $errorStatus = [
            self::REST_STATUS_PUBLISH_ADD_DATA_ERROR,
            self::REST_STATUS_PUBLISH_DELETE_DATA_ERROR,
            self::REST_STATUS_PUBLISH_EDIT_DATA_ERROR,
            self::REST_STATUS_PUBLISH_EDIT_STATUS_ERROR
        ];

        foreach ($results as $result) {
            if (
                in_array($result['platform_1_rest_status'], $successStatus)
                && in_array($result['platform_2_rest_status'], $successStatus)
                && in_array($result['platform_3_rest_status'], $successStatus)
                && in_array($result['platform_4_rest_status'], $successStatus)
            ) {
                $formatedData[self::STATUS_ACTIVE] += 1;
            } else {
                $formatedData[self::STATUS_ERROR] += 1;
            }
        }

        return $formatedData;
    }

    public static function countWebsites($options = [])
    {
        $additionalConditions = '';

        if (isset($options['p_ids'])) {
            if (count($options['p_ids']) > 0) {
                $additionalConditions .= ' AND id IN (' . implode(', ', $options['p_ids']) . ')';
            } else {
                $additionalConditions .= ' AND id IN (NULL)';
            }
        }

        $query = '
			SELECT * FROM {{product}}
			WHERE status NOT IN (' . self::STATUS_DELETED . ')
			' . $additionalConditions . '
		';

        $command = Yii::app()->db->createCommand($query);
        $results = $command->queryAll();

        $formatedData = [
            self::WEBSITE_WOO_COMMERCE => 0,
            self::WEBSITE_GOOGLE_MERCHANT => 0,
            self::WEBSITE_GSS => 0,
            self::WEBSITE_GOOGLE_MERCHANT_GSS => 0,
        ];

        foreach ($results as $result) {
            if (!empty($result['platform_1_rest_id'])) {
                $formatedData[self::WEBSITE_WOO_COMMERCE]++;
            }

            if (!empty($result['platform_2_rest_id'])) {
                $formatedData[self::WEBSITE_GSS]++;
            }

            if (!empty($result['platform_3_rest_id'])) {
                $formatedData[self::WEBSITE_GOOGLE_MERCHANT]++;
            }

            if (!empty($result['platform_4_rest_id'])) {
                $formatedData[self::WEBSITE_GOOGLE_MERCHANT_GSS]++;
            }
        }

        return $formatedData;
    }

    public static function countVendors($options = [])
    {
        $additionalConditions = '';

        if (isset($options['p_ids'])) {
            if (count($options['p_ids']) > 0) {
                $additionalConditions .= ' AND id IN (' . implode(', ', $options['p_ids']) . ')';
            } else {
                $additionalConditions .= ' AND id IN (NULL)';
            }
        }

        $query = '
			SELECT vendor_id, count(*) as count FROM {{product}}
			WHERE status NOT IN (' . self::STATUS_DELETED . ')
			' . $additionalConditions . '
			GROUP BY vendor_id
		';

        $command = Yii::app()->db->createCommand($query);
        $results = $command->queryAll();

        $formatedData = [
            Vendor::INDEX_GEO_VISION => 0,
            Vendor::INDEX_MOTOBIX => 0,
            Vendor::INDEX_FLIR => 0,
            Vendor::INDEX_ACTI => 0
        ];

        foreach ($results as $result) {
            $formatedData[(int) $result['vendor_id']] = $result['count'];
        }

        return $formatedData;
    }

    public static function countPublishedData($options = [])
    {
        $additionalConditions = '';

        if (isset($options['p_ids'])) {
            if (count($options['p_ids']) > 0) {
                $additionalConditions .= ' AND id IN (' . implode(', ', $options['p_ids']) . ')';
            } else {
                $additionalConditions .= ' AND id IN (NULL)';
            }
        }

        $query = '
			SELECT * FROM {{product}}
			WHERE status NOT IN (' . self::STATUS_DELETED . ')
			' . $additionalConditions . '
		';

        $command = Yii::app()->db->createCommand($query);
        $results = $command->queryAll();

        return count($results);
    }

    public static function getHtmlFileList($options)
    {
        $additionalConditions = '';

        if (isset($options['p_ids'])) {
            if (count($options['p_ids']) > 0) {
                $additionalConditions .= ' AND id IN (' . implode(', ', $options['p_ids']) . ')';
            } else {
                $additionalConditions .= ' AND id IN (NULL)';
            }
        }

        $query = '
			SELECT batch_id FROM {{product}}
			WHERE status NOT IN (' . self::STATUS_DELETED . ')
			' . $additionalConditions . '
			GROUP BY batch_id
		';

        $command = Yii::app()->db->createCommand($query);
        $results = $command->queryAll();

        $html = '';

        foreach ($results as $result) {
            $fileID = (int) str_replace('BTC', '', $result['batch_id']);

            $vendorFile = VendorFile::model()->findByPk($fileID);
            $vendorFileupload = $vendorFile->fileupload;

            $html .= '<tr>';
            $html .= '<td>(#' . $vendorFile->id . ') ' . Vendor::getVendorNameLabel($vendorFile->vendor_id) . '</td>';
            $html .= '<td><small>' . $vendorFileupload->original_filename . '</small></td>';
            $html .= '<td>' . date('M, d Y h:i a', strtotime($vendorFileupload->date_created)) . '</td>';
            $html .= '</tr>';
        }

        if ($html == '') {
            $html = '<tr><td colspan="3">Empty...</td></tr>';
        }

        return $html;
    }

    public function getVendorFile()
    {
    }

    public static function getProductStatusLabel($index)
    {
        $list = [
            self::PRODUCT_STATUS_EXISTING => 'Existing',
            self::PRODUCT_STATUS_EOL => 'EOL',
        ];

        return $list[$index];
    }

    public static function apisBatchSyncProduct($vendorId, $page)
    {
        $gssRestIds = [];
        $sbbRestIds = [];

        $gss = new WooCommerceGSS();

        $gssProducts = $gss->getProductsByCategory($vendorId, $page);


        $sbb = new WooCommerce();

        $sbbProducts = $sbb->getProductsByCategory($vendorId, $page);
        /*if($gssProducts){
            foreach ($gssProducts as $gssProduct) {
                $appProduct = $this->model()->find(array(
                    'condition'
                ));
            }
        }*/
        $products['gssProducts'] = $gssProducts;
        $products['sbbProducts'] = $sbbProducts;
        return $products;
    }

    public static function apisBatchOverwrite($products, $params = [])
    {
        $gssRestIds = [];
        $sbbRestIds = [];

        // SBB API request
        $sbb = new WooCommerce();

        $sbbResponse = $sbb->batchOverwriteData($products);
        $sbbResponseOverwrite = isset($sbbResponse->update) ? $sbbResponse->update : null;

        if ($sbbResponse) {
            foreach ($sbbResponseOverwrite as $sbbResponseOverwriteData) {
                if (!isset($sbbResponseOverwriteData->error)) {
                    $sbbProductDbId = $sbbResponseOverwriteData->attributes[0]->options[0];
                    foreach ($products as $productKey => $productData) {
                        if ($productData['id'] == $sbbProductDbId) {
                            $products[$productKey]['link'] = $sbbResponseOverwriteData->permalink;
                            $products[$productKey]['image_link'] = $sbbResponseOverwriteData->images[0]->src;
                        }
                    }
                    foreach ($products as $productKey => $productData) {
                        if ($productData['id'] == $sbbProductDbId) {
                            $products[$productKey]['link'] = $sbbResponseOverwriteData->permalink;
                            $products[$productKey]['image_link'] = $sbbResponseOverwriteData->images[0]->src;
                        }
                    }

                    $sbbRestIds[$sbbProductDbId] = [
                        'rest_status' => 'ok',
                        'rest_id' => $sbbResponseOverwriteData->id
                    ];
                }
            }
        }

        // GSS API request
        $gss = new WooCommerceGSS();

        $gssResponse = $gss->batchOverwriteData($products);
        $gssResponseOverwrite = isset($gssResponse->update) ? $gssResponse->update : null;

        if ($gssResponse) {
            foreach ($gssResponseOverwrite as $gssResponseOverwriteData) {
                if (!isset($gssResponseOverwriteData->error)) {
                    $gssProductDbId = $gssResponseOverwriteData->attributes[0]->options[0];
                    foreach ($products as $productKey => $productData) {
                        if ($productData['id'] == $gssProductDbId) {
                            $products[$productKey]['link'] = $gssResponseOverwriteData->permalink;
                            $products[$productKey]['image_link'] = $gssResponseOverwriteData->images[0]->src;
                        }
                    }
                    $gssRestIds[$gssProductDbId] = [
                        'rest_status' => 'ok',
                        'rest_id' => $gssResponseOverwriteData->id
                    ];
                }
            }
        }

        foreach ($products as $productFeed) {
            $product = Product::model()->findByPk($productFeed['id']);

            // SBB
            if (array_key_exists($product->id, $sbbRestIds)) {
                $product->platform_1_rest_status = $params['success_status'];
                $product->platform_1_rest_id = $sbbRestIds[$product['id']]['rest_id'];
            } else {
                $product->platform_1_rest_status = $params['success_error'];
                $product->platform_3_rest_status = Product::REST_STATUS_PENDING;
            }

            // GSS
            if (array_key_exists($product->id, $gssRestIds)) {
                $product->platform_2_rest_status = $params['success_status'];
                $product->platform_2_rest_id = $gssRestIds[$product['id']]['rest_id'];
            } else {
                $product->platform_2_rest_status = $params['success_error'];
                $product->platform_4_rest_status = Product::REST_STATUS_PENDING;
            }

            $product->save(false);

            if (!empty($product->platform_1_rest_id)) {
                $sbbTmpData = $product->attributes + $product->productInfo->attributes;
                //$sbbTmpData['sbb_id'] = $product->platform_1_rest_id;
                $sbbTmpData['link'] = $productFeed['link'] ?: '';
                $sbbTmpData['image_link'] = $productFeed['image_link'] ?: '';
                $sbbProducts[] = $sbbTmpData;
            }

            if (!empty($product->platform_2_rest_id)) {
                $gssTmpData = $product->attributes + $product->productInfo->attributes;
                //$gssTmpData['gss_id'] = $product->platform_2_rest_id;
                $gssTmpData['link'] = $productFeed['link'] ?: '';
                $gssTmpData['image_link'] = $productFeed['image_link'] ?: '';
                $gssProducts[] = $gssTmpData;
            }
        }

        self::googleBatchInsertEditData($sbbProducts, $gssProducts, $params);
        return true;
    }

    public static function apisBatchInsertEditData($products, $params = [], $test = false, $googleFeedPublish)
    {
        if (Yii::app()->params['website_published_product_switch'] == false) {
            foreach ($products as $productData) {
                $product = Product::model()->findByPk($productData['id']);
                $product->platform_1_rest_status = Product::REST_STATUS_DISABLED;
                $product->platform_2_rest_status = Product::REST_STATUS_DISABLED;
                $product->platform_3_rest_status = Product::REST_STATUS_DISABLED;
                $product->platform_4_rest_status = Product::REST_STATUS_DISABLED;

                $product->save(false);
            }

            return true;
        }

        $sbbRestIds = [];
        $gssRestIds = [];

        // GSS API request
        $gss = new WooCommerceGSS();

        $gssInsertResponseStart = date('m-d-Y H:i:s');
        $gssResponse = $gss->batchInsertEditData($products);
        $gssInsertResponseEnd = date('m-d-Y H:i:s');
        $gssInsertResponse = strtotime($gssInsertResponseEnd) - strtotime($gssInsertResponseStart);
        $gssResponseCreate = isset($gssResponse->create) ? $gssResponse->create : null;
        $gssResponseUpdate = isset($gssResponse->update) ? $gssResponse->update : null;
        if ($gssResponseCreate) {
            foreach ($gssResponseCreate as $gssResponseCreateData) {
                if (!isset($gssResponseCreateData->error)) {
                    $gssProductDbId = $gssResponseCreateData->attributes[0]->options[0];

                    $gssRestIds[$gssProductDbId] = [
                        'rest_status' => 'ok',
                        'rest_id' => $gssResponseCreateData->id,
                        'rest_description' => $gssResponseCreateData->description,
                        'link' => $gssResponseCreateData->permalink,
                    ];
                } else {
                    /* $gssRestIds[$gssProductDbId] = [
                        'rest_error' => $gssResponseCreateData->error->message,
                    ]; */
                }
            }
        }

        if ($gssResponseUpdate) {
            foreach ($gssResponseUpdate as $gssResponseUpdateData) {
                if (!isset($gssResponseUpdateData->error)) {
                    $gssProductDbId = $gssResponseUpdateData->attributes[0]->options[0];

                    $gssRestIds[$gssProductDbId] = [
                        'rest_status' => 'ok',
                        'rest_id' => $gssResponseUpdateData->id,
                        'rest_description' => $gssResponseUpdateData->description,
                        'link' => $gssResponseUpdateData->permalink,
                    ];
                } else {
                    /* $gssRestIds[$gssProductDbId] = [
                        'rest_error' => $gssResponseUpdateData->error->message,
                    ]; */
                }
            }
        }

        // SBB API request
        $sbb = new WooCommerce();

        $sbbInsertResponseStart = date('m-d-Y H:i:s');
        $sbbResponse = $sbb->batchInsertEditData($products);
        $sbbInsertResponseEnd = date('m-d-Y H:i:s');
        $sbbInsertResponse = strtotime($sbbInsertResponseEnd) - strtotime($sbbInsertResponseStart);
        $sbbResponseCreate = isset($sbbResponse->create) ? $sbbResponse->create : null;
        $sbbResponseUpdate = isset($sbbResponse->update) ? $sbbResponse->update : null;
        if ($sbbResponseCreate) {
            foreach ($sbbResponseCreate as $sbbResponseCreateData) {
                if (!isset($sbbResponseCreateData->error)) {
                    $sbbProductDbId = $sbbResponseCreateData->attributes[0]->options[0];

                    $sbbRestIds[$sbbProductDbId] = [
                        'rest_status' => 'ok',
                        'rest_id' => $sbbResponseCreateData->id,
                        'rest_description' => $sbbResponseCreateData->description,
                        'link' => $sbbResponseCreateData->permalink,
                    ];
                } else {
                    /* $sbbRestIds[$sbbProductDbId] = [
                        'rest_error' => $sbbResponseCreateData->error->message,
                    ]; */
                }
            }
        }

        if ($sbbResponseUpdate) {
            foreach ($sbbResponseUpdate as $sbbResponseUpdateData) {
                if (!isset($sbbResponseUpdateData->error)) {
                    $sbbProductDbId = $sbbResponseUpdateData->attributes[0]->options[0];

                    $sbbRestIds[$sbbProductDbId] = [
                        'rest_status' => 'ok',
                        'rest_id' => $sbbResponseUpdateData->id,
                        'rest_description' => $sbbResponseUpdateData->description,
                        'link' => $sbbResponseUpdateData->permalink,
                    ];
                } else {
                    $sbbRestIds[$sbbProductDbId] = [
                        'rest_error' => $sbbResponseUpdateData->error->message,
                    ];
                }
            }
        }

        foreach ($products as $productFeed) {
            $product = Product::model()->findByPk($productFeed['id']);

            if (array_key_exists($product->id, $sbbRestIds) && !isset($sbbRestIds[$product->id]['rest_error'])) {
                $product->platform_1_rest_status = $params['success_status'];
                $product->platform_1_rest_id = $sbbRestIds[$product->id]['rest_id'];
                $product->platform_1_rest_error = null;
            } else {
                $product->platform_1_rest_status = $params['success_error'];
                $product->platform_1_rest_error = (isset($sbbRestIds[$product->id]['rest_error']) ? $sbbRestIds[$product->id]['rest_error'] : '');
                $product->platform_3_rest_status = Product::REST_STATUS_PENDING;
            }
            if (array_key_exists($product->id, $gssRestIds) && !isset($sbbRestIds[$product->id]['rest_error'])) {
                $product->platform_2_rest_status = $params['success_status'];
                $product->platform_2_rest_id = $gssRestIds[$product['id']]['rest_id'];
                $product->platform_2_rest_error = null;
            } else {
                $product->platform_2_rest_status = $params['success_error'];
                $product->platform_2_rest_error = (isset($gssRestIds[$product->id]['rest_error']) ? $gssRestIds[$product->id]['rest_error'] : '');
                $product->platform_4_rest_status = Product::REST_STATUS_PENDING;
            }

            if (array_key_exists($product->id, $sbbRestIds) || array_key_exists($product->id, $gssRestIds)) {
                $gssDescription = $gssRestIds[$product->id]['rest_description'] ?: '';
                $sbbDescription = $sbbRestIds[$product->id]['rest_description'] ?: '';
                $description = (strlen($gssDescription) > strlen($sbbDescription) ? $gssDescription : $sbbDescription);
            }

            if ($googleFeedPublish) {
                if ($product->product_status != Product::PRODUCT_STATUS_EOL) {
                    $product->platform_3_rest_status = Product::REST_STATUS_PENDING;
                    $product->platform_3_rest_error = "EOL Product";
                    $product->platform_4_rest_status = Product::REST_STATUS_PENDING;
                    $product->platform_4_rest_error = "EOL Product";
                }
            } else {
                $product->platform_3_rest_status = Product::REST_STATUS_DISABLED;
                $product->platform_3_rest_error = "Google feed disabled when publishing";
                $product->platform_4_rest_status = Product::REST_STATUS_DISABLED;
                $product->platform_4_rest_error = "Google feed disabled when publishing";
            }

            $product->save(false);
            $product->productInfo->description = $description;
            $product->productInfo->save(false);

            if ($googleFeedPublish) {
                if (!empty($product->platform_1_rest_id) && $product->product_status != Product::PRODUCT_STATUS_EOL) {
                    $sbbTmpData = $product->attributes + $product->productInfo->attributes;
                    $sbbTmpData['link'] = $sbbRestIds[$product['id']]['link'] ?: '';
                    // $sbbTmpData['image_link'] = $productFeed['sbbImageLink'];
                    $sbbProducts[] = $sbbTmpData;
                }

                if (!empty($product->platform_2_rest_id) && $product->product_status != Product::PRODUCT_STATUS_EOL) {
                    $gssTmpData = $product->attributes + $product->productInfo->attributes;
                    $gssTmpData['link'] = $gssRestIds[$product['id']]['link'] ?: '';
                    // $gssTmpData['image_link'] = $productFeed['gssImageLink'];
                    $gssProducts[] = $gssTmpData;
                }
            }
        }

        if ($googleFeedPublish) {
            $googleBatch = self::googleBatchInsertEditData($sbbProducts, $gssProducts, $params, $test);
            if ($test) {
                $response = [
                    'sbbResponse' => $sbbInsertResponse,
                    'gssResponse' => $gssInsertResponse,
                    'sbbGoogleResponse' => $googleBatch['sbbGoogleResponse'],
                    'gssGoogleResponse' => $googleBatch['gssGoogleResponse']
                ];
                return $response;
            }
        }
        return true;
    }

    public static function googleBatchInsertEditData($sbbProducts, $gssProducts, $params = [], $test = false)
    {
        $googleMerchantRestIds = [];
        $gssGoogleMerchantRestIds = [];
        // SBB Google Merchant API request
        if ($sbbProducts) {
            $googleMerchant = new GoogleMerchant();
            $googleMerchantResponseStart = date('m-d-Y H:i:s');
            $googleMerchantResponse = $googleMerchant->batchInsertEditData($sbbProducts, $params);
            $googleMerchantResponseEnd = date('m-d-Y H:i:s');
            $googleMerchantResponseTime = strtotime($googleMerchantResponseEnd) - strtotime($googleMerchantResponseStart);
            if ($googleMerchantResponse) {
                foreach ($googleMerchantResponse as $googleMerchantData) {
                    if (!isset($googleMerchantData->errors)) {
                        $googleMerchantRestIds[$googleMerchantData->batchId] = [
                            'rest_status' => 'ok',
                            'rest_id' => $googleMerchantData->product->id
                        ];
                    }
                }
            }
            foreach ($sbbProducts as $sbbProduct) {
                $product = Product::model()->findByPk($sbbProduct['id']);
                if (isset($googleMerchantRestIds[$product->id])) {
                    $product->platform_3_rest_status = $params['success_status'];
                    $product->platform_3_rest_id = $googleMerchantRestIds[$sbbProduct['id']]['rest_id'];
                } else {
                    $product->platform_3_rest_status = $params['success_error'];
                }
                $product->save(false);
            }
        }

        // GSS Google Merchant API request
        if ($gssProducts) {
            $gssGoogleMerchant = new GoogleMerchantGSS();
            $gssGoogleMerchantResponseStart = date('m-d-Y H:i:s');
            $gssGoogleMerchantResponse = $gssGoogleMerchant->batchInsertEditData($gssProducts, $params);
            $gssGoogleMerchantResponseEnd = date('m-d-Y H:i:s');
            $gssGoogleMerchantResponseTime = strtotime($gssGoogleMerchantResponseEnd) - strtotime($gssGoogleMerchantResponseStart);

            if ($gssGoogleMerchantResponse) {
                foreach ($gssGoogleMerchantResponse as $gssGoogleMerchantData) {
                    if (!isset($gssGoogleMerchantData->errors)) {
                        $gssGoogleMerchantRestIds[$gssGoogleMerchantData->batchId] = [
                            'rest_status' => 'ok',
                            'rest_id' => $gssGoogleMerchantData->product->id
                        ];
                    }
                }
            }

            foreach ($gssProducts as $gssProduct) {
                $product = Product::model()->findByPk($gssProduct['id']);

                if (array_key_exists($product->id, $gssGoogleMerchantRestIds)) {
                    $product->platform_4_rest_status = $params['success_status'];
                    $product->platform_4_rest_id = $gssGoogleMerchantRestIds[$gssProduct['id']]['rest_id'];
                } else {
                    $product->platform_4_rest_status = $params['success_error'];
                }

                $product->save(false);
            }
        }
        if ($test) {
            $response = array(
                'sbbGoogleResponse' => $googleMerchantResponseTime,
                'gssGoogleResponse' => $gssGoogleMerchantResponseTime,
            );
            return $response;
        }
        return true;
    }

    public static function apisBatchDeleteData($products, $restStatus = [])
    {
        if (Yii::app()->params['website_published_product_switch'] == false) {
            foreach ($products as $productData) {
                $product = Product::model()->findByPk($productData['id']);

                $product->platform_1_rest_status = Product::REST_STATUS_DISABLED;
                $product->platform_2_rest_status = Product::REST_STATUS_DISABLED;
                $product->platform_3_rest_status = Product::REST_STATUS_DISABLED;
                $product->platform_4_rest_status = Product::REST_STATUS_DISABLED;

                $product->save(false);
            }

            return true;
        }

        $sbbRestIds = [];
        $gssRestIds = [];
        $googleMerchantRestIds = [];
        $gssGoogleMerchantRestIds = [];

        $gss = new WooCommerceGSS();
        $gssResponse = $gss->batchDelete($products);

        if ($gssResponse && $gssResponse->delete) {
            foreach ($gssResponse->delete as $gssResponseDeleteData) {
                if (!isset($gssResponseDeleteData->error)) {
                    $gssRestIds[$gssResponseDeleteData->attributes[0]->options[0]] = [
                        'rest_status' => 'ok',
                        'rest_id' => ''
                    ];
                }
            }
        }

        $sbb = new WooCommerce();
        $sbbResponse = $sbb->batchDelete($products);

        if ($sbbResponse && $sbbResponse->delete) {
            foreach ($sbbResponse->delete as $sbbResponseDeleteData) {
                if (!isset($sbbResponseDeleteData->error)) {
                    $sbbRestIds[$sbbResponseDeleteData->attributes[0]->options[0]] = [
                        'rest_status' => 'ok',
                        'rest_id' => ''
                    ];
                }
            }
        }


        $googleMerchant = new GoogleMerchant();
        $googleMerchantResponse = $googleMerchant->batchDelete($products);

        if ($googleMerchantResponse) {
            foreach ($googleMerchantResponse as $googleMerchBatchDeleteData) {
                if (!isset($googleMerchBatchDeleteData->errors)) {
                    $googleMerchantRestIds[$googleMerchBatchDeleteData->batchId] = [
                        'rest_status' => 'ok',
                        'rest_id' => ''
                    ];
                }
            }
        }


        $gssGoogleMerchant = new GoogleMerchantGSS();
        $gssGoogleMerchantResponse = $gssGoogleMerchant->batchDelete($products);

        if ($gssGoogleMerchantResponse) {
            foreach ($gssGoogleMerchantResponse as $gssGoogleMerchBatchDeleteData) {
                if (!isset($gssGoogleMerchBatchDeleteData->errors)) {
                    $gssGoogleMerchantRestIds[$gssGoogleMerchBatchDeleteData->batchId] = [
                        'rest_status' => 'ok',
                        'rest_id' => ''
                    ];
                }
            }
        }

        foreach ($products as $product) {
            $product = Product::model()->findByPk($product['id']);
            $errors = 0;

            // if (array_key_exists($product->id, $sbbRestIds)) {
            // $product->platform_1_rest_status = $restStatus['success_status'];
            // $product->platform_1_rest_id = null;
            // } else {
            // $product->platform_1_rest_status = $restStatus['success_error'];

            // if (!empty($product->platform_1_rest_id)) {
            // $errors++;
            // }
            // }

            if (array_key_exists($product->id, $gssRestIds)) {
                $product->platform_2_rest_status = $restStatus['success_status'];
                $product->platform_2_rest_id = null;
            } else {
                $product->platform_2_rest_status = $restStatus['success_error'];

                if (!empty($product->platform_2_rest_id)) {
                    $errors++;
                }
            }

            if (array_key_exists($product->id, $sbbRestIds)) {
                $product->platform_1_rest_status = $restStatus['success_status'];
                $product->platform_1_rest_id = null;
            } else {
                $product->platform_1_rest_status = $restStatus['success_error'];

                if (!empty($product->platform_1_rest_id)) {
                    $errors++;
                }
            }

            if (array_key_exists($product->id, $googleMerchantRestIds)) {
                $product->platform_3_rest_status = $restStatus['success_status'];
                $product->platform_3_rest_id = null;
            } else {
                $product->platform_3_rest_status = $restStatus['success_error'];

                if (!empty($product->platform_3_rest_id)) {
                    $errors++;
                }
            }

            if (array_key_exists($product->id, $gssGoogleMerchantRestIds)) {
                $product->platform_4_rest_status = $restStatus['success_status'];
                $product->platform_4_rest_id = null;
            } else {
                $product->platform_4_rest_status = $restStatus['success_error'];

                if (!empty($product->platform_4_rest_id)) {
                    $errors++;
                }
            }

            $product->save(false);

            if ($errors <= 0) {
                $product->status = Product::STATUS_DELETED;
                $product->save(false);
            }
        }

        return true;
    }

    public static function getPlatformSuccessStatus()
    {
        return [
            self::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS,
            self::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS,
            self::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS,
            self::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS
        ];
    }

    public static function getRestStatusLabel($index, $plaformNo)
    {
        $list = [
            self::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS => 'API : Successfully Added / Updated',
            self::REST_STATUS_PUBLISH_ADD_DATA_ERROR => 'API : Failed to Add',

            self::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS => 'API : Successfully Deleted',
            self::REST_STATUS_PUBLISH_DELETE_DATA_ERROR => 'API : Failed to Delete',

            self::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS => 'API : Successfully Edited / Republished',
            self::REST_STATUS_PUBLISH_EDIT_DATA_ERROR => 'API : Failed to Edit / Republished',

            self::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS => 'API : Successfully Edited Product Status',
            self::REST_STATUS_PUBLISH_EDIT_STATUS_ERROR => 'API : Failed to Edit Product Status',


            self::REST_STATUS_DISABLED => 'API : Live Publish is Disabled',
            self::REST_STATUS_PENDING => 'API : Product not yet Publish'
        ];

        if (!in_array($index, self::getPlatformSuccessStatus())) {
            if (in_array($plaformNo, [self::REST_STATUS_DISABLED, self::REST_STATUS_PENDING])) {
                if (!in_array($index, self::getPlatformSuccessStatus())) {
                    return 'API : Invalid or Duplicate SKU';
                }
            }
        }

        return $list[$index];
    }

    public static function getRestStatusContent($index, $rest, $error)
    {
        $list = [
            self::REST_STATUS_PUBLISH_ADD_DATA_SUCCESS => 'Product was added / updated in website',
            self::REST_STATUS_PUBLISH_ADD_DATA_ERROR => 'Product data was failed to add in website due to possible reasons: <ul>
        <li>'.$error.'</li>',

            self::REST_STATUS_PUBLISH_DELETE_DATA_SUCCESS => 'Product was deleted in website',
            self::REST_STATUS_PUBLISH_DELETE_DATA_ERROR => 'Product failed to delete in website due to possible reasons: <ul>
        <li>Product already deleted in website.</li>
    </ul>',

            self::REST_STATUS_PUBLISH_EDIT_DATA_SUCCESS => 'Product data was edited in website',
            self::REST_STATUS_PUBLISH_EDIT_DATA_ERROR => 'Product data was failed to edit in website due to possible reasons:
    <ul>
        <li>duplicate product SKU</li>
    </ul><strong>Fix:</strong> update product SKU',

            self::REST_STATUS_PUBLISH_EDIT_STATUS_SUCCESS => 'Product status was updated in website',
            self::REST_STATUS_PUBLISH_EDIT_STATUS_ERROR => 'Product status was failed to edit in website due to possible
    reasons: <ul>
	<li>'.$error.'</li>
    </ul><strong>Fix:</strong> update product SKU',

            self::REST_STATUS_DISABLED => 'Publishing flag for products was disabled.',
            self::REST_STATUS_PENDING => 'Product not yet publish in live. try to republish and checked if there are any errors'
        ];

        return $list[$index];
    }

    public function hasPendingPriceLevel()
    {
        $pendingPriceLevel = ProductPricingTierLookup::model()->find([
            'condition' => 'product_id = :product_id AND woocommerce_status = :woocommerce_status',
            'params' => [
                ':product_id' => $this->id,
                ':woocommerce_status' => ProductPricingTierLookup::WC_STATUS_PENDING
            ]
        ]);

        if ($pendingPriceLevel) {
            return true;
        } else {
            return false;
        }
    }
}
