<?php
/***************************************************************************
 *																		*
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.	*
 *																		  *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.													*
 *																		  *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.			*
 ****************************************************************************/ //
//$Id: SchemaModel.php, v 1.1 2012/12/24 20:52:11
//
class ProductSchemaModel extends Model {
    public function getSchema($params = array()) {
        extract($params);
        $timeZone = '';
        if (!empty($primaryID)) {
            $conditionArry = array(
                'productID' => $primaryID
            );
        } else {
            $conditionArry = array();
        }
        if (!empty($pre_process)) {
            $timeZone = $pre_process['productTimeZone'];
        }
        $default_currency = isset($default_currency) ? $default_currency : '';
        $schema           = array(
            'section' => 'products',
            'name' => 'products',
            'pattern_id' => 'products',
            'key' => array(
                'productID'
            ),
            'table' => 'products',
            'alt_table' => 'product_options',
            'condition' => $conditionArry,
            'references' => array(
                'product_details' => array(
                    'reference_fields' => array(
                        'productID' => '#key',
                        'languageID' => '1'
                    ),
                    'join_type' => 'LEFT'
                ),
                'product_options' => array(
                    'reference_fields' => array(
                        'productID' => '#key',
                        'productOptionDefault' => 'Yes'
                    ),
                    'join_type' => 'LEFT'
                )
            ),
            'post_processing' => array(
                'fn_exim_reset_extra',
                '$insert_ids',
                '1',
                $timeZone,
                $default_currency
            ),
            'notes' => array(
                'text_exim_import_options_note',
                'text_exim_import_features_note',
                'text_exim_import_images_note',
                'text_exim_import_files_note'
            ),
            'options' => array(
                '@images_path' => array(
                    'title' => 'images_directory',
                    'description' => 'text_images_directory',
                    'type' => 'input',
                    'default_value' => 'DIR_IMAGES' . 'backup'
                ),
                'files_path' => array(
                    'title' => 'files_directory',
                    'description' => 'text_files_directory',
                    'type' => 'input',
                    'default_value' => 'DIR_DOWNLOADS' . 'backup'
                )
            ),
            'export_fields' => array(
                'productID' => array(
                    'db_field' => 'productID',
                    'alt_key' => true
                ),
                'productUrl' => array(
                    'db_field' => 'productUrl',
                    'pre_insert' => array(
                        'fn_put_checkExists',
                        '#this',
                        'products',
                        'productUrl',
                        " productStatus!='Deleted'"
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product URL is required'
                    )
                ),
                'businessID' => array(
                    'db_field' => 'businessID',
                    'validateIt' => array(
                        'business',
                        'businessID',
                        " businessStatus IN ('Active','Inactive')"
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Business is required'
                    )
                    
                ),
                'isProductDeal' => array(
                    'db_field' => 'isProductDeal',
                    
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Type is required'
                    )
                ),
                'dealStartTime' => array(
                    'db_field' => 'dealStartTime',
                    'process_get' => array(
                        'fn_timestamp_to_date',
                        $this,
                        '#this'
                    ),
                    'convert_put' => array(
                        'fn_date_to_save'
                    ),
                    'return_result' => true
                ),
				'dealEndTime' => array(
                    'db_field' => 'dealEndTime',
                    'process_get' => array(
                        'fn_timestamp_to_date',
                        $this,
                        '#this'
                    ),
                    'convert_put' => array(
                        'fn_date_to_save'
                    ),
                    'return_result' => true
                ),
				'dealDiscount' => array(
                    'db_field' => 'dealDiscount',
                    
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Deal Discount is required'
                    )
                ),
				'dealMaxBuyLimit' => array(
                    'db_field' => 'dealMaxBuyLimit',
                    
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Deal Max Buy Limit is required'
                    )
                ),
                'optionSKU' => array(
                    'table' => 'product_options',
                    'db_field' => 'optionSKU',
                    'pre_insert' => array(
                                    'fn_put_checkExists',
                                    '#this',
                                    'product_options',
                                    'optionSKU',
                                    " productOptionStatus!='Deleted'"
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'OptionSKU is required'
                    )
                ),
                'variantTitle' => array(
                    'linked' => false,
                    'process_get' => array(
                        'fn_exim_export_oname',
                        $this,
                        '#key'
                    ),
                    'process_put' => array(
                        'fn_exim_set_oname',
                        '#key',
                        '#this',
                        '%optionSKU%',
                        '1',
                        '%productTitle%'
                    ),
                    'return_result' => true,
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Variant Title is required'
                    )
                ),
                'productOptionProductPrice' => array(
                    'table' => 'product_options',
                    'db_field' => 'productOptionProductPrice',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product Price is required'
                    )
                ),
                'productOptionRegularPrice' => array(
                    'table' => 'product_options',
                    'db_field' => 'productOptionRegularPrice',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product Regular Price is required'
                    )
                ),
                'productOptionQuantity' => array(
                    'table' => 'product_options',
                    'db_field' => 'productOptionQuantity',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Quantity is required'
                    )
                ),
                'boxSize' => array(
                    'process_get' => array(
                        'fn_exim_get_box_size',
                        $this,
                        '#key'
                    ),
                    'process_put' => array(
                        'fn_exim_put_box_size',
                        $this,
                        '#key',
                        '#this'
                    ),
                    'linked' => false
                ),
                'Category' => array(
                    'process_get' => array(
                        'fn_exim_get_product_categories',
                        $this,
                        '#key',
                        '1'
                    ),
                    'process_put' => array(
                        'fn_exim_set_product_categories',
                        $this,
                        '#key',
                        '#this',
                        '1',
                        '%URL Key%',
                        '%Product Name%'
                    ),
                    'linked' => false,
                    'default' => 'Products',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Category is required'
                    )
                ),
                'productStatus' => array(
                    'db_field' => 'productStatus',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product Status is required'
                    )
                ),
                'productDefaultCurrency' => array(
                    'db_field' => 'productDefaultCurrency',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Currency is required'
                    )
                ),
                'productMinBuyLimit' => array(
                    'db_field' => 'productMinBuyLimit',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Min Buy Limit is required'
                    )
                ),
                'productMaxBuyLimit' => array(
                    'db_field' => 'productMaxBuyLimit',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Max Buy Limit is required'
                    )
                ),
                'productStartTime' => array(
                    'db_field' => 'productStartTime',
                    'process_get' => array(
                        'fn_timestamp_to_date',
                        $this,
                        '#this'
                    ),
                    'convert_put' => array(
                        'fn_date_to_save'
                    ),
                    'return_result' => true
                ),
                'productEndTime' => array(
                    'db_field' => 'productEndTime',
                    'process_get' => array(
                        'fn_timestamp_to_date',
                        $this,
                        '#this'
                    ),
                    'convert_put' => array(
                        'fn_date_to_save'
                    ),
                    'return_result' => true
                ),
                'showCountTimer' => array(
                    'db_field' => 'showCountTimer'
                ),
                'featuredStatus' => array(
                    'db_field' => 'featuredStatus'
                ),
                'InventoryTrackLevel' => array(
                    'db_field' => 'InventoryTrackLevel'
                ),
                'productImage' => array(
                    'db_field' => 'productImage',
                    'process_get' => array(
                        'fn_exim_get_image_string',
                        $this,
                        '#this',
                        'product'
                    )
                ),
                'fileMimeType' => array(
                    'db_field' => 'productImage',
                    'process_get' => array(
                        'fn_exim_get_image_type',
                        $this,
                        '#this',
                        'product'
                    )
                ),
                'Detailed image' => array(
                    'db_field' => 'productImage',
                    'process_put' => array(
                        'fn_exim_set_product_image',
                        $this,
                        //'@images_path',
                        '%Preview Image%',
                        '#key',
                        '#this',
                        '%productUrl%',
                        '$fileMimeType'
                    )
                ),
                'taxClassID' => array(
                    'db_field' => 'taxClassID'
                ),
                'taxPayableToBusiness' => array(
                    'db_field' => 'taxPayableToBusiness'
                ),
                'productDescription' => array(
                    'table' => 'product_details',
                    'db_field' => 'productDescription',
                    'process_get' => array(
                        'fn_html_entity_decode',
                        $this,
                        '#this'
                    ),
                    'return_result' => true,
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product Description is required'
                    )
                ),
                'productHighlights' => array(
                    'table' => 'product_details',
                    'db_field' => 'productHighlights',
                    'process_get' => array(
                        'fn_html_entity_decode',
                        $this,
                        '#this'
                    ),
                    'return_result' => true
                ),
                'productMetaKeywords' => array(
                    'table' => 'product_details',
                    'db_field' => 'productMetaKeywords'
                ),
                'productMetaDescription' => array(
                    'table' => 'product_details',
                    'db_field' => 'productMetaDescription'
                ),
                'searchTags' => array(
                    'table' => 'product_details',
                    'db_field' => 'searchTags'
                ),
                'productTitle' => array(
                    'table' => 'product_details',
                    'db_field' => 'productTitle',
                    'process_get' => array(
                        'fn_html_entity_decode',
                        $this,
                        '#this'
                    ),
                    'return_result' => true,
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product Title is required'
                    )
                ),
                'productMetaTitle' => array(
                    'table' => 'product_details',
                    'process_get' => array(
                        'fn_html_entity_decode',
                        '#this'
                    ),
                    'db_field' => 'productMetaTitle'
                ),
                'multiOptionsAvailable' => array(
                    'db_field' => 'multiOptionsAvailable'
                ),
                'productOptions' => array(
                    'process_get' => array(
                        'fn_exim_get_product_options',
                        $this,
                        '#key',
                        '1'
                    ),
                    'process_put' => array(
                        'fn_exim_set_product_options',
                        $this,
                        '#key',
                        '#this',
                        '1',
                        '%productUrl%'
                    ),
                    'linked' => false,
                    'return_result' => true
                ),
                'customOptions' => array(
                    'process_get' => array(
                        'fn_exim_get_product_custom_options',
                        $this,
                        '#key',
                        '1'
                    ),
                    'process_put' => array(
                        'fn_exim_set_product_custom_options',
                        $this,
                        '#key',
                        '#this',
                        '1'
                    ),
                    'linked' => false,
                    'return_result' => true
                ),
                'attributeSetID' => array(
                    'db_field' => 'attributeSetID',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Attribute Set is required'
                    )
                ),
                'Attribute Set name' => array(
                    'process_get' => array(
                        'fn_exim_export_setname',
                        $this,
                        '#this'
                    ),
                    'db_field' => 'attributeSetID'
                ),
                'attributes' => array(
                    'linked' => false,
                    'process_get' => array(
                        'fn_exim_get_product_attributes',
                        $this,
                        '#key',
                        '1'
                    ),
                    'process_put' => array(
                        'fn_exim_set_product_attributes',
                        $this,
                        '#key',
                        '%Attribute Set name%',
                        '#this',
                        '1'
                    ),
                    'return_result' => true
                ),
                /**************************************************************/
                'productTypeID' => array(
                    'db_field' => 'productTypeID',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product Type ID is required'
                    )
                ),
                'isTaxable' => array(
                    'db_field' => 'isTaxable'
                ),
                'taxRate' => array(
                    'db_field' => 'taxRate'
                ),
                'productKey' => array(
                    'db_field' => 'productKey'
                ),
                'measurementLength' => array(
                    'db_field' => 'measurementLength'
                ),
                'measurementWeight' => array(
                    'db_field' => 'measurementWeight'
                ),
                'productTimeZone' => array(
                    'db_field' => 'productTimeZone'
                ),
                'productMaxGiftBuy' => array(
                    'db_field' => 'productMaxGiftBuy'
                ),
                'productMinQntyReqToTipp' => array(
                    'db_field' => 'productMinQntyReqToTipp'
                ),
                
                'productExpiryDate' => array(
                    'db_field' => 'productExpiryDate'
                ),'productCommissionRate' => array(
                    'db_field' => 'productCommissionRate'
                ),'productUseGlobalCommision' => array(
                    'db_field' => 'productUseGlobalCommision'
                ),'productCommissionType' => array(
                    'db_field' => 'productCommissionType'
                ),'enablePrepay' => array(
                    'db_field' => 'enablePrepay'
                ),'applyCommissionFrom' => array(
                    'db_field' => 'applyCommissionFrom'
                ),'isfreeShipping' => array(
                    'db_field' => 'isfreeShipping'
                ),'shippingPayableToBusiness' => array(
                    'db_field' => 'shippingPayableToBusiness'
                ),'codAvailable' => array(
                    'db_field' => 'codAvailable'
                ),'allowRefund' => array(
                    'db_field' => 'allowRefund'
                ),'collectPaymentWhen' => array(
                    'db_field' => 'collectPaymentWhen'
                ),'generateCertificateWhen' => array(
                    'db_field' => 'generateCertificateWhen'
                ),'productServiceFee' => array(
                    'db_field' => 'productServiceFee'
                ),'useCertCollection' => array(
                    'db_field' => 'useCertCollection'
                ),'productVisibleTo' => array(
                    'db_field' => 'productVisibleTo'
                ),'productShowNosBought' => array(
                    'db_field' => 'productShowNosBought'
                ),
                'productShowProductTipped' => array(
                    'db_field' => 'productShowProductTipped'
                ),
                'productShowVideo' => array(
                    'db_field' => 'productShowVideo'
                ),
                'productOnlineRedemption' => array(
                    'db_field' => 'productOnlineRedemption'
                ),
                'productRedemptionType' => array(
                    'db_field' => 'productRedemptionType'
                ),
                'productVideo' => array(
                    'db_field' => 'productVideo'
                ),
                'productPriority' => array(
                    'db_field' => 'productPriority'
                ),
                'productQuantityNotifyAt' => array(
                    'db_field' => 'productQuantityNotifyAt'
                ),
                'outofStockStatus' => array(
                    'db_field' => 'outofStockStatus'
                ),
                'productCreatedDate' => array(
                    'db_field' => 'productCreatedDate'
                ),'productUpdatedDate' => array(
                    'db_field' => 'productUpdatedDate'
                ),'productTippedDate' => array(
                    'db_field' => 'productTippedDate'
                ),'shippingStatus' => array(
                    'db_field' => 'shippingStatus'
                ),
                
                'shippingSetting' => array(
                    'db_field' => 'shippingSetting'
                ),
                'productAddedBy' => array(
                    'db_field' => 'productAddedBy'
                ),
                'shippingOrigin' => array(
                    'db_field' => 'shippingOrigin'
                ),
                'showQuantityAvailable' => array(
                    'db_field' => 'showQuantityAvailable'
                ),
                
                'productSoldQuantity' => array(
                    'db_field' => 'productSoldQuantity'
                ),
                'popularity' => array(
                    'db_field' => 'popularity'
                ),
                'purchasePopularity' => array(
                    'db_field' => 'purchasePopularity'
                ),
                /****************************************************************/
                
            )
        );
        $get              = isset($get) ? $get : '';
        $schema           = $this->setFilter($get, $conditionArry, $schema, $params);
        return $schema;
    }
    public function getOptionsSchema($params = array()) {
        extract($params);
        if (!empty($primaryID)) {
            $conditionArry = array(
                'productID' => $primaryID
            );
        } else {
            $conditionArry = array();
            $timeZone      = '';
        }
        if (!empty($pre_process)) {
            $timeZone = $pre_process['productTimeZone'];
        }
        $schema = array(
            'section' => 'products_options',
            'name' => 'products_options',
            'pattern_id' => 'products_options',
            'key' => array(
                'productOptionID'
            ),
            'table' => 'product_options',
            'alt_table' => 'product_options',
            'condition' => $conditionArry,
            'references' => array(
                'product_option_details' => array(
                    'reference_fields' => array(
                        'productOptionID' => '#key',
                        'languageID' => '1'
                    ),
                    'join_type' => 'LEFT'
                ),
                'products' => array(
                    'reference_fields' => array(
                        'productID' => '&productID'
                    ),
                    'join_type' => 'INNER'
                )
            ),
            'export_fields' => array(
                'productOptionID' => array(
                    'db_field' => 'productOptionID',
                    'alt_key' => true
                ),
                'productID' => array(
                    'db_field' => 'productID',
                    'validateIt' => array(
                        'products',
                        'productID',
                        " productStatus IN ('Active','Inactive')"
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product is required'
                    )
                ),
                'optionSKU' => array(
                    'db_field' => 'optionSKU',
                     'pre_insert' => array(
                                    'fn_put_checkExists',
                                    '#this',
                                    'product_options',
                                    'optionSKU',
                                    " productOptionStatus!='Deleted'",
                                    'productID',
                                    '&productID'
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Option SKU is required'
                    )
                ),
                'productOptionName' => array(
                    'db_field' => 'productOptionName',
                    'table' => 'product_option_details',
                    'process_get' => array(
                        'fn_html_entity_decode',
                        '#this'
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product Option name is required'
                    )
                ),
                'optionBarCode' => array(
                    'db_field' => 'optionBarCode'
                ),
                'productOptionRegularPrice' => array(
                    'db_field' => 'productOptionRegularPrice',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Regular price is required'
                    )
                ),
                'productOptionProductPrice' => array(
                    'db_field' => 'productOptionProductPrice',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product product price is required'
                    )
                ),
                'productOptionShowVideo' => array(
                    'db_field' => 'productOptionShowVideo'
                ),
                'productPrepayAmount' => array(
                    'db_field' => 'productPrepayAmount'
                ),
                'productOptionQuantity' => array(
                    'db_field' => 'productOptionQuantity',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Quantity is required'
                    )
                ),
                'productQuantityNotifyAt' => array(
                    'db_field' => 'productQuantityNotifyAt'
                ),
                'packageWeight' => array(
                    'db_field' => 'packageWeight'
                ),
                'packageLength' => array(
                    'db_field' => 'packageLength'
                ),
                'packageWidth' => array(
                    'db_field' => 'packageWidth'
                ),
                'packageHeight' => array(
                    'db_field' => 'packageHeight'
                ),
                'productQuantityUnlimited' => array(
                    'db_field' => 'productQuantityUnlimited'
                ),
                'soldQuantity' => array(
                    'db_field' => 'soldQuantity'
                ),
                'productOptionStatus' => array(
                    'db_field' => 'productOptionStatus',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Option status is required'
                    )
                ),
                'productOptionDefault' => array(
                    'db_field' => 'productOptionDefault',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Option Default is required'
                    )
                ),
                'productOptionImages' => array(
                    'process_get' => array(
                        'fn_exim_get_product_option_images',
                        $this,
                        '#key',
                        '$productOptionID',
                        '1'
                    ),
                    'process_put' => array(
                        'fn_exim_set_product_option_images',
                        $this,
                        '$productID',
                        '#key',
                        '#this',
                        '1'
                    ),
                    'linked' => false,
                    'return_result' => true
                )
            )
        );
        $get    = isset($get) ? $get : '';
        $schema = $this->setFilter($get, $conditionArry, $schema, $params);
        return $schema;
    }
    public function getCustomoptionsSchema($params = array()) {
        extract($params);
        if (!empty($primaryID)) {
            $conditionArry = array();
        }
        if (!empty($pre_process)) {
            $timeZone = $pre_process['productTimeZone'];
        }
        $conditionArry = isset($conditionArry) ? $conditionArry : '';
        $primaryID     = isset($primaryID) ? $primaryID : '';
        $schema        = array(
            'section' => 'product_custom_option',
            'name' => 'product_custom_option',
            'pattern_id' => 'product_custom_option',
            'key' => array(
                'customOptionID'
            ),
            'table' => 'product_custom_option',
            'alt_table' => 'product_custom_option',
            'condition' => $conditionArry,
            'references' => array(
                'product_custom_option_details' => array(
                    'reference_fields' => array(
                        'customOptionID' => '#key',
                        'languageID' => '1'
                    ),
                    'join_type' => 'LEFT'
                ),
                'product_custom_option_link' => array(
                    'reference_fields' => array(
                        'customOptionID' => '#key',
                        'productID' => $primaryID
                    ),
                    'join_type' => 'INNER'
                ),
                'products' => array(
                    'reference_fields' => array(
                        'productID' => $primaryID
                    ),
                    'join_type' => 'INNER'
                )
            ),
            'export_fields' => array(
                'customOptionID' => array(
                    'db_field' => 'customOptionID',
                    'alt_key' => true
                ),
                'customOptionName' => array(
                    'db_field' => 'customOptionName',
                    'table' => 'product_custom_option_details',
                    'process_get' => array(
                        'fn_html_entity_decode',
                        '#this'
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Custom option name is required'
                    )
                ),
                'validationMessage' => array(
                    'db_field' => 'validationMessage',
                    'table' => 'product_custom_option_details',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Validation message  is required'
                    )
                ),
                'inputType' => array(
                    'db_field' => 'inputType',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Input type is required'
                    )
                ),
                'validateRule' => array(
                    'db_field' => 'validateRule',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Validate rule is required'
                    )
                ),
                'priceDiff' => array(
                    'db_field' => 'priceDiff',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Price Difference is required'
                    )
                ),
                'priceDiffType' => array(
                    'db_field' => 'priceDiffType',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Difference Type is required'
                    )
                ),
                'helpText' => array(
                    'db_field' => 'helpText',
                    'table' => 'product_custom_option_details'
                ),
                'isGlobal' => array(
                    'db_field' => 'isGlobal'
                ),
                'variants' => array(
                    'process_get' => array(
                        'fn_exim_get_product_custom_options_variant',
                        $this,
                        '#key',
                        '1'
                    ),
                    'process_put' => array(
                        'fn_exim_set_product_custom_options_variant',
                        $this,
                        '#key',
                        '#this',
                        '1'
                    ),
                    'linked' => false,
                    'return_result' => true
                )
            )
        );
        $get           = isset($get) ? $get : '';
        $schema        = $this->setFilter($get, $conditionArry, $schema, $params);
        return $schema;
    }
    public function getCombinationSchema($params = array()) {
        extract($params);
        if (!empty($primaryID))
            $conditionArry = array(
                '&products.productID' => $primaryID
            );
        else
            $conditionArry = array();
        $schema = array(
            'section' => 'products',
            'name' => 'product_combinations',
            'pattern_id' => 'product_combinations',
            'condition' => $conditionArry,
            'key' => array(
                'combinationID'
            ),
            'table' => 'product_combination',
            'ref_table' => 'products',
            'references' => array(
//                'product_options' => array(
//                    'reference_fields' => array(
//                        'productOptionID' => '&productOptionID'
//                    ),
//                    'join_type' => 'LEFT'
//                ),
//                'product_option_details' => array(
//                    'reference_fields' => array(
//                        'productOptionID' => '%productOptionID',
//                        'languageID' => '1'
//                    ),
//                    'join_type' => 'LEFT'
//                ),
                'products' => array(
                    'reference_fields' => array(
                        'productID' => '%productID'
                    ),
                    'join_type' => 'INNER'
                )
            ),
            'export_fields' => array(
                'combinationID' => array(
                    'db_field' => 'combinationID',
                    'alt_key' => true
                ),
                'productID' => array(
                    'db_field' => 'productID',
                    'validateIt' => array(
                        'products',
                        'productID',
                        " productStatus IN ('Active','Inactive')"
                    ),
                    'table' => 'products',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product is required'
                    )
                ),
//                'productOptionID' => array(
//                    'db_field' => 'productOptionID',
//                    'validateIt' => array(
//                        'product_options',
//                        'productOptionID',
//                        " productOptionStatus IN ('Active','Inactive')"
//                    ),
//                    'table' => 'product_options',
//                    'validate' => array(
//                        'required'
//                    ),
//                    'error' => array(
//                        'Option is required'
//                    )
//                ),
//                'optionSKU' => array(
//                    'db_field' => 'optionSKU',
//                    'table' => 'product_options',
//                    'validate' => array(
//                        'required'
//                    ),
//                    'error' => array(
//                        'Option SKU is required'
//                    )
//                ),
//                'productOptionName' => array(
//                    'table' => 'product_option_details',
//                    'db_field' => 'productOptionName',
//                    'validate' => array(
//                        'required'
//                    ),
//                    'error' => array(
//                        'Option Name is required'
//                    )
//                ),
                'combinationBarCode' => array(
                    'db_field' => 'combinationBarCode',
                ),
                'combinationSKU' => array(
                    'db_field' => 'combinationSKU',
                    'pre_insert' => array(
                                    'fn_put_checkExists',
                                    '#this',
                                    'product_combination',
                                    'combinationSKU',
                                    " status!='D'"
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Combination SKU is required'
                    )
                ),
                'combination' => array(
                    'db_field' => 'combination',
                    'pre_insert' => array(
                                    'fn_put_checkCombinationExists',
                                    '#this',
                                    '$productID',
                                    'product_combination',
                                    'combinationSKU',
                                    " status!='D'"
                    ),
                    'process_get' => array(
                        'fn_exim_get_product_combination',
                        $this,
                        '#this',
                        '1'
                    ),
                    'process_put' => array(
                        'fn_exim_put_product_combination',
                        $this,
                        '#key',
                        '%productID%',
                        '#this',
                        '1'
                    )
                ),
                'combinationQty' => array(
                    'db_field' => 'combinationQty',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Quantity is required'
                    )
                ),
                'combinationPrice' => array(
                    'db_field' => 'combinationPrice',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Price is required'
                    )
                ),
                'combinationPriceDiffType' => array(
                    'db_field' => 'combinationPriceDiffType',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Difference Type is required'
                    )
                ),
                'combinationWeight' => array(
                    'db_field' => 'combinationWeight',
                ),
                'combinationWeightDiffType' => array(
                    'db_field' => 'combinationWeight',
                ),
                'combinationHeight' => array(
                    'db_field' => 'combinationHeight',
                ),
                'combinationWidth' => array(
                    'db_field' => 'combinationWidth',
                ),
                'combinationLength' => array(
                    'db_field' => 'combinationLength',
                ),
                'productCombinationImages' => array(
                    'process_get' => array(
                        'fn_exim_get_product_combination_images',
                        $this,
                        '#key',
                        '$combinationID',
                        '1'
                    ),
                    'process_put' => array(
                        'fn_exim_set_product_combination_images',
                        $this,
                        '$productID',
                        '#key',
                        '#this',
                        '1'
                    ),
                    'linked' => false,
                    'return_result' => true
                )
                
            )
        );
        $get    = isset($get) ? $get : '';
        $schema = $this->setFilter($get, $conditionArry, $schema, $params);
        return $schema;
    }
    public function getReviewSchema($params = array()) {
        extract($params);
        if (!empty($primaryID))
            $conditionArry = array(
                'productID' => $primaryID
            );
        $conditionArry = isset($conditionArry) ? $conditionArry : '';
        $schema        = array(
            'section' => 'product_reviews',
            'name' => 'product_reviews',
            'pattern_id' => 'product_reviews',
            'condition' => $conditionArry,
            'key' => array(
                'ProductReviewID'
            ),
            'references' => array(
                'products' => array(
                    'reference_fields' => array(
                        'productID' => '&productID'
                    ),
                    'join_type' => 'INNER'
                )
            ),
            'table' => 'product_reviews',
            'export_fields' => array(
                'ProductReviewID' => array(
                    'db_field' => 'ProductReviewID',
                    'alt_key' => true
                ),
                'productID' => array(
                    'db_field' => 'productID',
                    'validateIt' => array(
                        'products',
                        'productID',
                        " productStatus IN ('Active','Inactive')"
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Product is required'
                    )
                ),
                'userID' => array(
                    'db_field' => 'userID',
                    'validateIt' => array(
                        'users',
                        'userID',
                        " userStatus IN ('Active','Inactive')"
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'UserID is required'
                    )
                ),
                'languageID' => array(
                    'db_field' => 'languageID',
                    'validateIt' => array(
                        'users',
                        'userID',
                        " userStatus IN ('Active','Inactive')"
                    ),
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Language is required'
                    )
                ),
                'reviewTitle' => array(
                    'db_field' => 'reviewTitle',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Title is required'
                    )
                ),
                'reviewText' => array(
                    'db_field' => 'reviewText',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Review Content is required'
                    )
                ),
                'productRating' => array(
                    'db_field' => 'productRating',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Rating is required'
                    )
                ),
                'reviwedDate' => array(
                    'db_field' => 'reviwedDate',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Review date is required'
                    )
                ),
                'reviewStatus' => array(
                    'db_field' => 'reviewStatus',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Review Status is required'
                    )
                ),
                'updatedDate' => array(
                    'db_field' => 'updatedDate',
                    'validate' => array(
                        'required'
                    ),
                    'error' => array(
                        'Updated Date is required'
                    )
                ),
                'approvedBy' => array(
                    'db_field' => 'approvedBy'
                ),
                'reviewFollow' => array(
                    'db_field' => 'reviewFollow'
                ),
                'isCertifiedUser' => array(
                    'db_field' => 'isCertifiedUser'
                ),
                'helpfulVoteCount' => array(
                    'db_field' => 'helpfulVoteCount'
                ),
                'notHelpfulVoteCount' => array(
                    'db_field' => 'notHelpfulVoteCount'
                ),
                'userDetails' => array(
                    'db_field' => 'userDetails'
                ),
                'userIP' => array(
                    'db_field' => 'userIP'
                )
            )
        );
        $get           = isset($get) ? $get : '';
        $schema        = $this->setFilter($get, $conditionArry, $schema, $params);
        return $schema;
    }
    function setFilter($get = array(), $conditionArry, $schema, $params = array()) {
        extract($params);
        if (is_array($get)) {
            extract($get);
        }
        if (!empty($filter)) {
            foreach ($filter as $filtr) {
                if ($filtr['eq'] != '') {
                    $conditionArry[$filtr['key']]['eq'] = $filtr['eq'];
                } else if ($filtr['neq'] != '') {
                    $conditionArry[$filtr['key']]['neq'] = $filtr['neq'];
                } else if ($filtr['lt'] != '') {
                    $conditionArry[$filtr['key']]['lt'] = $filtr['lt'];
                } else if ($filtr['gt'] != '') {
                    $conditionArry[$filtr['key']]['gt'] = $filtr['gt'];
                } else if ($filtr['lteq'] != '') {
                    $conditionArry[$filtr['key']]['lteq'] = $filtr['lteq'];
                } else if ($filtr['gteq'] != '') {
                    $conditionArry[$filtr['key']]['gteq'] = $filtr['gteq'];
                } else if ($filtr['in'] != '') {
                    $conditionArry[$filtr['key']]['in'] = $filtr['in'];
                } else if ($filtr['nin'] != '') {
                    $conditionArry[$filtr['key']]['nin'] = $filtr['nin'];
                } else if ($filtr['llike'] != '') {
                    $conditionArry[$filtr['key']]['llike'] = $filtr['llike'];
                } else if ($filtr['rlike'] != '') {
                    $conditionArry[$filtr['key']]['rlike'] = $filtr['rlike'];
                } else if ($filtr['like'] != '') {
                    $conditionArry[$filtr['key']]['like'] = $filtr['like'];
                }
            }
        }
        if (isset($consumer['userType']) && $consumer['userType'] == 'merchant') {
            $userID                      = $consumer['userID'];
            $conditionArry['businessID'] = array(
                'eq' => $userID
            );
        }
        $schema['condition']        = $conditionArry;
        $schema['resultPerRequest'] = isset($resultPerRequest) ? $resultPerRequest : '';
        if (isset($page) && $page != '' && $page >= 0) {
            $schema['page'] = $page;
            $schema['from'] = $page * $resultPerRequest;
            $schema['to']   = $resultPerRequest;
        } else if (isset($from) && $from != '' && $to != '') {
            $schema['from'] = $from;
            $schema['to']   = $to;
        } else if (isset($limit) && $limit != '' && $limit >= 0) {
            $schema['limit'] = $limit;
        }
        if (isset($order) && $order != '') {
            $schema['order'] = $order;
            if ($dir != '') {
                $schema['dir'] = $dir;
            } else {
                $schema['dir'] = 'ASC';
            }
        }
        return $schema;
    }
    function fn_exim_put_product_combination($combinationID, $productOptionID, $data, $languageID = '1') {
        $combination      = implode("_", $data);
        $combination      = $productOptionID . "_" . $combination;
        $combination_hash = $this->makeHAsh($combination);
        $sql              = "
				UPDATE 
					" . DB_PREFIX . "product_combination 
				SET 
					combination='" . $combination . "',
					combinationHash ='" . $combination_hash . "'

				WHERE 
					combinationID='" . $combinationID . "'";
        $this->ObjDatabase->setQuery($sql);
    }
    function fn_exim_get_product_combination($combination, $lang_code) {
        $return                 = array();
        $ObjCustom              = new CustomOptionModel();
        $languageIDs['Current'] = $lang_code;
        $comboArray             = $ObjCustom->getCombinationVariants($languageIDs, $combination);
        return $comboArray;
    }
    function fn_exim_get_product_custom_options_variant($customOptionID, $languageID) {
        $ObjCustom              = new CustomOptionModel();
        $languageIDs['Current'] = $languageID;
        return $ObjCustom->getVariantsForOptions(array(
            $customOptionID
        ), $languageIDs);
    }
    function fn_exim_set_product_custom_options_variant($customOptionID, $data, $languageID) {
        $sql = "
			DELETE FROM 
				" . DB_PREFIX . "product_custom_option_variant
			WHERE
				customOptionID ='" . $customOptionID . "'
				";
        $this->ObjDatabase->setQuery($sql);
        $sql = "
			DELETE FROM 
				" . DB_PREFIX . "product_custom_option_variant_details
			WHERE
				customOptionVariantID NOT IN ( 
					SELECT 
						customOptionVariantID 
					FROM  
						" . DB_PREFIX . "product_custom_option_variant
					)
				";
        $this->ObjDatabase->setQuery($sql);
        foreach ($data as $options) {
            $sql = "
				INSERT INTO " . DB_PREFIX . "product_custom_option_variant
					(
					customOptionID,
					priceDiff,
					priceDiffType,
					weightDiff,
					weightDiffType
					)
				VALUES
					(
					'" . $customOptionID . "',
					'" . $options['priceDiff'] . "',
					'" . $options['priceDiffType'] . "',
					'" . $options['weightDiff'] . "',
					'" . $options['weightDiffType'] . "'
					)
			";
            $this->ObjDatabase->setQuery($sql);
            $customOptionVariantID = $this->ObjDatabase->getInsertId();
            $sql                   = "
				INSERT INTO " . DB_PREFIX . "product_custom_option_variant_details
					(
					customOptionVariantID,
					languageID,
					value
					)
				VALUES
					(
					'" . $customOptionVariantID . "',
					'" . $languageID . "',
					'" . $options['value'] . "'
					)
			";
            $this->ObjDatabase->setQuery($sql);
        }
    }
    function fn_exim_get_product_option_images_default($productID, $data, $languageID) {
        if ($data != '') {
			$upload_images_to = $this->getSettings('upload_images_to'); 
			if($upload_images_to=='filesystem'){
				$globalHttpUrl = $this->getSettings('global_http_url');
			}
			else
			{
				$globalHttpUrl = $this->getSettings('cdn_baseurl_image');
			}

            $imagePaths    = array(
                'small',
                'preview',
                'preview-main',
                'large'
            );
            foreach ($imagePaths as $path) {
                $productMedia[$path] = $globalHttpUrl . "/public/uploads/catalog/product/" . $path . "/" . $data;
            }
            return $productMedia;
        } else {
            return '';
        }
    }
    function fn_exim_set_product_option_images_default($productID, $optionID, $data, $languageID, $ImageType) {
        if ($data != '') {
            $sql          = "
					SELECT 
						productUrl
					FROM
						" . DB_PREFIX . "products
					WHERE 
						productID='" . $productID . "'
				";
            $optionImages = $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);
        }
    }
    function fn_exim_set_product_option_images($productID, $optionID, $data, $languageID) {
        foreach ($data as $images) {
            if ($images['productMedia'] != '') {
                $sql          = "
					SELECT 
						productUrl
					FROM
						" . DB_PREFIX . "products
					WHERE 
						productID='" . $productID . "'
				";
                $optionImages = $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);
                //if ($images['mediaType'] != '') {
                $thumb = '';
                if ($images['productMedia'] != '') {
                    $imagePath = $this->saveImage($productID, $images['productMedia'], $optionImages['productUrl'], '', 'option', $thumb);
                }
                $sql = "
					INSERT INTO " . DB_PREFIX . "product_media
						(
						productID,
						productObjectID,
						productObjectType,
						productMedia,
						productMediaType,
						productMediaStatus
						)
					VALUES
						(
						'" . $productID . "',
						'" . $optionID . "',
						'DO',
						'" . $imagePath . "',
						'I',
						'A'
						)
				";
                $this->ObjDatabase->setQuery($sql);
            }
        }
    }
    function fn_exim_get_product_option_images($productID, $optionID, $languageID) {
        $upload_images_to = $this->getSettings('upload_images_to'); 
		if($upload_images_to=='filesystem'){
			$globalHttpUrl = $this->getSettings('global_http_url');
		}
		else
		{
			$globalHttpUrl = $this->getSettings('cdn_baseurl_image');
		}
        $sql           = "
			SELECT 
				productObjectID,
				productObjectType,
				productMedia,
				productMediaType,
				productMediaPriority,
				productMediaStatus
			FROM 
				" . DB_PREFIX . "product_media
			WHERE
				productObjectID='" . $optionID . "'
				AND
				productObjectType='DO'
		";
        $optionImages  = $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
        $images        = array();
        foreach ($optionImages as $optionImg) {
            $imagePaths = array(
                'small',
                'preview',
                'preview-main',
                'large'
            );
            foreach ($imagePaths as $path) {
                $productMedia[$path] = $globalHttpUrl . "/public/uploads/catalog/product/" . $path . "/" . $optionImg['productMedia'];
            }
            $images[] = array(
                'productObjectID' => $optionImg['productObjectID'],
                'productObjectType' => $optionImg['productObjectType'],
                'productMedia' => $productMedia,
                'productMediaType' => $optionImg['productMediaType'],
                'productMediaPriority' => $optionImg['productMediaPriority'],
                'productMediaStatus' => $optionImg['productMediaStatus']
            );
        }
        return $images;
    }
    
    function fn_exim_set_product_combination_images($productID, $combinationID, $data, $languageID) {
        foreach ($data as $images) {
            if ($images['productMedia'] != '') {
                $sql          = "
					SELECT 
						productUrl
					FROM
						" . DB_PREFIX . "products
					WHERE 
						productID='" . $productID . "'
				";
                $optionImages = $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);
                //if ($images['mediaType'] != '') {
                $thumb = '';
                if ($images['productMedia'] != '') {
                    $imagePath = $this->saveImage($productID, $images['productMedia'], $optionImages['productUrl'], '', 'combination', $thumb);
                }
                $sql = "
					INSERT INTO " . DB_PREFIX . "product_media
						(
						productID,
						productObjectID,
						productObjectType,
						productMedia,
						productMediaType,
						productMediaStatus
						)
					VALUES
						(
						'" . $productID . "',
						'" . $combinationID . "',
						'C',
						'" . $imagePath . "',
						'I',
						'A'
						)
				";
                $this->ObjDatabase->setQuery($sql);
            }
        }
    }
    function fn_exim_get_product_combination_images($productID, $combinationID, $languageID) {
        $upload_images_to = $this->getSettings('upload_images_to'); 
		if($upload_images_to=='filesystem'){
			$globalHttpUrl = $this->getSettings('global_http_url');
		}
		else
		{
			$globalHttpUrl = $this->getSettings('cdn_baseurl_image');
		}
        $sql           = "
			SELECT 
				productObjectID,
				productObjectType,
				productMedia,
				productMediaType,
				productMediaPriority,
				productMediaStatus
			FROM 
				" . DB_PREFIX . "product_media
			WHERE
				productObjectID='" . $combinationID . "'
				AND
				productObjectType='C'
		";
        $optionImages  = $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
        $images        = array();
        foreach ($optionImages as $optionImg) {
            $imagePaths = array(
                'small',
                'preview',
                'preview-main',
                'large'
            );
            foreach ($imagePaths as $path) {
                $productMedia[$path] = $globalHttpUrl . "/public/uploads/catalog/product/" . $path . "/" . $optionImg['productMedia'];
            }
            $images[] = array(
                'productObjectID' => $optionImg['productObjectID'],
                'productObjectType' => $optionImg['productObjectType'],
                'productMedia' => $productMedia,
                'productMediaType' => $optionImg['productMediaType'],
                'productMediaPriority' => $optionImg['productMediaPriority'],
                'productMediaStatus' => $optionImg['productMediaStatus']
            );
        }
        return $images;
    }
    
    
    function fn_exim_get_image_type($imagePath, $destination) {
        $imageTypes   = array(
            "1" => IMAGETYPE_GIF,
            "2" => IMAGETYPE_JPEG,
            "3" => IMAGETYPE_PNG
        );
        $productImage = __CORE_PUBLIC_PATH . "/uploads/catalog/" . $destination . "/small/" . $imagePath;
        if (file_exists($productImage)) {
            $imageExt = exif_imagetype($productImage);
            return $imageExt = image_type_to_mime_type($imageTypes[$imageExt]);
        }
        return '';
    }
    function fn_exim_get_image_string($imagePath, $destination) {
		$upload_images_to = $this->getSettings('upload_images_to'); 
		if($upload_images_to=='filesystem'){
			$globalHttpUrl = $this->getSettings('global_http_url');
		}
		else
		{
		$globalHttpUrl = $this->getSettings('cdn_baseurl_image');
		}
        $imagePaths    = array(
            'small',
            'preview',
            'preview-main',
            'large'
        );
        foreach ($imagePaths as $path) {
            $images[$path] = $globalHttpUrl . "/public/uploads/catalog/" . $destination . "/" . $path . "/" . $imagePath;
        }
        return $images;
    }
    function fn_exim_export_oname($product_id) {
        $sql    = "
			SELECT 
				productOptDet.productOptionName 
			FROM 
					" . DB_PREFIX . "product_options productOpt 
				LEFT JOIN 
					" . DB_PREFIX . "product_option_details productOptDet 
						ON	(productOptDet.productOptionID=productOpt.productOptionID) 
			WHERE  
				productOpt.productID='" . $product_id . "' 
				AND 
				productOpt.productOptionDefault='Yes'";
        $result = $this->ObjDatabase->readValue($sql);
        return $this->fn_html_entity_decode($result['productOptionName']);
    }
    function fn_exim_get_box_size($product_id) {
        $sql             = "
			SELECT 
				packageWeight,
				packageLength,
				packageWidth,
				packageHeight 
			FROM 
				" . DB_PREFIX . "product_options 
			WHERE 
				productOptionDefault='Yes' 
				AND 
				productID ='" . $product_id . "'";
        $shipping_params = $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);
        return array(
            'length' => (empty($shipping_params['packageLength']) ? 0 : $shipping_params['packageLength']),
            'width' => (empty($shipping_params['packageWidth']) ? 0 : $shipping_params['packageWidth']),
            'height' => (empty($shipping_params['packageHeight']) ? 0 : $shipping_params['packageHeight']),
            'weight' => (empty($shipping_params['packageWeight']) ? 0 : $shipping_params['packageWeight'])
        );
    }
    function fn_exim_get_product_categories($product_id, $lang_code = '') {
        $languageIDs['Current'] = $languageIDs['Default'] = $lang_code;
        $ObjProduct             = new ProductModel();
        $resProductcategory     = $ObjProduct->listProductTocategoryDetails($languageIDs, $product_id);
        $categories             = array();
        foreach ($resProductcategory as $key => $category) {
            $categories[$key]['productCategoryID']     = $category['productCategoryID'];
            $categories[$key]['productCategoryName']   = $category['productCategoryName'];
            $categories[$key]['productCategoryParent'] = $category['productCategoryParent'];
        }
        return $categories;
    }
    function fn_timestamp_to_date($timestamp) {
        if ($timestamp == '0000-00-00')
            return '';
        else {
            $timestamp = date("d-m-Y", strtotime($timestamp));
        }
        return $timestamp;
    }
    function fn_exim_set_product_image($thumb, $product_id, $main,$url, $fileMimeType ) {
        $this->saveImage($product_id, $main, $url, $fileMimeType, 'product',  $thumb);
    }
    
