<?php
ini_set('serialize_precision', 14);
ini_set('precision', 14);
require '../manager/inventory.php';
require_once(__DIR__.'/../php/product.php');
require_once(__DIR__.'/../php/inventory.php');
require_once(__DIR__.'/../php/helper/category-helper.php');
class Setting {
    private $dataPath;
    private $inventoryName;
    public function __construct() {
        $this->inventory = new InventoryCore();
        $this->dataPath = '../setting/';
        $this->formats = array();
        $this->uploaded_dir = '../images/icons/';
        $this->productTemplatePath = __DIR__.'/../setting/_product_template.json';
        $this->adminPath = $this->dataPath.'admin.json';
        $this->settingPath = $this->dataPath.'setting-inventory.json';
        $this->headerPath = $this->dataPath.'setting-header.json';
        $this->InventoryLogPath = $this->dataPath.'inventory.log';
        $this->categoryImagePath = __DIR__.'/../images/category/';
        $this->promoImagePath = __DIR__.'/../images/promo/';
        $this->packageImagePath = __DIR__.'/../images/Packaging/';
        $this->exclude = array('Books');
    }

    public function loadData() {
        $setting_file = $this->dataPath.'admin.json';
        if (!is_file($setting_file)) {
            return null;
        }
        $json_result = json_decode(file_get_contents($setting_file), true);
        foreach ($json_result['Categories'] as &$cat) {
            $filename = $this->inventory->convertToFormat($cat['CategoryName']);
            if (file_exists($this->categoryImagePath.$filename.'.jpg')) {
                $cat['Image'] = $filename.'.jpg';
            }
        }
        $products = $this->getProductList();
        return array(
            'productTemplate' => $this->inventory->loadJson($this->productTemplatePath),
            'setting' => $json_result,
            'products' => $products,
            'formats' => $this->formats,
            'log' => $this->getLogList(),
        );

    }
    public function getLogList() {
        $list = array();
        $list['download'] = array_values(preg_grep("/^process.*\.txt$/", scandir(__DIR__.'/../php/log/download/')));
        $list['upload'] = array_values(preg_grep("/^process.*\.txt$/", scandir(__DIR__.'/../php/log/upload/')));
        return $list;
     }
    private function checkIfWordRestrictExist($field_name, $dataElement, $restrictedWordVal)
    {
        if (!isset($dataElement[$field_name]))
            return false;
        $field_value = $dataElement[$field_name];
        if (is_array($field_value)) {
                $rs = false;
            foreach ($field_value as $v) {
                if (preg_match("/\b{$restrictedWordVal}\b/i", $v)) {
                    $rs = true;
                }
            }
            return $rs;
        }
        elseif (preg_match("/\b{$restrictedWordVal}\b/i", $field_value)) {
            return true;
        }
        return false;
    }
    public function getRestrictedProducts() {
        $inventories = $this->loadAllInventories($this->exclude);
        $get_all_resttricted_words = json_decode(file_get_contents($this->dataPath.'admin.json'), true);
        $restrictedWords = $get_all_resttricted_words['RestrictedWords'];
        $restrictedWordsArray = explode(', ',$restrictedWords);
        $restrictedProducts = array();
        if(is_array($restrictedWordsArray) && count($restrictedWordsArray))
        {
            $field_names = array('Description', 'Benefits');
            foreach ($inventories as $category => $inventory) {
                foreach ($inventory as $product) {
                    $res = array(
                        'product' => $product['Product'],
                        'format' => $category,
                        'restricted' => array()
                    );
                    foreach($field_names as $field_name) {
                        foreach($restrictedWordsArray as $restrictedWordVal) {
                            if (isset($product[$field_name]) && is_array($product[$field_name])) {
                                foreach ($product[$field_name] as $key => $value) {
                                    if($this->checkIfWordRestrictExist($key, $product[$field_name], $restrictedWordVal)) {
                                        $key = is_numeric($key)?'':$key;
                                        $field = "{$field_name}[{$key}]";
                                        if (!isset($res['restricted'][$field]))
                                            $res['restricted'][$field] = array();
                                        $res['restricted'][$field][] = $restrictedWordVal;
                                    }
                                }
                            } else {
                                if($this->checkIfWordRestrictExist($field_name, $product, $restrictedWordVal)) {
                                    if (!isset($res['restricted'][$field_name]))
                                        $res['restricted'][$field_name] = array();
                                    $res['restricted'][$field_name][] = $restrictedWordVal;
                                }
                            }
                        }
                    }
                    if (count($res['restricted']))
                        $restrictedProducts[] = $res;
                }
            }
            return $restrictedProducts;
        }
    }
    public function loadAllInventories($exclude = array()) {
        $inventoryFiles = $this->inventory->getList();
        $inventoryFiles = array_filter($inventoryFiles, function($filename) use ($exclude) {
            $category = $this->inventory->removeExt($filename);
            return !in_array($category, $exclude);
        });
        $rs = array();
        foreach ($inventoryFiles as $filename) {
            $category = $this->inventory->removeExt($filename);
            $rs[$category] = $this->inventory->loadInventory($filename);
        }
        return $rs;
    }
    public function getExpirationDateSetting() {
        $setting_file = $this->dataPath.'admin.json';
        $setting = json_decode(file_get_contents($setting_file), true);
        $formats = $this->inventory->getList();
        $formats = array_map(function($f) {
            return $this->inventory->removeExt($f);
        }, $formats);
        $rs = array();
        foreach ($formats as $format) {
            if (isset($setting[$format]))
                $rs[] = array(
                    'format' => strtolower($format),
                    'expirationTime' => $setting[$format],
                );
        }
        return $rs;
    }
    private function getStockSupplier($suppliers) {
        if (!is_array($suppliers))
            return false;
        uasort($suppliers, function($s1, $s2) {
            return strcmp($s1['DateDelivery'], $s2['DateDelivery']);
        });
        foreach ($suppliers as $supplier) {
            if ((isset($supplier['StockRetailLB']) && $supplier['StockRetailLB'] > 0) || (isset($supplier['StockRecipe']) && $supplier['StockRecipe'] > 0))
                return $supplier;
        }
        return null;
    }
    private function getProductList() {
        $retail = new Retail();
        $list = array();
        $formats = array();
        $inventories = $this->inventory->loadAllInventories();
        foreach ($inventories as $format) {
            $formats[] = $format['format'];
            if (is_array($format['data']))
                foreach ($format['data'] as $product) {
                    $supplier = $retail->pickSupplier($product);
                    $list[] = array(
                        'label' => $product['Product'],
                        'value' => $product['Product'],
                        'supplier' => $supplier,
                        'category' => $format['format']
                    );
                }
        }
        $this->formats = $formats;
        return $list;
    }
    function reArrayFiles($file_post) {
        $file_ary = array();
        $index = array_keys($file_post['name']);
        $file_keys = array_keys($file_post);
        foreach ($index as $i) {
            foreach ($file_keys as $key) {
                $file_ary[$i][$key] = $file_post[$key][$i];
            }
        }

        return $file_ary;
    }
    private function uploadImage($file, $destName, $imageType='') {
    	$uploaded_dir = $this->categoryImagePath;
    	if($imageType != '') {
    		if($imageType=='BodiPromo') {
				$uploaded_dir = $this->promoImagePath;
			}
			else if($imageType=='PackagingCategories') {
				$uploaded_dir = $this->packageImagePath;
			}
		}

        if (!is_dir($uploaded_dir)) {
            mkdir($uploaded_dir);
        }
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $temp = explode(".", $file["name"]);
        if (count($temp) > 1) {
            $extension = array_pop($temp);
        } else {
            $extension = '';
        }
        if ((($file["type"] == "image/gif")
            || ($file["type"] == "image/jpeg")
            || ($file["type"] == "image/jpg")
            || ($file["type"] == "image/pjpeg")
            || ($file["type"] == "image/x-png")
            || ($file["type"] == "image/png"))
            && in_array($extension, $allowedExts)) {
            if ($file["error"] > 0) {
            } else {
            	$filename = $destName.'.'.$extension;
            	if($imageType != '') {
    				if($imageType=='BodiPromo' || $imageType=='PackagingCategories') {
    					$filename = $destName;
    				}
    			}
                if (move_uploaded_file($file["tmp_name"], "$uploaded_dir" . $filename))
                    return $filename;
            }
        }
        return false;
    }
    private function uploadImg() {
        $uploaded_dir = '../images/icons/';
        if (!is_dir($uploaded_dir)) {
            mkdir($uploaded_dir);
        }
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        foreach($_FILES['file'] as $key => $file)
        {
            $temp = explode(".", $file["name"]);
            if (count($temp) > 1) {
                $extension = array_pop($temp);
            } else {
                $extension = '';
            }
            if ((($file["type"] == "image/gif")
                || ($file["type"] == "image/jpeg")
                || ($file["type"] == "image/jpg")
                || ($file["type"] == "image/pjpeg")
                || ($file["type"] == "image/x-png")
                || ($file["type"] == "image/png"))
                && in_array($extension, $allowedExts)) {
                if ($file["error"] > 0) {
                } else {
                    $filename = $file['name'].'_'.$key.'_temp';
                    move_uploaded_file($file["tmp_name"],
                        "$uploaded_dir" . $filename);
                }
            }
        }
    }

