<?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 W
 ITH THIS DISTRIBUTION PACKAGE.			*
 ****************************************************************************/ //
//$Id: CloneModel.php, v 1.0 2013/09/20 20:52:11
//Sreeja Venugopal
//
class CloneModel extends Model {
    function fn_clone_product($languageIDs, $product_id, $productExistID = 0,$baseproduct='No',$productReq='') {
        /**
         * Adds additional actions before product cloning
         *
         * @param int $product_id Original product identifier
         */
        //fn_set_hook('clone_product_pre', $product_id);
        // Clone main data
        //print_r($_POST);exit;
        $ObjProduct = new ProductModel();
        $pid  = '';
        $data = $this->ObjDatabase->readValue("SELECT * FROM `" . DB_PREFIX . "products` WHERE productID =" . $product_id, MYSQLI_ASSOC);
        unset($data['productID']);
        $data['productStatus']      = ($productReq=='')?'Inactive':'Pending';
        $data['productCreatedDate'] = date("Y-m-d H:i:s");
        $data['productImage']       = $this->fn_clone_image_pairs($pid, $product_id, 'product', '', $data['productImage']);
        $urlSuffix                  = $this->getSettingsValue('product_url_suffix');
        if ($productExistID > 0) {
            $whereproducts['productID'] = $productExistID;
            $data['buyboxStatus'] = 'Yes';            
            $this->update($data, 'products', $whereproducts);
            $pid = $productExistID;
        } else {
            $pid = $this->insert($data, 'products');
            $this->update(array('productUrl'=>$data['productUrl']."-".$pid), 'products', array('productID'=>$pid));
        }       
        $rewriteProduct             = $data;
        // Clone descriptions
        $data                       = $this->ObjDatabase->readValues("SELECT * FROM `" . DB_PREFIX . "product_details` WHERE productID =" . $product_id, MYSQLI_ASSOC);
        foreach ($data as $v) {
            $v['productID'] = $pid;
            if ($v['languageID'] == 'CART_LANGUAGE') {
                $orig_name = $v['productTitle'];
                $new_name  = $v['productTitle'] . ' [CLONE]';
            }
            unset($v['productDetailsID']);            
            $v['productTitle'] .= ' [CLONE]';
            if ($productExistID > 0) {
                $whereproductDet['productID'] = $productExistID;
                $whereproductDet['languageID'] = $v['languageID'];
                $v['productID'] = $productExistID;
                $this->update($v, 'product_details', $whereproductDet);
            } else {
                $this->insert($v, 'product_details');
            }
            
        }
        if($baseproduct=='Yes'){
            $ObjProduct->insertBuyBox($pid);
        }
        // Clone options
        if ($productExistID > 0) {
            $ObjProduct->destroyOptionValues($productExistID);
        }
        $changed_pdt_option = $this->fn_clone_product_variants($product_id, $pid);
        $this->fn_clone_image_pairs($pid, $product_id, 'option_image', $changed_pdt_option);
        // Clone prices
        /*$data = $this->ObjDatabase->readValues("SELECT * FROM `".DB_PREFIX."product_options WHERE product_id = ?i", $product_id);
        foreach ($data as $v) {
        $v['product_id'] = $pid;
        unset($v['price_id']);
        db_query("INSERT INTO ?:product_prices ?e", $v);
        }*/
        // Clone categories links
        $data  = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_to_category WHERE productID =" . $product_id, MYSQLI_ASSOC);
        $_cids = array();
        if ($productExistID > 0) {
            $ObjProduct->destroyTablesWithProductID($productExistID, 'product_to_category');            
        }
        foreach ($data as $v) {
            $v['productID'] = $pid;
            unset($v['productToCategoryID']);
            $this->insert($v, 'product_to_category');
            $_cids[] = $v['productCategoryID'];
        }
        $rewriteCat = $data;
        // Clone global linked options
        $gl_options = $this->ObjDatabase->readValues("SELECT pcl.customOptionID,pcl.productID,pcl.sortOrder FROM " . DB_PREFIX . "product_custom_option_link pcl LEFT JOIN " . DB_PREFIX . "product_custom_option pco ON(pcl.customOptionID=pco.customOptionID) WHERE pco.isGlobal='1'
							     AND productID =" . $product_id, MYSQLI_ASSOC);
        if ($productExistID > 0) {
            $ObjProduct->destroyTablesWithProductID($productExistID, 'product_custom_option_link');
        }
        if (!empty($gl_options)) {
            foreach ($gl_options as $v) {
                $v['productID'] = $pid;
                $this->insert($v, "product_custom_option_link");
            }
        }
        // Clone product options
        $this->fn_clone_product_options($product_id, $pid, $changed_pdt_option);
        // Clone product Attributes
        $data = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_attribute_values WHERE  productID =" . $product_id, MYSQLI_ASSOC);
        if ($productExistID > 0) {
            $ObjProduct->destroyAttributeValues($productExistID, $currentLanguageID);
        }
        foreach ($data as $v) {
            $v['productID'] = $pid;
            $attrval_id     = $v['attrValueID'];
            unset($v['attrValueID']);
            $new_attrval_id = $this->insert($v, "product_attribute_values");
            // Clone descriptions
            if ($v['attrOptionID'] == 0) {
                $a_data = $this->ObjDatabase->readValues("SELECT * FROM `" . DB_PREFIX . "product_attribute_value_details` WHERE  attrValueID = " . $attrval_id, MYSQLI_ASSOC);
                foreach ($a_data as $a_v) {
                    $a_v['attrValueID'] = $new_attrval_id;
                    unset($a_v['attrValDetID']);
                    $this->insert($a_v, 'product_attribute_value_details');
                    // Clone product files
                    if (file_exists(__CORE_PUBLIC_PATH . "/uploads/catalog/attributes/" . $a_v['attrDetValue'])) {
                        copy(__CORE_PUBLIC_PATH . "/uploads/catalog/attributes/" . $a_v['attrDetValue'], __CORE_PUBLIC_PATH . "/uploads/catalog/attributes/clone_" . rand(1, 200) . "_" . $a_v['attrDetValue']);
                    }
                }
            }
        }
        // Clone product Shipping
        if ($productExistID > 0) {
            $ObjProduct->destroyTablesWithProductID($productExistID, 'shipping_to_product');            
        }
        $data = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "shipping_to_product WHERE  productID =" . $product_id, MYSQLI_ASSOC);
        foreach ($data as $v) {
            $old_ship_product_id = $v['shippingtoproductID'];
            unset($v['shippingtoproductID']);
            $v['productID']      = $pid;
            $new_ship_product_id = $this->insert($v, "shipping_to_product");
            $_data               = $this->ObjDatabase->readValues("SELECT * FROM `" . DB_PREFIX . "product_to_shipping_deliveryzone` WHERE  shippingtoproductID = " . $old_ship_product_id, MYSQLI_ASSOC);
            foreach ($_data as $_v) {
                unset($_v['zoneToproductID']);
                $_v['shippingtoproductID'] = $new_ship_product_id;
                $this->insert($_v, 'product_to_shipping_deliveryzone');
            }
        }
        // Clone Related Products
        if ($productExistID > 0) {
            $ObjProduct->destroyTablesWithProductID($productExistID, 'product_link_relation');
        }
        $data = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_link_relation WHERE  productID =" . $product_id, MYSQLI_ASSOC);
        foreach ($data as $v) {
            $v['productID'] = $pid;
            $this->insert($v, "product_link_relation");
        }
        if ($productExistID > 0) {
            $ObjProduct->destroyTablesWithProductID($productExistID, 'product_link_up_sell');
        }
        // Clone Upseell Products
        $data = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_link_up_sell WHERE  productID =" . $product_id, MYSQLI_ASSOC);
        foreach ($data as $v) {
            $v['productID'] = $pid;
            $this->insert($v, "product_link_up_sell");
        }
        if ($productExistID > 0) {
            $ObjProduct->destroyTablesWithProductID($productExistID, 'product_link_cross_sell');
        }
        // Clone Cross Sell Products
        $data = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_link_cross_sell WHERE  productID =" . $product_id, MYSQLI_ASSOC);
        foreach ($data as $v) {
            $v['productID'] = $pid;
            $this->insert($v, "product_link_cross_sell");
        }
        // insert into rewrite url table
        if ($productExistID > 0) {
            $ObjProduct->destroyUrlWithProductID($productExistID);
        }
        $this->fn_insert_rewrite_table($languageIDs, $pid, $rewriteProduct, $rewriteCat, $urlSuffix);
        //exit;
        $orig_name = isset($orig_name) ? $orig_name : '';
        $new_name  = isset($new_name) ? $new_name : '';
        return array(
            'product_id' => $pid,
            'orig_name' => $orig_name,
            'product' => $new_name
        );
    }
    function insert($data, $table) {
        $values = array();
        $table  = "`" . DB_PREFIX . $table . "`";
        foreach ($data as $key => $v) {
            if ($v != '') {
                $v        = $this->escape($v);
                $values[] = "'$v'";
            } else {
                $default  = $this->ObjDatabase->readValue("SHOW COLUMNS FROM " . $table . " WHERE Field =  '" . $key . "' ");
                $values[] = ($default['Null'] == 'NO') ? "''" : 'NULL';
            }
        }
        //echo "INSERT INTO $table (`" . implode('`, `', array_keys($data)) . "`) VALUES (" . implode(', ', $values) . ");\n";exit;
        $result = $this->ObjDatabase->setQuery("INSERT INTO $table (`" . implode('`, `', array_keys($data)) . "`) VALUES (" . implode(', ', $values) . ");\n");
        if ($result)
            return $this->ObjDatabase->getInsertId();
    }
    function update($data, $table, $where) {
        $whereString = '1';
        $updateString = '';
        $table = "`" . DB_PREFIX . $table . "`";
        foreach ($data as $key => $val) {
            if ($val !== '')
                $val = "'" . $this->fn_html_entity_encode($val) . "'";
            else {
                if ($table) {
                    $default = $this->ObjDatabase->readValue("SHOW COLUMNS FROM " . $table . " WHERE Field =  '" . $key . "' ");
                    $val = ($default['Null'] == 'NO') ? "'$val'" : 'NULL';
                }
                else
                    $val = "''";
            }
            $updateString.="`" . $key . "`=" . $val . ",";
        }
        $updateString = trim($updateString, ",");
        if ($where) {
            foreach ($where as $key => $val) {
                $whereString.=" AND `" . $key . "`='" . $this->fn_html_entity_encode($val) . "'";
            }
        }
        $sqlString = "UPDATE $table SET " . $updateString . " WHERE " . $whereString;
                //echo $table.'<br/>';exit;
//                if($table=='`dp_deal_details`'){
//                  echo $sqlString; exit; 
//                }exit;
        $this->ObjDatabase->setQuery($sqlString);
    }
    /**
     * Clones dynamic object data
     * 
     * @param string $object_type Object type in DB
     * @param int $old_object_id Object identifier to get data from
     * @param int $new_object_id Object identifier to clone
     * @return bool Always true
     */
    public function fn_clone_product_variants($old_object_id, $new_object_id) {
        $changed_pdt_option = array();
        $data               = $this->ObjDatabase->readValues("SELECT * FROM `" . DB_PREFIX . "product_options` WHERE productID=" . $old_object_id, MYSQLI_ASSOC);
        foreach ($data as $v) {
            $v['productID']  = $new_object_id;
            $is_exist_string = $v['optionSKU'] . "-clone";
            $exist_sku       = $this->ObjDatabase->getField("SELECT optionSKU FROM `" . DB_PREFIX . "product_options` WHERE optionSKU like '%" . $is_exist_string . "%' ORDER BY `optionSKU` DESC LIMIT 1");
            if (!empty($exist_sku)) {
                $iterator       = array_pop(explode('-clone', $exist_sku));
                $v['optionSKU'] = $v['optionSKU'] . "-clone" . ($iterator + 1);
            } else {
                $v['optionSKU'] = $v['optionSKU'] . "-clone1";
            }
            $old_option_id = $v['productOptionID'];
            unset($v['productOptionID']);
            $new_option_id                      = $this->insert($v, 'product_options');
            $changed_pdt_option[$old_option_id] = $new_option_id;
            // Clone descriptions
            $_data                              = $this->ObjDatabase->readValues("SELECT * FROM `" . DB_PREFIX . "product_option_details` WHERE  productOptionID = " . $old_option_id, MYSQLI_ASSOC);
            foreach ($_data as $_v) {
                unset($_v['productOptionDetailsID']);
                $_v['productOptionID'] = $new_option_id;
                if ($v['productOptionDefault'] == 'Yes')
                    $_v['productOptionName'] = $_v['productOptionName'] . ' [CLONE]';
                $this->insert($_v, 'product_option_details');
            }
            
            $_data = $this->ObjDatabase->readValues("SELECT " . $new_option_id . " AS productOptionID,businessID,businessOptionSKU,productOptionRegularPrice,productOptionProductPrice,productPrepayAmount,productOptionQuantity,productQuantityNotifyAt,productQuantityUnlimited,productOptionCashBack,busWareHouse,businessDispatchTime,busProductStatus,businessOptionDefault,dealPrice FROM `" . DB_PREFIX . "products_options_business` WHERE  productOptionID = " . $old_option_id, MYSQLI_ASSOC);
            foreach ($_data as $_v) {
                $this->insert($_v, 'products_options_business');
            }
            
            $_data = $this->ObjDatabase->readValues("SELECT " . $new_option_id . " AS productOptionID,businessID,userGroupID,specialPrice FROM `" . DB_PREFIX . "variant_group_price` WHERE  productOptionID = " . $old_option_id, MYSQLI_ASSOC);
            foreach ($_data as $_v) {
                $this->insert($_v, 'variant_group_price');
            }
            $_data = $this->ObjDatabase->readValues("SELECT " . $new_option_id . " AS productOptionID,allGroups,userGroupID,quantity,tierPrice FROM `" . DB_PREFIX . "variant_tier_price` WHERE  productOptionID = " . $old_option_id, MYSQLI_ASSOC);
            foreach ($_data as $_v) {
                $this->insert($_v, 'variant_tier_price');
            }
        }
        return $changed_pdt_option;
    }
    /**
     * This function clones options to product from a product or from a global option
     *
     * @param int $from_product_id Identifier of product from that options are copied
     * @param int $to_product_id Identifier of product to that options are copied
     * @param type $from_global_option_id Identifier of the global option or false (if options are copied from product)
     */
    function fn_clone_product_options($from_product_id, $to_product_id, $changed_pdt_option) {
        /**
         * Adds additional actions before poduct options clone
         *
         * @param int $from_product_id Identifier of product from that options are copied
         * @param int $to_product_id Identifier of product to that options are copied
         * @param int/boolean $from_global_option_id Identifier of the global option or false (if options are copied from product)
         */
        $ObjImage = new ImageModel();
        // Get all product options assigned to the product
        $id_req   = "productID =" . $from_product_id;
        $linked   = $this->ObjDatabase->getField("SELECT COUNT(customOptionID) FROM " . DB_PREFIX . "product_custom_option_link WHERE  productID =" . $from_product_id);
        if (!empty($linked)) {
            $data             = $this->ObjDatabase->readValues("SELECT pco.*,pcl.sortOrder  FROM " . DB_PREFIX . "product_custom_option_link pcl LEFT JOIN " . DB_PREFIX . "product_custom_option pco ON(pcl.customOptionID=pco.customOptionID) WHERE pco.isGlobal='0' AND $id_req", MYSQLI_ASSOC);
            // Fill array of options for linked global options options
            $change_options   = array();
            $change_varaiants = array();
            // If global option are linked than ids will be the same
            $change_options   = $this->ObjDatabase->getHashSingleArray("SELECT customOptionID FROM " . DB_PREFIX . "product_custom_option_link WHERE productID = $from_product_id", array(
                'customOptionID',
                'customOptionID'
            ));
            if (!empty($change_options)) {
                foreach ($change_options as $value) {
                    $change_varaiants = $this->fn_array_merge($this->ObjDatabase->getHashSingleArray("SELECT customOptionVariantID  FROM " . DB_PREFIX . "product_custom_option_variant WHERE customOptionID =.$value", array(
                        'customOptionVariantID',
                        'customOptionVariantID'
                    )), $change_varaiants, true);
                }
            }
            foreach ($data as $v) {
                // Clone main data
                $option_id  = $v['customOptionID'];
                $sort_order = $v['sortOrder'];
                unset($v['customOptionID']);
                unset($v['sortOrder']);
                $new_option_id = $this->insert($v, 'product_custom_option');
                //APPLY LINK
                $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_custom_option_link (customOptionID, productID,sortOrder) VALUES (" . $new_option_id . "," . $to_product_id . "," . $sort_order . ")");
                // Clone descriptions
                $_data = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_custom_option_details WHERE  customOptionID = " . $option_id, MYSQLI_ASSOC);
                foreach ($_data as $_v) {
                    $_v['customOptionID'] = $new_option_id;
                    unset($_v['customOptionDetailsID']);
                    $this->insert($_v, "product_custom_option_details");
                }
                $change_options[$option_id] = $new_option_id;
                // Clone variants if exists
                if ($v['inputType'] == 'select' || $v['inputType'] == 'multiselect') {
                    $_data = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_custom_option_variant WHERE customOptionID =" . $option_id, MYSQLI_ASSOC);
                    foreach ($_data as $_v) {
                        $variant_id           = $_v['customOptionVariantID'];
                        $_v['customOptionID'] = $new_option_id;
                        if ($_v['variantThumbImage'] != '') {
                            //$thumbImage  = "clone_".rand(1,100)."_".$_v['variantThumbImage'];
                            $thumbImage = substr_replace($_v['variantThumbImage'], rand(1, 1000) . '.', strrpos($_v['variantThumbImage'], '.'), 1);
                            $ObjImage->copy_file(__CORE_PUBLIC_PATH . "/uploads/catalog/custom-option-variant/" . $_v['variantThumbImage'], '/' . __UPLOADS_FOLDER . "catalog/custom-option-variant/" . $thumbImage,'Y');
                            $_v['variantThumbImage'] = $thumbImage;
                        }
                        unset($_v['customOptionVariantID']);
                        $new_variant_id = $this->insert($_v, "product_custom_option_variant");
                        // Clone Exceptions
                        if (!empty($exceptions)) {
                            //fn_clone_options_exceptions($exceptions, $option_id, $variant_id, $new_option_id, $new_variant_id);
                        }
                        $change_varaiants[$variant_id] = $new_variant_id;
                        // Clone descriptions
                        $__data                        = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_custom_option_variant_details WHERE customOptionVariantID = " . $variant_id, MYSQLI_ASSOC);
                        foreach ($__data as $__v) {
                            $__v['customOptionVariantID'] = $new_variant_id;
                            unset($__v['customOptionVariantDetailsID']);
                            $this->insert($__v, "product_custom_option_variant_details");
                        }
                    }
                    unset($_data, $__data);
                }
            }
            $global_data = $this->ObjDatabase->readValues("SELECT pco.customOptionID,pco.inputType FROM " . DB_PREFIX . "product_custom_option_link pcl LEFT JOIN " . DB_PREFIX . "product_custom_option pco ON(pcl.customOptionID=pco.customOptionID) WHERE pco.isGlobal='1' AND $id_req", MYSQLI_ASSOC);
            foreach ($global_data as $gv) {
                $option_id = $gv['customOptionID'];
                if ($gv['inputType'] == 'select' || $gv['inputType'] == 'multiselect') {
                    $_gvdata = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_custom_option_variant WHERE customOptionID =" . $option_id, MYSQLI_ASSOC);
                    foreach ($_gvdata as $_vg) {
                        $variant_id                    = $_vg['customOptionVariantID'];
                        $change_varaiants[$variant_id] = $variant_id;
                    }
                }
            }
            // Clone Inventory			
            $this->fn_clone_options_inventory($from_product_id, $to_product_id, $changed_pdt_option, $change_varaiants);
        }
    }
    //
    // Clone Inventory
    //
    function fn_clone_options_inventory($from_product_id, $to_product_id, $changed_options, $variants) {
        $ObjProduct = new ProductModel();
        /**
         * Adds additional actions before options inventory clone
         *
         * @param int $from_product_id Identifier of product from that options are copied
         * @param int $to_product_id Identifier of product to that options are copied
         * @param array $options Array with options identifiers where old identifiers points to new identifier
         * @param array $variants Array with variant identifiers where old identifiers points to new identifier
         */
        $inventory  = $this->ObjDatabase->readValues("SELECT proComb.* FROM " . DB_PREFIX . "product_combination proComb  WHERE proComb.status!='D' AND 
							    productID =" . $from_product_id, MYSQLI_ASSOC);
        if (!empty($inventory)) {
            foreach ($inventory as $key => $value) {
                $_comb        = array();
                $old_combo_id = $value['combinationID'];
                unset($value['combinationID']);
                $_variants = explode('_', $value['combination']);
                unset($_variants[0]);
                $inventory[$key]['combination'] = '';
                foreach ($_variants as $kk => $vv) {
                    $_comb[0] = $to_product_id;
                    $_comb[]  = $variants[$vv];
                }
                $inventory[$key]['combination'] = implode('_', $_comb);
                $value['combinationQty']        = $value['combinationQty'];
                $value['productID']             = $to_product_id;
                $value['combinationSKU']        = $value['combinationSKU'] . "-" . $this->generate_random_letters(4);
                $value['combinationHash']       = $this->makeHAsh($inventory[$key]['combination']);
                $value['combination']           = rtrim($inventory[$key]['combination'], "|");
                $new_combo_id                   = $this->insert($value, "product_combination");
                // Clone option images
                $this->fn_clone_image_pairs($from_product_id, $to_product_id, 'combo', '', '', $old_combo_id, $new_combo_id);
                
                $_data = $this->ObjDatabase->readValues("SELECT " . $new_combo_id . " AS combinationID,businessID,businessCombSKU,businessCombQuantity,businessCombPrice,businessCombDiff FROM `" . DB_PREFIX . "product_combination_business` WHERE combinationID = " . $old_combo_id, MYSQLI_ASSOC);
                foreach ($_data as $_v) {
                    $this->insert($_v, 'product_combination_business');
                }
            }
        }
    }
    //helper function
    function fn_array_merge() {
        $arg_list      = func_get_args();
        $preserve_keys = true;
        $result        = array();
        if (is_bool(end($arg_list))) {
            $preserve_keys = array_pop($arg_list);
        }
        foreach ((array) $arg_list as $arg) {
            foreach ((array) $arg as $k => $v) {
                if ($preserve_keys == true) {
                    $result[$k] = !empty($result[$k]) && is_array($result[$k]) ? $his->fn_array_merge($result[$k], $v) : $v;
                } else {
                    $result[] = $v;
                }
            }
        }
        return $result;
    }
    function fn_clone_image_pairs($target_product_id, $product_id, $object_type, $changed_options = array(), $orig_image = '', $parent_object_id = '', $object_id = '') {
        //Media//
        if ($object_type == 'option_image') {
            $destination = "product";
            $pair_data   = $this->ObjDatabase->readValues("SELECT * FROM " . DB_PREFIX . "product_media WHERE productID =" . $product_id . " AND productObjectType ='DO'", MYSQLI_ASSOC);
            if (empty($pair_data)) {
                return false;
            }
            foreach ($pair_data as $pair_id => $p_data) {
                unset($p_data['productMediaID']);
                $p_data['productID']       = $target_product_id;
                $p_data['productObjectID'] = $changed_options[$p_data['productObjectID']];
                $filename                  = $p_data['productMedia'];
                $p_data['productMedia']    = $this->fn_clone_images($filename, $destination);
                $this->insert($p_data, "product_media");
            }
        }
        if ($object_type == 'product') {
            $filename    = $orig_image;
            $destination = 'product';
            return $new_name = $this->fn_clone_images($filename, $destination);
        }
        if ($object_type == 'combo') {
            $destination = 'product-combination';
            $p_data      = $this->ObjDatabase->readValue("SELECT * FROM " . DB_PREFIX . "product_media WHERE productObjectID =" . $parent_object_id . " AND productObjectType ='C'", MYSQLI_ASSOC);
            if (empty($p_data)) {
                return false;
            }
            $p_data['productID']       = $target_product_id;
            $p_data['productObjectID'] = $object_id;
            unset($p_data['productMediaID']);
            $filename               = $p_data['productMedia'];
            $p_data['productMedia'] = $this->fn_clone_images($filename, $destination);
            $this->insert($p_data, "product_media");
        }
    }
    function fn_clone_images($filename, $destination) {
        $ObjImage      = new ImageModel();
        $extension_pos = strrpos($filename, '.'); // find position of the last dot, so where the extension starts
        $sep_pos       = strrpos($filename, '__');
        $new_name      = substr($filename, 0, $sep_pos) . '__' . rand() . substr($filename, $extension_pos);
        //clone Product Images	
        $large         = __UPLOADS_FOLDER . "catalog/" . $destination . "/large/" . $filename;
        $thumb         = __UPLOADS_FOLDER . "catalog/" . $destination . "/thumb/" . $filename;
        $small_thumb   = __UPLOADS_FOLDER . "catalog/" . $destination . "/small/" . $filename;
        $preview       = __UPLOADS_FOLDER . "catalog/" . $destination . "/preview/" . $filename;
        $preview_main  = __UPLOADS_FOLDER . "catalog/" . $destination . "/preview-main/" . $filename;
        $custom        = __UPLOADS_FOLDER . "catalog/" . $destination . "/custom/" . $filename;       
         
        if ($ObjImage->file_exist($large))
            $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . $large, '/' . __UPLOADS_FOLDER . "catalog/" . $destination . "/large/" . $new_name,'Y');
        if ($ObjImage->file_exist($thumb))
            $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . $thumb, '/' . __UPLOADS_FOLDER . "catalog/" . $destination . "/thumb/" . $new_name,'Y');
        if ($ObjImage->file_exist($small_thumb))
            $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . $small_thumb, '/' . __UPLOADS_FOLDER . "catalog/" . $destination . "/small/" . $new_name,'Y');
        if ($ObjImage->file_exist($preview))
            $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . $preview, '/' . __UPLOADS_FOLDER . "catalog/" . $destination . "/preview/" . $new_name,'Y');
        if ($ObjImage->file_exist($preview_main))
            $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . $preview_main, '/' . __UPLOADS_FOLDER . "catalog/" . $destination . "/preview-main/" . $new_name,'Y');
        if ($ObjImage->file_exist($custom))
            $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . $custom, '/' . __UPLOADS_FOLDER . "catalog/" . $destination . "/custom/" . $new_name,'Y');
        return $new_name;
    }
    function generate_random_letters($length) {
        $random = '';
        for ($i = 0; $i < $length; $i++) {
            $random .= chr(rand(ord('a'), ord('z')));
        }
        return $random;
    }
    //Insert into Rewrite table
    function fn_insert_rewrite_table($languageIDs, $pid, $product, $categories, $urlSuffix) {
        $SefModel = new SefModel();
        $args     = array(
            'productUrl' => $product['productUrl'] . '-' . $pid
        );
        $product_sef_format        = $this->getSettingsValue('product_sef_format');
        $product_sef_format=    isset($product_sef_format)  ? $product_sef_format   : false;
        $SefModel->_refreshProductRewrites($languageIDs['AllList'], $pid, $urlSuffix, $args,'',$product_sef_format, 'insert');
        if($product_sef_format){
        foreach ($categories as $key => $category) {
            $args['category'] = $category['productCategoryID'];
            $SefModel->_refreshProductRewrites($languageIDs['AllList'], $pid, $urlSuffix, $args,'',$product_sef_format, 'insert');
        }
        }
    }
    public function getSettingsValue($settingsKey) {
        $sql              = " SELECT 
						settingsValue 
					FROM 			
						" . DB_PREFIX . "settings  
                    WHERE 
                    	settingsKey = '" . $settingsKey . "' ";
        $resSettingsValue = $this->ObjDatabase->readValue($sql);
        return $resSettingsValue['settingsValue'];
    }
    function fn_html_entity_encode($data) {
        if (!is_array($data)) {
            $data = htmlspecialchars($data, ENT_NOQUOTES, 'UTF-8');
            return $this->escape($data);
        } else {
            return $data;
        }
    }
}
//END OF CLASS