//    function fn_exim_set_product_image($images_path, $thumb, $product_id, $main) {
//        $objProduct = new ProductModel();
//        $imageFlag  = 0;
//        if (!empty($product_id)) {
//            if (!empty($main)) {
//                $main                           = trim($main);
//                $dataResize['previewHeight']    = $this->getSettings('preview_height');
//                $dataResize['previewWidth']     = $this->getSettings('preview_width');
//                $dataResize['thumbHeight']      = $this->getSettings('thumb_height');
//                $dataResize['thumbWidth']       = $this->getSettings('thumb_width');
//                $dataResize['smallthumbWidth']  = $this->getSettings('small_thumb_width');
//                $dataResize['smallthumbHeight'] = $this->getSettings('small_thumb_height');
//                if (strpos($thumb, '/') !== false && strpos($main, '/') !== false)
//                    $imageFlag = 1;
//                if ($imageFlag != 1) {
//                    //thumb exist
//                    if (strpos($thumb, '/') !== false)
//                        $MediaArry['thumbImage_temp'] = '';
//                    //thumb changes
//                    elseif ($thumb != '')
//                        $MediaArry['thumbImage_temp'] = $images_path . "/" . $thumb;
//                    //thumb null
//                    else
//                        $MediaArry['thumbImage_temp'] = '';
//                    //@Main Image change sections//
//                    //main exist
//                    if (strpos($main, '/') !== false) {
//                        $Image                       = $objProduct->getImageName($main);
//                        $MediaArry['mainImage_temp'] = "";
//                    }
//                    //main changes
//                    else {
//                        $Image                       = substr_replace($main, "_" . rand(1, 1000) . '.', strrpos($main, '.'), 1);
//                        $MediaArry['mainImage_temp'] = $images_path . "/" . $main;
//                        //main changes : preview same
//                        if (strpos($thumb, '/') !== false) {
//                            $MediaArry['thumbFlag'] = 1;
//                            $MediaArry['resImage']  = $thumb;
//                        }
//                    }
//                    $MediaArry['mediaParam'] = $dataResize;
//                    $MediaArry['destFolder'] = 'product';
//                    $MediaArry['mainImage']  = $Image;
//                    $MediaArry['productID']  = $product_id;
//                    //echo $MediaArry['mainImage_temp'];
//                    //echo $MediaArry['thumbImage_temp'];
//                    $main_fullpath           = __ROOT_PATH . '/' . $MediaArry['mainImage_temp'];
//                    if (is_file($main_fullpath) && file_exists($main_fullpath)) {
//                        $upload_flag = 0;
//                        if ($MediaArry['thumbImage_temp'] != '') {
//                            $thumb_fullpath = __ROOT_PATH . '/' . $MediaArry['thumbImage_temp'];
//                            if (!(file_exists($thumb_fullpath)))
//                                $upload_flag = 1;
//                        }
//                    } else {
//                        $upload_flag = 1;
//                    }
//                    if ($upload_flag != 1) {
//                        $image = $objProduct->generateMedia($MediaArry);
//                        $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "products SET productImage='" . $image . "',productStatus='Active' WHERE productID='" . $product_id . "'");
//                    }
//                }
//                return true;
//            } else
//                return false;
//        } else
//            return false;
//    }
    function saveImage($product_id, $imageContent, $url, $fileMimeType, $imageOf = 'product', $thumb = '') {
        
        if (!empty($product_id) && ($imageContent!='')) {
            $ObjImage               = new ImageModel();
            $previewHeight          = $this->getSettings('preview_height');
            $previewWidth           = $this->getSettings('preview_width');
            $thumbHeight            = $this->getSettings('thumb_height');
            $thumbWidth             = $this->getSettings('thumb_width');
            $smallthumbWidth        = $this->getSettings('small_thumb_width');
            $smallthumbHeight       = $this->getSettings('small_thumb_height');
            $mainDir                = $url['0'];
            $subDir                 = $url['1'];
            //Product Level Directory Creation 
            if($imageOf == 'combination')
            {
                $dirLevel1              = __CORE_PUBLIC_PATH . "/uploads/catalog/product-combination/large/" . $mainDir;
                $dirLevel2              = __CORE_PUBLIC_PATH . "/uploads/catalog/product-combination/large/" . $mainDir . "/" . $subDir;
                $dirLevel2_thumb        = __CORE_PUBLIC_PATH . "/uploads/catalog/product-combination/thumb/" . $mainDir . "/" . $subDir;
                $dirLevel2_preview      = __CORE_PUBLIC_PATH . "/uploads/catalog/product-combination/preview/" . $mainDir . "/" . $subDir;
                $dirLevel2_small        = __CORE_PUBLIC_PATH . "/uploads/catalog/product-combination/small/" . $mainDir . "/" . $subDir;
                $dirLevel2_preview_main = __CORE_PUBLIC_PATH . "/uploads/catalog/product-combination/preview-main/" . $mainDir . "/" . $subDir;
            }else{
                $dirLevel1              = __CORE_PUBLIC_PATH . "/uploads/catalog/product/large/" . $mainDir;
                $dirLevel2              = __CORE_PUBLIC_PATH . "/uploads/catalog/product/large/" . $mainDir . "/" . $subDir;
                $dirLevel2_thumb        = __CORE_PUBLIC_PATH . "/uploads/catalog/product/thumb/" . $mainDir . "/" . $subDir;
                $dirLevel2_preview      = __CORE_PUBLIC_PATH . "/uploads/catalog/product/preview/" . $mainDir . "/" . $subDir;
                $dirLevel2_small        = __CORE_PUBLIC_PATH . "/uploads/catalog/product/small/" . $mainDir . "/" . $subDir;
                $dirLevel2_preview_main = __CORE_PUBLIC_PATH . "/uploads/catalog/product/preview-main/" . $mainDir . "/" . $subDir;
            }
            
            if (file_exists($dirLevel2) && is_dir($dirLevel2)) {
            } elseif (file_exists($dirLevel1) && is_dir($dirLevel1)) {
                mkdir($dirLevel2, 0777);
                mkdir($dirLevel2_thumb, 0777);
                mkdir($dirLevel2_preview, 0777);
                mkdir($dirLevel2_small, 0777);
                mkdir($dirLevel2_preview_main, 0777);
            } else {
                mkdir($dirLevel2, 0777, TRUE);
                mkdir($dirLevel2_thumb, 0777, TRUE);
                mkdir($dirLevel2_preview, 0777, TRUE);
                mkdir($dirLevel2_small, 0777, TRUE);
                mkdir($dirLevel2_preview_main, 0777, TRUE);
            }
            
            
            //echo $imageContent;exit;
            $ext = pathinfo($imageContent, PATHINFO_EXTENSION);
            //echo $ext; exit;
            $ImageName = $url . "_" . rand(1, 1000).".".$ext;
            
//            switch ($fileMimeType) {
//                case 'image/jpeg':
//                    $Image .= '.jpeg';
//                    break;
//                case 'image/gif':
//                    $Image .= '.gif';
//                    break;
//                case 'image/png':
//                    $Image .= '.png';
//                    break;
//                default:
//                    $Image .= '.jpeg';
//            }
            //$imageContent = base64_decode($imageContent);
            $Image = file_get_contents($imageContent, true); 
            $result = file_put_contents($dirLevel2_thumb . "/" . $ImageName, $Image);
            $result = file_put_contents($dirLevel2 . "/" . $ImageName, $Image);
            //echo $dirLevel2_thumb . "/" . $ImageName; exit;
            $objProduct = new ProductModel();
        $imageFlag  = 0;
        if (!empty($product_id)) {
            if (!empty($Image)) {
                $main                           = trim($Image);
                $dataResize['previewHeight']    = $this->getSettings('preview_height');
                $dataResize['previewWidth']     = $this->getSettings('preview_width');
                $dataResize['thumbHeight']      = $this->getSettings('thumb_height');
                $dataResize['thumbWidth']       = $this->getSettings('thumb_width');
                $dataResize['smallthumbWidth']  = $this->getSettings('small_thumb_width');
                $dataResize['smallthumbHeight'] = $this->getSettings('small_thumb_height');
                
                
                $MediaArry['thumbFlag'] = 1;
                 
                $MediaArry['mediaParam'] = $dataResize;
                if($imageOf == 'combination'){
                $MediaArry['destFolder'] = 'product-combination';
                 $MediaArry['mainImage_temp'] = "public/uploads/catalog/product-combination/large/" . $mainDir . "/" . $subDir. "/" .$ImageName; 
                 $MediaArry['thumbImage_temp'] = "public/uploads/catalog/product-combination/thumb/" . $mainDir . "/" . $subDir. "/" .$ImageName; 
                }
                
                else{
                $MediaArry['destFolder'] = 'product';
                $MediaArry['mainImage_temp'] = "public/uploads/catalog/product/large/" . $mainDir . "/" . $subDir. "/" .$ImageName; 
                 $MediaArry['thumbImage_temp'] = "public/uploads/catalog/product/thumb/" . $mainDir . "/" . $subDir. "/" .$ImageName; 
                }
                $MediaArry['mainImage']  = $ImageName;
                $MediaArry['productID']  = $product_id;
               }}
            $image = $objProduct->generateMedia($MediaArry); //exit; 
//            file_put_contents($dirLevel2_thumb . "/" . $Image, $imageContent);
//            echo $dirLevel2_thumb . "/" . $Image."<br>"; 
//            chmod($dirLevel2_thumb . "/" . $Image, 0777);
//            file_put_contents($dirLevel2_small . "/" . $Image, $imageContent);
//            chmod($dirLevel2_small . "/" . $Image, 0777);
//            file_put_contents($dirLevel2_preview . "/" . $Image, $imageContent);
//            chmod($dirLevel2_preview . "/" . $Image, 0777);
//            file_put_contents($dirLevel2_preview_main . "/" . $Image, $imageContent);
//            chmod($dirLevel2_preview_main . "/" . $Image, 0777);
//            file_put_contents($dirLevel2 . "/" . $Image, $imageContent);
//            chmod($dirLevel2_preview_main . "/" . $Image, 0777);
//            echo "smSize".$dirLevel2_small . "/" . $Image;
//            $ObjImage->resizeImage($dirLevel2_small . "/" . $Image, $smallthumbWidth, $smallthumbHeight);
//            $ObjImage->resizeImage($dirLevel2_thumb . "/" . $Image, $thumbWidth, $thumbHeight);
//            $ObjImage->resizeImage($dirLevel2_preview . "/" . $Image, $previewWidth, $previewHeight);
//            $image = $mainDir . "/" . $subDir . "/" . $Image;
            if ($imageOf == 'product') {
                $sql = "
					UPDATE 
						" . DB_PREFIX . "products 
					SET 
						productImage='" . $image . "' 
					WHERE 
						productID='" . $product_id . "'";
                $this->ObjDatabase->setQuery($sql);
            }
            return $image;
        } else
            return false;
    }
    function fn_get_product_options($product_id, $lang_code) {
        $ObjCustom                         = new CustomOptionModel();
        $condition                         = $_status = $join = '';
        $extra_variant_fields              = '';
        $option_ids                        = $variants_ids = $options = array();
        $selectable_option_types           = array(
            'S',
            'R',
            'C'
        );
        $inputKeys                         = $ObjCustom->getInputShortKeys();
        $customAttributeArray['productID'] = $product_id;
        $languageIDs['Current']            = $lang_code;
        $resoptions                        = $ObjCustom->listCustomProductOption($languageIDs, $customAttributeArray);
        foreach ($resoptions as $key => $_options) {
            $options[$_options['customOptionID']]['option_name'] = $this->fn_html_entity_decode($_options['customOptionName']);
            $options[$_options['customOptionID']]['option_type'] = $inputKeys[$_options['inputType']];
            $options[$_options['customOptionID']]['isGlobal']    = $_options['isGlobal'];
            if ($_options['inputType'] == 'multiselect' || $_options['inputType'] == 'select')
                $option_ids[] = $_options['customOptionID'];
        }
        if (!empty($option_ids)) {
            $resVariants = $ObjCustom->getVariantsForOptions($option_ids, $languageIDs);
            if (count($resVariants) > 0) {
                foreach ($resVariants as $key => $_variants) {
                    $variants[$_variants['customOptionID']][$_variants['customOptionVariantID']]['variant_name'] = $this->fn_html_entity_decode($_variants['value']);
                }
            }
            foreach ($options as $key => $dataoptions) {
                $options[$key]['variants'] = !empty($variants[$key]) ? $variants[$key] : array();
            }
        }
        return $options;
    }
    function fn_exim_get_product_options($product_id, $lang_code = '') {
        $sql = "
			SELECT 
				productOpt.productOptionID,
				optionSKU,
				productOptionName,
				optionBarCode,
				productOptionRegularPrice,
				productOptionProductPrice,
				productOptionShowVideo,
				productPrepayAmount,
				productOptionQuantity,
				productQuantityNotifyAt,
				packageWeight,
				packageLength,
				packageWidth,
				packageHeight,
				productQuantityUnlimited,
				soldQuantity,
				productOptionStatus,
				productOptionDefault
			FROM 
					" . DB_PREFIX . "product_options AS productOpt
				INNER JOIN
					" . DB_PREFIX . "product_option_details AS productOptDet
						ON	(
							productOpt.productOptionID=productOptDet.productOptionID
						)
			WHERE 
				productID='" . $product_id . "' 
				AND
				languageID='" . $lang_code . "'
		";
        return $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
    }
    function fn_exim_get_product_custom_options($product_id, $lang_code = '') {
        $ObjCustom                         = new CustomOptionModel();
        $customAttributeArray['productID'] = $product_id;
        $languageIDs['Current']            = $lang_code;
        $resoptions                        = $ObjCustom->listCustomProductOption($languageIDs, $customAttributeArray);
		$customOptions[] = array();
	   foreach ($resoptions as $options) {
            $resVariants     = $ObjCustom->getVariantsForOptions(array(
                $options['customOptionID']
            ), $languageIDs);
            $customOptions[] = array(
                "customOptionID" => $options['customOptionID'],
                "customOptionName" => $options['customOptionName'],
                "isGlobal" => $options['isGlobal'],
                "priceDiff" => $options['priceDiff'],
                "priceDiffType" => $options['priceDiffType'],
                "validationMessage" => $options['validationMessage'],
                "helpText" => $options['helpText'],
                "validateRule" => $options['validateRule'],
                "inputType" => $options['inputType'],
                "status" => $options['status'],
                "customOptionLinkID" => $options['customOptionLinkID'],
                "variants" => $resVariants
            );
        }
        return $customOptions;
    }
    function fn_exim_get_product_attributes($product_id, $lang_code = '') {
        $ObjAttribute           = new AttributeModel();
        $ObjProduct             = new ProductModel();
        $attrParamArray         = array(
            'attributeSetID' => $ObjProduct->getAttrSetID($product_id),
            'productID' => $product_id,
            'attrStatus' => 'A',
            'mode' => 'attributeDetails'
        );
        $languageIDs['Current'] = $lang_code;
        $attributesGroupWise    = $ObjAttribute->listAttributesGroupWise($languageIDs, $attrParamArray);
        $attributeArray         = array();
        if (isset($attributesGroupWise)) {
            foreach ($attributesGroupWise as $key => $attributes) {
                $attributeArray[] = array(
                    'attributeID' => $attributes['attributeID'],
                    'attrName' => $attributes['attrName'],
                    'attributeValue' => $attributes['attributeValue']
                );
            }
        }
        return $attributeArray;
    }
    function fn_exim_export_setname($setID) {
        $ObjAttr = new AttributeModel();
        $set     = $ObjAttr->getAttributeSetDetails($setID);
        return $this->fn_html_entity_decode($set['attributeSetName']);
    }
    function fn_html_entity_decode($data) {
        return html_entity_decode($data);
    }
    function fn_exim_post_item_id($item_id) {
        return '{' . $item_id . '}';
    }
    function fn_exim_put_box_size($product_id, $data) {
        if (empty($data)) {
            return false;
        }
        $length = $width = $height = 0;
        $params = explode(';', $data);
        foreach ($params as $param) {
            $elm = explode(':', $param);
            if ($elm[0] == 'length') {
                $length = floatval($elm[1]);
            } elseif ($elm[0] == 'width') {
                $width = floatval($elm[1]);
            } elseif ($elm[0] == 'height') {
                $height = floatval($elm[1]);
            } elseif ($elm[0] == 'weight') {
                $weight = floatval($elm[1]);
            }
        }
        $shipping_params['packageLength'] = $length;
        $shipping_params['packageWidth']  = $width;
        $shipping_params['packageHeight'] = $height;
        $shipping_params['packageWeight'] = $weight;
        $where['productID']               = $product_id;
        $where['productOptionDefault']    = 'Yes';
        /* $queryUpdate=$this->update($shipping_params,$where);
        $this->ObjDatabase->setQuery("UPDATE ".DB_PREFIX."product_options SET ".$queryUpdate['cond']." WHERE ".$queryUpdate['where']); */
        return true;
    }