    private function getDifferentFilename($filename) {
        $matches = array();
        if (preg_match('/(.*)_([1-9])*$/', $filename, $matches, PREG_OFFSET_CAPTURE)) {
            $suffix = $matches[2][0] + 1;
            $filename = $matches[1][0] . '_'.$suffix;
        } else {
            $filename .= '_2';
        }
        return $filename;
    }
    public function save($dataElement) {
        $result = array();
        $result['success'] = false;
        if (!$dataElement || empty($dataElement)) {
            $result['success'] = false;
            $result['error'] = 'Data is null';
            return $result;
        }

        $updateFileDataPath = $this->dataPath.'admin.json';
        if (isset($_FILES['file']) && count($_FILES['file'])) {
            $_FILES['file'] = $this->reArrayFiles($_FILES['file']);
            $this->uploadImg();
        }
        $chars = array(' ', ':', '/', '"', '?', '@', '#', '$', '%', '&', '*', '(', ')', '-', '+', '|', '<', '>');
        $dataElement['Certificates'] = json_decode($dataElement['Certificates'], true);
        foreach ($dataElement['Certificates'] as $k => &$e) {
            if ($e['oldImage'] || $e['file']) {
                if ($e['oldImage']) {
                    $e['image'] = $e['oldImage'];
                    if ($e['delete']) {
                        if (is_file('../images/icons/'.$e['image']))
                            unlink('../images/icons/'.$e['image']);
                        unset($dataElement['Certificates'][$k]);
                    } elseif ($e['file']) {
                        if (is_file('../images/icons/'.$e['image']))
                            unlink('../images/icons/'.$e['image']);
                        $temp = $e['file'].'_'.$e['id'].'_temp';
                        $name = explode(".", $e["file"]);
                        if (count($name) > 1) {
                            $extension = array_pop($name);
                        } else {
                            $extension = '';
                        }
                        if ($e['label']) {
                            $filename = str_replace($chars, '_', $e['label']);
                        } else {
                            $filename = implode('.', $name);
                        }
                        $full_filename = $filename.'.'.$extension;
                        while (is_file($this->uploaded_dir.$full_filename)) {
                            $filename = $this->getDifferentFilename($filename);
                            $full_filename = $filename.'.'.$extension;
                        }
                        $e['label'] = $filename;
                        if (is_file($this->uploaded_dir.$temp)) {
                            rename($this->uploaded_dir.$temp, $this->uploaded_dir . $full_filename);
                            $e['image'] = $full_filename;
                        }
                    }
                } else {
                    if ($e['file']) {
                        $temp = $e['file'].'_'.$e['id'].'_temp';
                        $name = explode(".", $e["file"]);
                        if (count($name) > 1) {
                            $extension = array_pop($name);
                        } else {
                            $extension = '';
                        }
                        if ($e['label']) {
                            $filename = str_replace($chars, '_', $e['label']);
                        } else {
                            $filename = implode('.', $name);
                        }
                        $full_filename = $filename.'.'.$extension;
                        while (is_file($this->uploaded_dir.$full_filename)) {
                            $filename = $this->getDifferentFilename($filename);
                            $full_filename = $filename.'.'.$extension;
                        }
                        $e['label'] = $filename;
                        if (is_file($this->uploaded_dir.$temp)) {
                            rename($this->uploaded_dir.$temp, $this->uploaded_dir . $full_filename);
                            $e['image'] = $full_filename;
                        }
                    } else {
                        unset($dataElement['Certificates'][$k]);
                    }
                }
            } else {
                unset($dataElement['Certificates'][$k]);
            }
        }
        $dataElement['Certificates'] = array_map(function($e) {
            return array(
                'label' => $e['label'] != ''?$e['label']:$e['image'],
                'image' => $e['image'],
            );
        }, array_values($dataElement['Certificates']));

        //Categories
        if (isset($_FILES['category']) && count($_FILES['category'])) {
            $_FILES['category'] = $this->reArrayFiles($_FILES['category']);
        }
        $dataElement['Categories'] = json_decode($dataElement['Categories'], true);
        foreach ($dataElement['Categories'] as $k => &$e) {
            $image = false;
            if ($e['imageUpload']) {
                if (isset($_FILES['category'][$e['imageUpload']])) {
                    $this->uploadImage($_FILES['category'][$e['imageUpload']], $this->inventory->convertToFormat($e['CategoryName']));
                }
            }
            unset($e['imageUpload']);
        }
        //end categoires

        //bodi promo
        if (isset($_FILES['bodipromo']) && count($_FILES['bodipromo'])) {
            $_FILES['bodipromo'] = $this->reArrayFiles($_FILES['bodipromo']);
        }
        $dataElement['BodiPromo'] = json_decode($dataElement['BodiPromo'], true);
        foreach ($dataElement['BodiPromo'] as $k => &$e) {
            $image = false;
            if ($e['PromoLogoImage']) {
	            //echo "<pre>";
		        //print_r($_FILES['bodipromo'][$e['PromoLogoImage']]);
		        //die('SSS');
                if (isset($_FILES['bodipromo'][$e['PromoLogoImage']])) {
                    $PromoLogoImage = $this->uploadImage($_FILES['bodipromo'][$e['PromoLogoImage']], $_FILES['bodipromo'][$e['PromoLogoImage']]['name'],'BodiPromo');
                    $e['PromoLogo'] = $PromoLogoImage;
                }
            }
            unset($e['PromoLogoImage']);
        }

        //packaging categories
        if (isset($_FILES['packagingcategories']) && count($_FILES['packagingcategories'])) {
            $_FILES['packagingcategories'] = $this->reArrayFiles($_FILES['packagingcategories']);
        }
        $dataElement['PackagingCategories'] = json_decode($dataElement['PackagingCategories'], true);
        foreach ($dataElement['PackagingCategories'] as $k => &$e) {
            $image = false;
            if ($e['PackageImageImage']) {
	            //echo "<pre>";
		        //print_r($_FILES['packagingcategories'][$e['PackageImageImage']]);
		        //die('SSS');
                if (isset($_FILES['packagingcategories'][$e['PackageImageImage']])) {
                    $PackageImageImage = $this->uploadImage($_FILES['packagingcategories'][$e['PackageImageImage']], $_FILES['packagingcategories'][$e['PackageImageImage']]['name'],'PackagingCategories');
                    //echo "<br>PackageImageImage=$PackageImageImage";die('SSS');
                    $e['PackageImage'] = $PackageImageImage;
                }
            }
            unset($e['PackageImageImage']);
        }
		//-------------
		
        $data = $this->updateObjectFromData($dataElement);
        $css = $this->generateCss($data);
        $a = file_put_contents(__DIR__.'/../css/color.css', $css);
        $success = file_put_contents($updateFileDataPath . '_temp', json_encode($data, JSON_PRETTY_PRINT));
        if ($success) {
            $moveSuccess = rename($updateFileDataPath . '_temp', $updateFileDataPath);
        } else {
            $result['success'] = false;
            $result['error'] = 'Cannot save data';
            return $result;
        }
        if (isset($dataElement['ProductTemplate'])) {
            $template = json_decode($dataElement['ProductTemplate'], true);
            foreach ($template as $key => $value) {
                switch ($value) {
                    case 'string':
                        $template[$key] = '';
                        break;
                    case 'object':
                        $template[$key] = array();
                        break;
                }
            }
            $this->inventory->saveJson($this->productTemplatePath, $template);
            $this->applyTemplate();
        }
        $result['success'] = true;
        $result['Item'] = $data;
        return $result;
    }
    public function generateCss($setting) {
        $str = '';
        if (isset($setting['CategoryCss']) && is_array($setting['CategoryCss'])) {
            $categories = $setting['CategoryCss'];
            foreach ($categories as $category) {
                $str .= ".row-{$category['category']} {\n";
                $str .= "background-color: {$category['style']['background-color']};\n}\n";
            }
        }
        return $str;
    }

    public function applyTemplate() {
        /*require '../php/retail.php';*/
        $product = new Product();
        $setting = $this->inventory->loadJson($this->adminPath);
        $inventoryFiles = $this->inventory->getList();
        $rs = array_map(function($filename){
            $inv = array(
                'format' => $filename,
                'data' => $this->inventory->loadInventory($filename)
            );
            return $inv;
        }, $inventoryFiles);
        foreach ($rs as &$inventory) {
            foreach ($inventory['data'] as &$itemData) {
                $product->data = $itemData;
                $itemData = $product->getData();
            }
            $this->inventory->saveInventory($inventory['format'], $inventory['data']);
        }
    }
// CREATE NEW ITEMS SEQUENCE IN INVENTORY JSON
    private function createNewObjectFromData($data) {
        $UnwantedWords = isset($data['UnwantedWords']) ? $data['UnwantedWords'] : '';
       	$UnwantedWordsArray = explode(',',$UnwantedWords);
        natsort($UnwantedWordsArray);
        $UnwantedWordsStr = implode(',',$UnwantedWordsArray);

        $RestrictedWords = isset($data['RestrictedWords']) ? $data['RestrictedWords'] : '';
        $RestrictedWordsArray = explode(',',$RestrictedWords);
        natsort($RestrictedWordsArray);
        $RestrictedWordsStr = implode(',',$RestrictedWordsArray);

      /*$SymtomsWords = isset($data['SymtomsWords']) ? $data['SymtomsWords'] : '';
        $SymtomsWordsArray = explode(',',$SymtomsWords);
        natsort($SymtomsWordsArray);
        $SymtomsWordsStr = implode(',',$SymtomsWordsArray);
      */
        $ObjectiveWordsInput = isset($data['ObjectiveWords']) ? json_decode($data['ObjectiveWords']) : array();
        foreach ($ObjectiveWordsInput as $key => $ObjectiveWords) {
            $ObjectiveWordsArray = explode(',',$ObjectiveWords);
            $collectObjectiveWords = array();
            if(is_array($ObjectiveWordsArray) && count($ObjectiveWordsArray)>0) {
                foreach($ObjectiveWordsArray as $ObjectiveWordVal) {
                    $collectObjectiveWords[] = trim($ObjectiveWordVal);
                }
            }
            $collectObjectiveWords2 = $this->array_iunique($collectObjectiveWords);
            natcasesort($collectObjectiveWords2);
            $ObjectiveWordsInput[$key] = implode(', ',$collectObjectiveWords2);
        }

        $object['UnwantedWords'] = $UnwantedWordsStr;
        $object['RestrictedWords'] = $RestrictedWordsStr;
      //$object['SymtomsWordsWords'] = $SymtomsWordsStr;
        $object['ObjectiveWords'] = $ObjectiveWordsInput;
        $object['EbayMaxStock'] = isset($data['EbayMaxStock']) ? $data['EbayMaxStock'] : '';
        $object['usps'] = isset($data['usps']) ? $data['usps'] : '';
        $object['ups'] = isset($data['ups']) ? $data['ups'] : '';
        $object['dhl'] = isset($data['dhl']) ? $data['dhl'] : '';
        $object['fedex'] = isset($data['fedex']) ? $data['fedex'] : '';
        $object['canps'] = isset($data['canps']) ? $data['canps'] : '';
        $object['czkps'] = isset($data['czkps']) ? $data['czkps'] : '';
        $object['Ontrac'] = isset($data['Ontrac']) ? $data['Ontrac'] : '';
        $object['global'] = isset($data['global']) ? $data['global'] : '';
        $object['freight'] = isset($data['freight']) ? $data['freight'] : '';

        return $object;
    }
// UPDATE ITEMS SEQUENCE OF IN THE INVENTORY JSON
    private function updateObjectFromData($data) {
        $inventoryFiles = $this->inventory->getList();
        $categories = array_map(function($filename) {
            $category = $this->inventory->removeExt($filename);
            return $category;
        }, $inventoryFiles);
        $setting_file = $this->dataPath.'admin.json';
        $object = json_decode(file_get_contents($setting_file), true);
        foreach ($categories as $category) {
            if (isset($object[$category]) && isset($data[$category])) {
                $object[$category] = $data[$category];
            }
        }
        $UnwantedWords = isset($data['UnwantedWords']) ? $data['UnwantedWords'] : '';
        $UnwantedWordsArray = explode(',',$UnwantedWords);
        if(is_array($UnwantedWordsArray) && count($UnwantedWordsArray)>0) {
            foreach($UnwantedWordsArray as $UnwantedWordsVal) {
                $collectUnwantedWords[] = trim($UnwantedWordsVal);
            }
        }
        $collectUnwantedWords2 = $this->array_iunique($collectUnwantedWords);
        natcasesort($collectUnwantedWords2);
        $UnwantedWordsStr = implode(', ',$collectUnwantedWords2);

        $RestrictedWords = isset($data['RestrictedWords']) ? $data['RestrictedWords'] : '';
        $RestrictedWordsArray = explode(',',$RestrictedWords);
        $RestrictedWordsArray = array_map(function($e) {
            return trim($e);
        }, $RestrictedWordsArray);
        $RestrictedWordsArray = $this->array_iunique($RestrictedWordsArray);
        natcasesort($RestrictedWordsArray);
        $collectRestrictedWords = array();
        $collectReplacementWords = array();
        $patt = "/\((.*)\)$/";
        $matches = array();
        if(is_array($RestrictedWordsArray) && count($RestrictedWordsArray)>0) {
            foreach($RestrictedWordsArray as $RestrictedWordVal) {
                $restrictedWord = trim($RestrictedWordVal);
                if (preg_match($patt, $restrictedWord, $matches)) {
                    $restrictedWord = str_replace($matches[0], '', $restrictedWord);
                    $replacementWord = $matches[1];
                } else {
                    $replacementWord = '';
                }
                $collectRestrictedWords[] = trim($restrictedWord);
                $collectReplacementWords[] = trim($replacementWord);
            }
        }
        $RestrictedWordsStr = implode(', ',$collectRestrictedWords);


      /*$SymtomsWords = isset($data['SymtomsWords']) ? $data['SymtomsWords'] : '';
        $SymtomsWordsArray = explode(',',$SymtomsWords);
        if(is_array($SymtomsWordsArray) && count($SymtomsWordsArray)>0) {
            foreach($SymtomsWordsArray as $SymtomsWordVal) {
                $collectSymtomsWords[] = trim($SymtomsWordVal);
            }
        }
        $collectSymtomsWords2 = $this->array_iunique($collectSymtomsWords);
        natcasesort($collectSymtomsWords2);
        $SymtomsWordsStr = implode(', ',$collectSymtomsWords2);
      */

        $ObjectiveWordsInput = isset($data['ObjectiveWords']) ? json_decode($data['ObjectiveWords']) : array();
        foreach ($ObjectiveWordsInput as $key => $ObjectiveWords) {
            $collectObjectiveWords = array();
            $ObjectiveWordsArray = explode(',',$ObjectiveWords);
            if(is_array($ObjectiveWordsArray) && count($ObjectiveWordsArray)>0) {
                foreach($ObjectiveWordsArray as $ObjectiveWordVal) {
                    $collectObjectiveWords[] = trim($ObjectiveWordVal);
                }
            }
            $collectObjectiveWords2 = $this->array_iunique($collectObjectiveWords);
            natcasesort($collectObjectiveWords2);
            $ObjectiveWordsInput[$key] = implode(', ',$collectObjectiveWords2);
        }

        $listFields = array('SKUCategory', 'SKUForm', 'SKUType', 'SKUAmazon');
        foreach ($listFields as $field) {
            $collectWord = array();
            $words = $data[$field] ?? '';
            $wordArray = explode(',',$words);
            if(is_array($wordArray) && count($wordArray)>0) {
                foreach($wordArray as $w) {
                    if (strlen(trim($w)))
                        $collectWord[] = trim($w);
                }
            }
            $collectWord2 = $this->array_iunique($collectWord);
            natcasesort($collectWord2);
            $wordStr = implode(', ',$collectWord2);
            $object[$field] = $wordStr;
        }

        if (isset($object['BenefitWord'])) unset($object['BenefitWord']);
        $object['UnwantedWords'] = $UnwantedWordsStr;
        $object['RestrictedWords'] = $RestrictedWordsStr;
        $object['RestrictedProduct'] = isset($data['RestrictedProduct']) ? $data['RestrictedProduct'] : '';
        $object['ReplacementWords'] = implode(', ',$collectReplacementWords);
      //$object['SymtomsWords'] = $SymtomsWordsStr;
        $object['ObjectiveWords'] = $ObjectiveWordsInput;
        $object['EbayMaxStock'] = isset($data['EbayMaxStock']) ? $data['EbayMaxStock'] : '';
        $object['usps'] = isset($data['usps']) ? $data['usps'] : '';
        $object['ups'] = isset($data['ups']) ? $data['ups'] : '';
        $object['dhl'] = isset($data['dhl']) ? $data['dhl'] : '';
        $object['fedex'] = isset($data['fedex']) ? $data['fedex'] : '';
        $object['canps'] = isset($data['canps']) ? $data['canps'] : '';
        $object['czkps'] = isset($data['czkps']) ? $data['czkps'] : '';
        $object['ontrac'] = isset($data['ontrac']) ? $data['ontrac'] : '';
        $object['global'] = isset($data['global']) ? $data['global'] : '';
        $object['freight'] = isset($data['freight']) ? $data['freight'] : '';
        $object['SubCategory'] = isset($data['SubCategory']) ? json_decode($data['SubCategory']) : array();
        $object['PackingFee'] = isset($data['PackingFee']) ? json_decode($data['PackingFee']) : array();
        $object['ShippingFee'] = isset($data['ShippingFee']) ? json_decode($data['ShippingFee']) : array();
        $object['Categories'] = isset($data['Categories']) ? $data['Categories'] : array();
        $object['BodiPromo'] = isset($data['BodiPromo']) ? $data['BodiPromo'] : array();
        $object['PackagingCategories'] = isset($data['PackagingCategories']) ? $data['PackagingCategories'] : array();
        $object['CategoryStoreAccount'] = isset($data['CategoryStoreAccount']) ? json_decode($data['CategoryStoreAccount'], true) : array();
        $object['EqCategories'] = isset($data['EqCategories']) ? json_decode($data['EqCategories']) : array();
        $object['Certificates'] = isset($data['Certificates']) ? $data['Certificates'] : array();
        $object['Coupons'] = isset($data['Coupons']) ? json_decode($data['Coupons']) : array();
        $object['GeneralSetting'] = isset($data['GeneralSetting']) ? json_decode($data['GeneralSetting']) : array();
        $object['InventoryLogTemplate'] = isset($data['InventoryLogTemplate']) ? json_decode($data['InventoryLogTemplate']) : array();
        $object['SpecialtyProducts'] = isset($data['SpecialtyProducts']) ? trim($data['SpecialtyProducts']) : '';

        // $object['Markup'] = isset($data['Markup']) ? $data['Markup'] : array();
        if (!isset($object['Markup']))
            $object['Markup'] = array();
        foreach ($data['Markup'] as $inventory => $markup) {
            if (!isset($object['Markup'][$inventory]))
                $object['Markup'][$inventory] = 0;
            $object['Markup'][$inventory] = $markup;
            if($inventory != 'RetailerMarkup' && $inventory != 'MarkupRetailer' && $inventory != 'MarkupPromo' && $inventory != 'MarkupBodi4Life' && $inventory != 'MarkupBodi4LifePromo' && $inventory != 'MarkupBodiShop' && $inventory != 'MarkupBodiShopPromo' && $inventory != 'MarkupEquineSolution' && $inventory != 'MarkupEquineSolutionPromo')	{
                $this->updateInventoryPrice($inventory);
            }
        }

        $object['CategoryCss'] = isset($data['CategoryCss']) ? json_decode($data['CategoryCss'], true) : array();

        return $object;
    }
    public function updateInventoryPrice($inventory) {
        $products = $this->inventory->loadInventory($inventory);
        if ($products == null)
            return;
        foreach ($products as $i => $product) {
            if (isset($product['Retail']) && is_array($product['Retail'])) {
                foreach ($product['Retail'] as $key => $retail) {
                    if ($retail['Markup'] == -1) {
                        $retail['UploadPrice'] = true;
                        $product['Retail'][$key] = Template::createRetailTemplate($retail);
                    }
                }
                $products[$i] = $product;
            }
        }
        $this->inventory->saveInventory($inventory, $products);
    }
    private function array_iunique($array) {

        /* Sort the array so it's alphabetical and so items beginning in uppercase (like OCRemix, which are usually more precise unless the user goes nuts with capslock) over lowercase ones (ocremix) */
        usort($array, 'strcmp');

        /* We make a reference array that is truly unique (but all lower case) to compare against */

        $finalArray = array(); /* Declare it as blank first, just in case) */
        $referenceArray = array();

        /* Every value has its lower-case equivalent compared to the reference array. If it's not there, it gets added in lowercase form to the reference array and in regular form to the final array. */
        foreach($array as $item) {

        if(!in_array(strtolower($item), $referenceArray)) {
            $finalArray[] = $item;
            $referenceArray[] = strtolower($item);
            }
        }

        return $finalArray;

    }
    public function updateInventoryLog() {
        $result = array('success' => true);
        $setting = $this->inventory->loadJson($this->adminPath);
        if (!isset($setting['InventoryLogTemplate'])) {
            $result['success'] = false;
            $result['err'] = 'InventoryLogTemplate not found';
            return $result;
        }
        $template = $setting['InventoryLogTemplate'];
        //$specialtyProducts = isset($setting['SpecialtyProducts'])?array_map('trim', explode(',', $setting['SpecialtyProducts'])):array();
        $inventories = $this->loadAllInventories();
        $products = array();
        foreach ($inventories as $key => $category) {
            foreach ($category as $product) {
                $arr = array('filename' => $key);
                $pointer1 = &$arr;
                $value = '';
                foreach ($template as $field) {
                    /*if ($field == 'SpecialtyProducts') {
                        if (in_array($product['Product'], $specialtyProducts)) {
                            $arr[$field] = 'Yes';
                        } else {
                            $arr[$field] = '';
                        }
                        continue;
                    }*/
                    if ($field == 'FeaturedProducts') {
                    	$FeaturedProducts = '';
                        if (isset($product['StoreListingASIN']) && is_array($product['StoreListingASIN'])) {
		                    foreach ($product['StoreListingASIN'] as $store => $value) {
		                        if (is_array($value) && count($value)) {
		                        	if(isset($value[1]) && $value[1] == 'Featured') {
										$FeaturedProducts = 'Yes';
									}
		                        }
		                    }
		                }
                        $arr[$field] = $FeaturedProducts;
                        continue;
                    }

                    $pointer2 = $product;
                    $pointer1 = &$arr;
                    if (strpos($field, '.') !== false) {
                        $f = explode('.', $field);
                        $f = array_values(array_filter($f, function($e) {
                            return $e !== '';
                        }));
                        foreach ($f as $i => $k) {
                            if (isset($pointer2[$k])) {
                                $value = $pointer2[$k];
                                $pointer2 = $pointer2[$k];
                                if (!isset($pointer1[$k]))
                                    $pointer1[$k] = array();
                                $pointer1 = &$pointer1[$k];
                                if ($i == count($f)-1)
                                    $pointer1 = $value;
                            } else {
                                $pointer1[$k] = '';
                                break;
                            }
                        }
                    } else {
                        if (isset($product[$field])) {
                            $arr[$field] = $product[$field];
                        } else {
                            $arr[$field] = '';
                        }
                    }
                }
                $activeStores = array();
                if (isset($product['StoreListingASIN']) && is_array($product['StoreListingASIN'])) {
                    foreach ($product['StoreListingASIN'] as $store => $value) {
                        if (is_array($value) &&
                            count($value) &&
                            $value[0] == 'Active'
                        ) {
                            $activeStores[] = $store;
                        }
                    }
                }
                if (count($activeStores)) {
                    $arr['ActiveStatus'] = $activeStores;
                }
                if (count($arr))
                    $products[] = $arr;
            }
        }
        usort($products, function($a, $b) {
            return strcmp($a['Product'], $b['Product']);
        });

        $this->inventory->saveJson($this->InventoryLogPath, $products);
        return $result;
    }
    private function getAmazonTemplatePriceAndQuantity($totalStock, $product, $retail) {
        $cal = new Retail();
        $price = $cal->calculateRetailUniversal($product, $retail, 'bodiretailer');

        $stock = round($cal->calculateStockTotal($product, $retail['RetailUnit'])/$retail['RetailSize']);
        if ($totalStock < 115) {
            if ($retail['RetailSize'] == 4 && $retail['RetailUnit'] == 'oz') {
                $price *= 1;
                $stock = 1;
            } elseif ($retail['RetailSize'] == 1 && $retail['RetailUnit'] == 'lb') {
                $price *= 1;
                $stock = 1;
            } elseif ($retail['RetailSize'] == 5 && $retail['RetailUnit'] == 'lb') {
                $price *= 1;
                $stock = 1;
            }
        } elseif ($totalStock < 454) {
            if ($retail['RetailSize'] == 1 && $retail['RetailUnit'] == 'lb') {
                $price *= 1;
                $stock = 1;
            } elseif ($retail['RetailSize'] == 5 && $retail['RetailUnit'] == 'lb') {
                $price *= 1;
                $stock = 1;
            }
        } elseif ($totalStock <= 2270) {
            if ($retail['RetailSize'] == 5 && $retail['RetailUnit'] == 'lb') {
                $price *= 1;
                $stock = 1;
            }
        }
        return [round($price, 2), $stock];
    }
    public function updateAmazonTemplate() {

        $rs = array(
            'success' => true
        );
        $tbl = array(
            array('sku', 'price', 'minimum-seller-allowed-price', 'maximum-seller-allowed-price', 'quantity', 'handling-time', 'fulfillment-channel')
        );
        try {
            $inventoryCtl = new InventoryCore();
            $except = ['Exclusive', 'Archive', 'Mixture', 'Furnitures', 'Packaging', 'Shipping'];
            $inventories = $inventoryCtl->loadAllInventories($except);
            $cal = new Retail();
            foreach ($inventories as $inventory) {
            	if(isset($inventory['data']) && !empty($inventory['data'])) {
					foreach($inventory['data'] as $product) {
	                    if (isset($product['StoreListingASIN']) &&
	                        isset($product['StoreListingASIN']['amazon']) &&
	                        !empty($product['StoreListingASIN']['amazon'][0])
	                    ) {
                            $product['Format'] = $inventory['format'];
                            $totalStock = round($cal->calculateStockTotal($product, 'gr'), 2);
	                        foreach ($product['Retail'] as $key => $retail) {
	                            if (in_array(strtolower($key), ['recipe', 'bulk', 'delivery'])) continue;
	                            $sku = $this->findAmazonSKU($key);
                                if (CategoryHelper::isHandCraft($product['Format']) !== false) {
                                    $price = $cal->calculateRetailUniversal($product, $retail, 'bodiretailer');
                                    $quantity = 50;
                                } else {
                                    [$price, $quantity] = $this->getAmazonTemplatePriceAndQuantity($totalStock, $product, $retail);
                                }
	                            $tbl[] = array($sku, $price, '', '', $quantity, 1, '');
	                        }
	                    }
	                }
                }
            }
            $txt = implode("\n", array_map(function($row) {
                return implode("\t", $row);
            }, $tbl));
            $inventoryCtl->saveFile('Amazon_Template_Price_Quantity.txt', $txt);
        } catch (Exception $e) {
            $rs['success'] = false;
        }
        return $rs;
    }
    public function findAmazonSKU($sku) {
        if (!isset($this->amazonSkuList)) {
            $setting = $this->inventory->loadJson($this->adminPath);
            $this->amazonSkuList = [];
            if (isset($setting['SKUAmazon'])) {
                $list = explode(', ', $setting['SKUAmazon']);
                $pattern = '/^(.*) \((.*)\)$/';
                foreach ($list as $item) {
                    $match = preg_match($pattern, $item, $matches);
                    if ($match) {
                        $this->amazonSkuList[$matches[2]] = $matches[1];
                    }
                }
            }

        }
        return isset($this->amazonSkuList[$sku]) ? $this->amazonSkuList[$sku] : $sku;
    }
    private function find4digitCustomer($folder) {
        $path = '../retail/'.$folder;
        $inventoryCtl = new InventoryCore();
        $inventoryCtl->path = $path;
        $list = $inventoryCtl->getList();
        $file_arr = array();
        foreach ($list as $filename) {
            $customer = $inventoryCtl->loadJson($inventoryCtl->path.$filename);
            if (isset($customer['Payments']) &&
                isset($customer['Payments'][0]) &&
                !empty($customer['Payments'][0]['CCNumber']) &&
                preg_match("/\d{7,}/", $customer['Payments'][0]['CCNumber'])
            ) {
                $file_arr[] = $folder.$filename." \"{$customer['Payments'][0]['CCNumber']}\"";
            }
        }
        return $file_arr;
    }
    public function exportDecryptCard() {
        $rs = array(
            'success' => true
        );
        try {
            $inventoryCtl = new InventoryCore();
            $file_arr = $this->find4digitCustomer('Bodi4life/');
            $file_arr = array_merge($file_arr, $this->find4digitCustomer('Equine/'));
            if (!count($file_arr)) {
                throw new Exception('No customer found');
            }
            $inventoryCtl->saveFile('decryptcard.txt', implode(PHP_EOL, $file_arr));
        } catch (Exception $e) {
            $rs['success'] = false;
            $rs['error'] = $e->getMessage();
        }
        return $rs;
    }
    public function removeOldSupplierItem() {
        $rs = array(
            'success' => true
        );
        try {
            $inventoryCtl = new InventoryCore();
            $inventories = $inventoryCtl->loadAllInventories();
            $now = new DateTime();
            foreach ($inventories as $key => $inventory) {
                foreach($inventory['data'] as &$product) {
                    if (is_array($product['Suppliers']) && count($product['Suppliers'])) {
                        $suppliers = array_values(array_filter($product['Suppliers'], function($supplier) use ($now) {
                            $date = DateTime::createFromFormat('Y-m-d', $supplier['DateDelivery']);
                            if ($date !== false) {
                                $dateInt = $date->diff($now);
                                $m = $dateInt->format("%r%a")/365;
                                return $m < 2;
                            }
                            return true;
                        }));
                        if (!count($suppliers)) {
                            $suppliers[] = $product['Suppliers'][0];
                        }
                        $product['Suppliers'] = $suppliers;
                    }
                    $inventoryCtl->saveInventory($inventory['format'], $inventory['data']);
                }
            }
        } catch (Exception $e) {
            $rs['success'] = false;
            $rs['error'] = $e->getMessage();
        }
        return $rs;
    }
    public function changeStatusShippedToDelivered() {
    	require_once(__DIR__.'/../retail/order.php');
    	$OrderModel = new Order();
        $rs = array(
            'success' => true
        );
        try {
        	$stores = array('Ebay','Etsy','Amazon');
        	foreach($stores as $store){
				$storePath = '../retail/'.$store.'/';
				$storeData = $this->inventory->loadJson($storePath.'_log.json');
	        	if(!empty($storeData)) {
					foreach($storeData as $row){
						$needChange = false;
						if(!empty($row['OrderStatus'])) {
							foreach($row['OrderStatus'] as $rowOrderDate=>$rowOrderStatus){
								if($rowOrderStatus=='Shipped') {
									$needChange = true;
									break;
								}
							}
						}
						if($needChange) {
							$CustomerID = $row['CustomerID'];
							if(file_exists($storePath.$CustomerID.'.json')){
								$CustomerData = $this->inventory->loadJson($storePath.$CustomerID.'.json');
								if(!empty($CustomerData)) {
									foreach($CustomerData as $CustomerRowKey => $CustomerRow) {
										if(isset($CustomerRow['Order'])) {
											foreach($CustomerRow['Order'] as $CustomerOrderKey => $CustomerOrder) {
												if($CustomerOrder['OrderStatus'] == 'Shipped'){
													$CustomerData[$CustomerRowKey]['Order'][$CustomerOrderKey]['OrderStatus'] = 'Delivered';
												}
											}
										}
									}
								}
								$success = file_put_contents($storePath.$CustomerID.'.json_temp', json_encode($CustomerData, JSON_PRETTY_PRINT));
						        if ($success) {
						            $moveSuccess = rename($storePath.$CustomerID.'.json_temp', $storePath.$CustomerID.'.json');
						        } else {
						            $result['success'] = false;
						            $result['error'] = 'Cannot save data';
						        }
							}
						}
					}
					$option = array('stores' => array($store));
					$result = $OrderModel->updateLog($option);
				}
			}
        } catch (Exception $e) {
            $rs['success'] = false;
            $rs['error'] = $e->getMessage();
        }
        return $rs;
    }
    public function removeBlankOrder() {
    	require_once(__DIR__.'/../retail/order.php');
    	$OrderModel = new Order();
        $rs = array(
            'success' => true
        );
        try {
        	$stores = array('Ebay','Etsy','Amazon','BodiShop');
        	foreach($stores as $store){
				$storePath = '../retail/'.$store.'/';
				$storeData = $this->inventory->loadJson($storePath.'_log.json');
	        	if(!empty($storeData)) {
					foreach($storeData as $row){
						$needChange = false;
						if(!empty($row['OrderStatus'])) {
							foreach($row['OrderStatus'] as $rowOrderDate=>$rowOrderStatus){
								if($rowOrderStatus=='Ordered') {
									$needChange = true;
									break;
								}
							}
						}
						if($needChange) {
							$CustomerID = $row['CustomerID'];
							if(file_exists($storePath.$CustomerID.'.json')){
								$CustomerData = $this->inventory->loadJson($storePath.$CustomerID.'.json');
								if(!empty($CustomerData)) {
									foreach($CustomerData as $CustomerRowKey => $CustomerRow) {
										if(isset($CustomerRow['Order'])) {
											foreach($CustomerRow['Order'] as $CustomerOrderKey => $CustomerOrder) {
												if($CustomerOrder['OrderStatus'] == 'Ordered' && empty($CustomerOrder['OrderItems'])){
													array_splice($CustomerData, $CustomerRowKey, 1);
												}
											}
										}
									}
								}
								if(!empty($CustomerData)) {
									$success = file_put_contents($storePath.$CustomerID.'.json_temp', json_encode($CustomerData, JSON_PRETTY_PRINT));
							        if ($success) {
							            $moveSuccess = rename($storePath.$CustomerID.'.json_temp', $storePath.$CustomerID.'.json');
							        } else {
							            $result['success'] = false;
							            $result['error'] = 'Cannot save data';
							        }
							    }
							    else {
									@unlink($storePath.$CustomerID.'.json');
								}
							}
						}
					}
					$option = array('stores' => array($store));
					$result = $OrderModel->updateLog($option);
				}
			}
        } catch (Exception $e) {
            $rs['success'] = false;
            $rs['error'] = $e->getMessage();
        }
        return $rs;
    }
    public function addCategory($category) {
        $result = array('success' => true);
        $updateFileDataPath = $this->dataPath.'admin.json';
        $object = json_decode(file_get_contents($updateFileDataPath), true);
        if (!isset($object['CategoryCss'])) {
            $object['CategoryCss'] = array();
        }
        $object['CategoryCss'][] = array(
            'category' => $category['category'],
            'style' => $category['style'],
        );
        $SKUCategory = explode(', ', $object['SKUCategory']);
        $SKUCategory[] = "{$category['category']} ({$category['SKUCategory']})";
        $object['SKUCategory'] = implode(', ', $SKUCategory);
        $css = $this->generateCss($object);
        $a = file_put_contents(__DIR__.'/../css/color.css', $css);
        if (!file_exists(__DIR__.'/../inventory/'.$category['category'].'.json')) {
            file_put_contents(__DIR__.'/../inventory/'.$category['category'].'.json', json_encode(array(), JSON_PRETTY_PRINT));
        }
        if (!file_exists(__DIR__.'/../images/'.$category['category'])) {
            mkdir(__DIR__.'/../images/'.$category['category']);
        }
        $success = file_put_contents($updateFileDataPath . '_temp', json_encode($object, JSON_PRETTY_PRINT));
        if ($success) {
            $moveSuccess = rename($updateFileDataPath . '_temp', $updateFileDataPath);
        } else {
            $result['success'] = false;
            $result['error'] = 'Cannot save data';
        }
        return $result;
    }
    function saveHeader($header) {
        $rs['success'] = true;
        $setting = $this->inventory->loadJson($this->headerPath);
        $setting['ProductHeader'] = $header;
        $this->inventory->saveJson($this->headerPath, $setting);
        return $rs;
    }
    function saveHeaderDroplist($page, $header) {
        $rs['success'] = true;
        $setting = $this->inventory->loadJson($this->headerPath);
        $setting['ListHeader'][$page] = $header;
        $this->inventory->saveJson($this->headerPath, $setting);
        return $rs;
    }
    function saveHeaderRetail($page, $header) {
        $rs['success'] = true;
        $setting = $this->inventory->loadJson($this->headerPath);
        $setting['RetailHeader'][$page] = $header;
        $this->inventory->saveJson($this->headerPath, $setting);
        return $rs;
    }
    function getProductWeight($category, $productName) {
        $rs = ['success' => true];
        try {
            $products = $this->inventory->loadInventory($category);
            if ($products == null) {
                throw new Exception("$category not found");
            }
            foreach ($products as $i => $product) {
                if ($product['Product'] == $productName) {
                    if (is_array($product['Retail']) && count($product['Retail'])) {
                        $retail = array_values($product['Retail'])[0];
                        $rs['weight'] = (float)$retail['ShipWeight'];
                        return $rs;
                    }
                }
            }
            throw new Exception("$productName not found");

        } catch (Exception $e) {
            $rs['success'] = false;
            $rs['error'] = $e->getMessage();
            return $rs;
        }
    }
}