//    function fn_exim_set_product_categories($product_id, $categories_data, $lang_code = 1, $productUrl = '', $productName = '') {
//        $category_delimiter = '///';
//        $productToCategory = array();
//        
//        //URL Rewrite
//        if (empty($productUrl) || $productUrl == '') {
//            $productUrl = $this->ObjDatabase->getField("SELECT productUrl FROM " . DB_PREFIX . "products WHERE productID='" . $product_id . "'");
//            if (empty($productUrl) || $productUrl == '') {
//                $productUrl = $this->fn_generate_productUrl($productName);
//                $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "products SET productUrl='" . $productUrl . "' WHERE productID ='" . $product_id . "'");
//            }
//        }
//        $productUrl = strtolower($productUrl);
//        $this->fn_insert_basic_rewrite_details($product_id, $productUrl, '');
//        
//        
//        /*foreach ($categories_data as $category) {
//            $productToCategory[] = "('" . $product_id . "','" . $category['productCategoryID'] . "')";
//        }*/
//        $arrayCatID = explode(';',$categories_data);
//        for($i=0;$i<count($arrayCatID);$i++){
//            $productToCategory[] = "('" . $product_id . "','" . $arrayCatID[$i] . "')";
//        }
//        $sql = "
//			DELETE FROM 
//				" . DB_PREFIX . "product_to_category 
//			WHERE 
//				productID='" . $product_id . "'";
//        $this->ObjDatabase->setQuery($sql);
//        $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "url_rewrite WHERE objectID = " . $product_id . " AND type='product' AND parentID <> 0 ");
//        /*$sql = "
//			INSERT INTO " . DB_PREFIX . "product_to_category
//				(
//				productID,
//				productCategoryID
//				)
//			VALUES 
//				" . implode(",", $productToCategory) . "
//				";
//        $this->ObjDatabase->setQuery($sql);*/
//        
//        if (empty($categories_data)) {
//            return false;
//        }
//        $set_delimiter      = ';';
//        $paths              = array();
//        $updated_categories = array();
//        // Check if array is provided
//        if (strpos($categories_data, $set_delimiter) !== false) {
//            $paths = explode($set_delimiter, $categories_data);
//            array_walk($paths, array(
//                $this,
//                'fn_trim_helper'
//            ));
//        } else {
//            $paths[] = $categories_data;
//        }
//        if (!$this->fn_is_empty($paths)) {
//            $old_data = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_to_category WHERE productID='" . $product_id . "'");
//            foreach ($old_data as $k => $v) {
//                $updated_categories[] = $k;
//            }
//            //$this->ObjDatabase->setQuery("DELETE FROM ".DB_PREFIX."product_to_category WHERE productID ='".$product_id."'");
//        }
//        foreach ($paths as $category) {
//            $categories = (strpos($category, $category_delimiter) !== false) ? explode($category_delimiter, $category) : array(
//                $category
//            );
//            if (!empty($categories)) {
//                $parent_id = '0';
//                foreach ($categories as $cat) {
//                    $category_condition = '';
//                    $category_ids       = $this->ObjDatabase->readValue("SELECT " . DB_PREFIX . "product_category_details.productCategoryID FROM " . DB_PREFIX . "product_category_details INNER JOIN " . DB_PREFIX . "product_categories ON
//										     " . DB_PREFIX . "product_categories.productCategoryID = " . DB_PREFIX . "product_category_details.productCategoryID $category_condition
//								    WHERE " . DB_PREFIX . "product_categories.productCategoryStatus!='Delete' AND " . DB_PREFIX . "product_category_details.productCategoryName ='" . $this->fn_html_entity_encode($cat) . "' AND languageID = '" . $lang_code . "' AND productCategoryParent='" . $parent_id . "'");
//                    $category_id        = $category_ids['productCategoryID'];
//                    if (!empty($category_id)) {
//                        $parent_id = $category_id;
//                    }
//                }
//                $data = array(
//                    'productID' => $product_id,
//                    'productCategoryID' => $category_id
//                );
//                if (!empty($old_data) && !empty($old_data[$category_id])) {
//                    $data = array_merge($old_data[$category_id], $data);
//                }
//                $this->ObjDatabase->setQuery("REPLACE INTO " . DB_PREFIX . "product_to_category(`productID`,`productCategoryID`) VALUES('" . $product_id . "', '" . $category_id . "')");
//                $updated_categories[] = $category_id;
//                //URL REWRITE
//                $this->fn_insert_basic_rewrite_details($product_id, $productUrl, $category_id);
//            }
//        }
//        
////        $sql = "
////			INSERT INTO " . DB_PREFIX . "product_to_category
////				(
////				productID,
////				productCategoryID
////				)
////			VALUES 
////				" . implode(",", $productToCategory) . "
////				";
////        $this->ObjDatabase->setQuery($sql);
//        //exit;
//        if (!empty($updated_categories)) {
//            return true;
//        }
//        
//    }
    
    function fn_exim_set_product_categories($product_id, $categories_data, $lang_code = 1, $productUrl = '', $productName = '') {
        $category_delimiter = '///';
        //URL Rewrite
        if (empty($productUrl) || $productUrl == '') {
            $productUrl = $this->ObjDatabase->getField("SELECT productUrl FROM " . DB_PREFIX . "products WHERE productID='" . $product_id . "'");
            if (empty($productUrl) || $productUrl == '') {
                $productUrl = $this->fn_generate_productUrl($productName);
                $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "products SET productUrl='" . $productUrl . "' WHERE productID ='" . $product_id . "'");
            }
        }
        $productUrl = strtolower($productUrl);
        $this->fn_insert_basic_rewrite_details($product_id, $productUrl, '');
        $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "product_to_category WHERE productID ='" . $product_id . "'");
        $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "url_rewrite WHERE objectID = " . $product_id . " AND type='product' AND parentID <> 0 ");
        if (empty($categories_data)) {
            return false;
        }
        $set_delimiter      = ';';
        $paths              = array();
        $updated_categories = array();
        // Check if array is provided
        if (strpos($categories_data, $set_delimiter) !== false) {
            $paths = explode($set_delimiter, $categories_data);
            array_walk($paths, array(
                $this,
                'fn_trim_helper'
            ));
        } else {
            $paths[] = $categories_data;
        }
        if (!$this->fn_is_empty($paths)) {
            $old_data = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_to_category WHERE productID='" . $product_id . "'");
            foreach ($old_data as $k => $v) {
                $updated_categories[] = $k;
            }
            //$this->ObjDatabase->setQuery("DELETE FROM ".DB_PREFIX."product_to_category WHERE productID ='".$product_id."'");
        }
        foreach ($paths as $category) {
            $categories = (strpos($category, $category_delimiter) !== false) ? explode($category_delimiter, $category) : array(
                $category
            );
            if (!empty($categories)) {
                $parent_id = '0';
                foreach ($categories as $cat) {
                    $category_condition = '';
                    $category_ids       = $this->ObjDatabase->readValue("SELECT " . DB_PREFIX . "product_category_details.productCategoryID FROM " . DB_PREFIX . "product_category_details INNER JOIN " . DB_PREFIX . "product_categories ON
										     " . DB_PREFIX . "product_categories.productCategoryID = " . DB_PREFIX . "product_category_details.productCategoryID $category_condition
								    WHERE " . DB_PREFIX . "product_categories.productCategoryStatus!='Delete' AND " . DB_PREFIX . "product_category_details.productCategoryName ='" . $this->fn_html_entity_encode($cat) . "' AND languageID = '" . $lang_code . "' AND productCategoryParent='" . $parent_id . "'");
                    $category_id        = $category_ids['productCategoryID'];
                    if (!empty($category_id)) {
                        $parent_id = $category_id;
                    }
                }
                $data = array(
                    'productID' => $product_id,
                    'productCategoryID' => $category_id
                );
                if (!empty($old_data) && !empty($old_data[$category_id])) {
                    $data = array_merge($old_data[$category_id], $data);
                }
                $this->ObjDatabase->setQuery("REPLACE INTO " . DB_PREFIX . "product_to_category(`productID`,`productCategoryID`) VALUES('" . $product_id . "', '" . $category_id . "')");
                $updated_categories[] = $category_id;
                //URL REWRITE
                $this->fn_insert_basic_rewrite_details($product_id, $productUrl, $category_id);
            }
        }
        //exit;
        if (!empty($updated_categories)) {
            return true;
        }
        return false;
    }
    function fn_trim_helper(&$value) {
        $value = is_string($value) ? trim($value) : $value;
    }
    /* function to insert or update product and store details to rewrite table */
    function fn_insert_basic_rewrite_details($productID, $productUrl, $category = 0) {
        //URL Rewrite 							
        $ObjLanguage = new LanguageModel();
        $langsList   = $ObjLanguage->listLanguages();
        foreach ($langsList as $lang) {
            $languageIDs[] = $lang['languageID'];
        }
        $args      = array(
            'productUrl' => $productUrl
        );
        $urlSuffix = $this->getSettings('product_url_suffix');
        $product_sef_format = $this->getSettings('product_sef_format');
        $SefModel  = new SefModel();
        if ($category && $product_sef_format)
            $args['category'] = $category;
        $SefModel->_refreshProductRewrites($languageIDs, $productID, $urlSuffix, $args, '',$product_sef_format);
    }
    
    function fn_exim_set_product_options($product_id, $data, $lang_code = '', $url) {
        foreach ($data as $option) {
            if (isset($option['productOptionID']) && $option['productOptionID'] > 0) {
                $sql = "
					UPDATE 
						" . DB_PREFIX . "product_options
					SET
						optionSKU='" . $option['optionSKU'] . "',
						optionBarCode='" . $option['optionBarCode'] . "',
						productOptionRegularPrice='" . $option['productOptionRegularPrice'] . "',
						productOptionProductPrice='" . $option['productOptionProductPrice'] . "',
						productOptionShowVideo='" . $option['productOptionShowVideo'] . "',
						productPrepayAmount='" . $option['productPrepayAmount'] . "',
						productOptionQuantity='" . $option['productOptionQuantity'] . "',
						productQuantityNotifyAt='" . $option['productQuantityNotifyAt'] . "',
						packageWeight='" . $option['packageWeight'] . "',
						packageLength='" . $option['packageLength'] . "',
						packageWidth='" . $option['packageWidth'] . "',
						packageHeight='" . $option['packageHeight'] . "',
						productQuantityUnlimited='" . $option['productQuantityUnlimited'] . "',
						soldQuantity='" . $option['soldQuantity'] . "',
						productOptionStatus='" . $option['productOptionStatus'] . "',
						productOptionDefault='" . $option['productOptionDefault'] . "'
					WHERE
						productOptionID='" . $option['productOptionID'] . "'
				";
                $this->ObjDatabase->setQuery($sql);
                $sql = "
					UPDATE 
						" . DB_PREFIX . "product_option_details
					SET					
						languageID='" . $lang_code . "',
						productOptionName='" . $option['productOptionName'] . "'
					WHERE
						productOptionID='" . $option['productOptionID'] . "'
				";
                $this->ObjDatabase->setQuery($sql);
            } else {
                $sql = "
					INSERT INTO " . DB_PREFIX . "product_options
						(
						productID,
						optionSKU,
						optionBarCode,
						productOptionRegularPrice,
						productOptionProductPrice,
						productOptionShowVideo,
						productPrepayAmount,
						productOptionQuantity,
						productQuantityNotifyAt,
						packageWeight,
						packageLength,
						packageWidth,
						packageHeight,
						productQuantityUnlimited,
						soldQuantity,
						productOptionStatus,
						productOptionDefault
						)
					VALUES 
						(
						'" . $product_id . "',
						'" . $option['optionSKU'] . "',
						'" . $option['optionBarCode'] . "',
						'" . $option['productOptionRegularPrice'] . "',
						'" . $option['productOptionProductPrice'] . "',
						'" . $option['productOptionShowVideo'] . "',
						'" . $option['productPrepayAmount'] . "',
						'" . $option['productOptionQuantity'] . "',
						'" . $option['productQuantityNotifyAt'] . "',
						'" . $option['packageWeight'] . "',
						'" . $option['packageLength'] . "',
						'" . $option['packageWidth'] . "',
						'" . $option['packageHeight'] . "',
						'" . $option['productQuantityUnlimited'] . "',
						'" . $option['soldQuantity'] . "',
						'" . $option['productOptionStatus'] . "',
						'" . $option['productOptionDefault'] . "'
						)
				";
                $this->ObjDatabase->setQuery($sql);
                $productOptionID = $this->ObjDatabase->getInsertId();
                $sql             = "
					INSERT INTO " . DB_PREFIX . "product_option_details
						(
						productOptionID,
						languageID,
						productOptionName
						)
					VALUES
						(
						'" . $productOptionID . "',
						'" . $lang_code . "',
						'" . $option['productOptionName'] . "'
						)
				";
                $this->ObjDatabase->setQuery($sql);
            }
        }
    }
    function fn_exim_set_product_custom_options($product_id, $data, $lang_code = '') {
        $sql = "
			DELETE FROM 
				" . DB_PREFIX . "product_custom_option_link
			WHERE
				productID='" . $product_id . "'
			";
        $this->ObjDatabase->setQuery($sql);
        $sql = "
			DELETE FROM 
				" . DB_PREFIX . "product_custom_option
			WHERE
				customOptionID NOT IN ( 
					SELECT 
						customOptionID 
					FROM  
						" . DB_PREFIX . "product_custom_option_link
					)
				AND
				isGlobal='0'";
        $this->ObjDatabase->setQuery($sql);
        $sql = "
			DELETE FROM 
				" . DB_PREFIX . "product_custom_option_details
			WHERE
				customOptionID NOT IN ( 
					SELECT 
						customOptionID 
					FROM  
						" . DB_PREFIX . "product_custom_option
					)";
        $this->ObjDatabase->setQuery($sql);
        $sql = "
			DELETE FROM 
				" . DB_PREFIX . "product_custom_option_variant
			WHERE
				customOptionID NOT IN ( 
					SELECT 
						customOptionID 
					FROM  
						" . DB_PREFIX . "product_custom_option
					)
				";
        $this->ObjDatabase->setQuery($sql);
        $sql = "
			DELETE FROM 
				" . DB_PREFIX . "product_custom_option_variant_details
			WHERE
				customOptionVariantID NOT IN ( 
					SELECT 
						customOptionVariantID 
					FROM  
						" . DB_PREFIX . "product_custom_option_variant
					)
				";
        $this->ObjDatabase->setQuery($sql);
        foreach ($data as $option) {
            $sql = "
				INSERT INTO " . DB_PREFIX . "product_custom_option 
					(
					isGlobal,
					inputType,
					validateRule,
					priceDiff,
					priceDiffType,
					status
					)
				VALUES
					(
					'" . $option['isGlobal'] . "',
					'" . $option['inputType'] . "',
					'" . $option['validateRule'] . "',
					'" . $option['priceDiff'] . "',
					'" . $option['priceDiffType'] . "',
					'A'
					)
				";
            $this->ObjDatabase->setQuery($sql);
            $customOptionID = $this->ObjDatabase->getInsertId();
            if (is_array($option['variants']) && !empty($option['variants'])) {
                foreach ($option['variants'] as $variants) {
                    $variantThumbImage = '';
                    $sql               = "
						INSERT INTO " . DB_PREFIX . "product_custom_option_variant
							(
							customOptionID,
							variantThumbImage,
							priceDiff,
							priceDiffType,
							weightDiff,
							weightDiffType
							)
						VALUES
							(
							'" . $customOptionID . "',
							'" . $variantThumbImage . "',
							'" . $variants['priceDiff'] . "',
							'" . $variants['priceDiffType'] . "',
							'" . $variants['weightDiff'] . "',
							'" . $variants['weightDiffType'] . "'
							)
					";
                    $this->ObjDatabase->setQuery($sql);
                    $customOptionVariantID = $this->ObjDatabase->getInsertId();
                    $sql                   = "
						INSERT INTO " . DB_PREFIX . "product_custom_option_variant_details
							(
							customOptionVariantID,
							languageID,
							value
							)
						VALUES
							(
							'" . $customOptionVariantID . "',
							'" . $lang_code . "',
							'" . $variants['value'] . "'
							)
					";
                    $this->ObjDatabase->setQuery($sql);
                }
            }
            $sql = "
				INSERT INTO " . DB_PREFIX . "product_custom_option_details 
					(
					customOptionID,
					languageID,
					customOptionName,
					validationMessage,
					helpText
					)
				VALUES
					(
					'" . $customOptionID . "',
					'" . $lang_code . "',
					'" . $option['customOptionName'] . "',
					'" . $option['validationMessage'] . "',
					'" . $option['helpText'] . "'
					)
				";
            $this->ObjDatabase->setQuery($sql);
            $sql = "
				INSERT INTO " . DB_PREFIX . "product_custom_option_link 
					(
					customOptionID,
					productID
					)
				VALUES
					(
					'" . $customOptionID . "',
					'" . $product_id . "'
					)
				";
            $this->ObjDatabase->setQuery($sql);
        }
    }
    function fn_html_entity_encode($data) {
        $data = htmlspecialchars($data, ENT_NOQUOTES, 'UTF-8');
        return $this->escape($data);
    }
    function fn_exim_set_product_attributes($product_id, $setID, $data, $lang_code = '') {
        $sql = "
			DELETE FROM 
				" . DB_PREFIX . "product_attribute_values 
			WHERE 
				productID='" . $product_id . "'";
        $this->ObjDatabase->setQuery($sql);
        $sql = "
			DELETE FROM 
				" . DB_PREFIX . "product_attribute_value_details 
			WHERE 
				attrValueID NOT IN (
					SELECT 
						attrValueID 
					FROM 
						" . DB_PREFIX . "product_attribute_values
				)";
        $this->ObjDatabase->setQuery($sql);
        foreach ($data as $attribute) {
            $sql    = "SELECT
								attrInputType
							FROM
								" . DB_PREFIX . "attributes
							WHERE
								attributeID='" . $attribute['attributeID'] . "'";
            $result = $this->ObjDatabase->readValue($sql);
            
            if(empty($attribute['attributeValue']))
                $attribute['attributeValue'] = '';
            if ($result['attrInputType'] == 'select' || $result['attrInputType'] == 'multiselect') {
                if (is_array($attribute['attributeValue'])) {
                    $attributeOptions[] = "('" . $product_id . "','" . $attribute['attributeID'] . "'," . implode("),('" . $product_id . "','" . $attribute['attributeID'] . "',", $attribute['attributeValue']) . ")";
                } else {
                    $attributeOptions[] = "('" . $product_id . "','" . $attribute['attributeID'] . "','" . $attribute['attributeValue'] . "')";
                }
            } else {
                $sql = "
					INSERT INTO " . DB_PREFIX . "product_attribute_values
						(
						productID,
						attributeID,
						attrOptionID
						)
					VALUES
						(
						'" . $product_id . "',
						'" . $attribute['attributeID'] . "',
						'0'
						)";
                $this->ObjDatabase->setQuery($sql);
                $attributeValues[] = "('" . $this->ObjDatabase->getInsertId() . "','" . $lang_code . "','" . $attribute['attributeValue'] . "')";
            }
        }
        if (!empty($attributeOptions)) {
            $sql = "
				INSERT INTO " . DB_PREFIX . "product_attribute_values
					(
					productID,
					attributeID,
					attrOptionID
					)
				VALUES
					" . implode(",", $attributeOptions);
            $this->ObjDatabase->setQuery($sql);
        }
        if (!empty($attributeValues)) {
            $sql = "
				INSERT INTO " . DB_PREFIX . "product_attribute_value_details
					(
					attrValueID,
					languageID,
					attrDetValue
					)
				VALUES
					" . implode(",", $attributeValues);
            $this->ObjDatabase->setQuery($sql);
        }
    }
    function fn_is_empty($var) {
        if (!is_array($var)) {
            return (empty($var));
        } else {
            foreach ($var as $k => $v) {
                if (empty($v)) {
                    unset($var[$k]);
                    continue;
                }
                if (is_array($v) && $this->fn_is_empty($v)) {
                    unset($var[$k]);
                }
            }
            return (empty($var)) ? true : false;
        }
    }
    public function getSettings($settingsKey) {
        $sql    = "SELECT
								settingsValue
							FROM
								" . DB_PREFIX . "settings
							WHERE
								settingsKey='" . $settingsKey . "'";
        $result = $this->ObjDatabase->readValue($sql);
        return $result['settingsValue'];
    }
    
//    public function fn_put_checkExists($data, $table, $field, $query, $pkField = '', $pkValue = '') {
//        echo "<br>==========data=============<br>";
//        print_r($data);
//        echo "<br>==========table=============<br>";
//        print_r($table);
//        echo "<br>==========field=============<br>";
//        print_r($field);
//        echo "<br>==========query=============<br>";
//        print_r($query);
//        echo "<br>==========pkField=============<br>";
//        print_r($pkField);
//        echo "<br>==========pkValue=============<br>";
//        print_r($pkValue);
//        exit;
//        
//        
//        if ($pkField != '') {
//            $query .= " AND " . $pkField . " !='" . $pkValue . "'";
//        }
//        if ($this->ObjDatabase->checkExist($table, $field, $data, $query) == 'YES') {
//            $errorArray = array(
//                'error' => $field,
//                'errType' => 'record_exists',
//                'errorMessage' => "Data Already exists(" . $field . ":" . $data . ")"
//            );
//            $this->reportError($errorArray);
//        } else {
//            return $data;
//        }
//    }
}