<?php

/**
 * Manage Background Things to change
 *
 * PHP version 5.6
 *
 * @category  Backgrounds
 * @package   Assets
 * @author    Satyabrata <satyabratap@riaxex.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */

namespace App\Modules\Backgrounds\Controllers;

use App\Components\Controllers\Component as ParentController;
use App\Modules\Backgrounds\Models\Background;
use App\Modules\Backgrounds\Models\BackgroundCategory as Category;
use App\Modules\Backgrounds\Models\BackgroundCategoryRelation;
use App\Modules\Backgrounds\Models\BackgroundTagRelation;
use Illuminate\Database\Capsule\Manager as DB;
use App\Modules\PrintProfiles\Models as PrintProfileModels;
use App\Modules\PrintProfiles\Models\PrintProfileAssetsCategoryRel;

/**
 * Backgrounds Controller
 *
 * @category Backgrounds
 * @package  Assets
 * @author   Satyabrata <satyabratap@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */

class BackgroundController extends ParentController
{
    /**
     * POST: Save Background
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author satyabratap@riaxe.com
     * @date   4th Nov 2019
     * @return json response wheather data is saved or any error occured
     */
    public function saveBackgrounds($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Backgrounds', 'error')
        ];
        try {
            // Get Store Specific Details from helper
            $getStoreDetails = get_store_details($request);
            $allPostPutVars = $request->getParsedBody();
            $catIdArr = !empty($allPostPutVars['categories']) ? json_clean_decode($allPostPutVars['categories'], true) : [];
            $allFileNames = $saveBackgroundList = $recordBackgroundIds = [];
            $uploadingFilesNo = $success = 0;
            $isS3Enabled = $this->checkS3Settings($getStoreDetails['store_id']);
            if (empty($allPostPutVars['name'])) {
                $jsonResponse['message'] = 'Name should not be empty!';
            } elseif ($allPostPutVars['type'] == 1 && !$request->getUploadedFiles()) {
                $jsonResponse['message'] = 'File Required!';
            } elseif ($allPostPutVars['type'] == 0 && empty($allPostPutVars['upload'])) {
                $jsonResponse['message'] = 'Color code Required!';
            } elseif (!$catIdArr) {
                $jsonResponse['message'] = "Please select category";
            } else {
                // type = 1 : with file as background and check if any file received
                if ($allPostPutVars['type'] == 1) {
                    // Save file
                    $allFileNames = do_upload('upload', path('abs', 'background'), [150], 'array');
                    if (empty($allFileNames)) {
                        throw new \Exception('File upload error');
                    }
                    if (is_string($allFileNames) && $allFileNames == "limit_error") {
                        throw new \Exception('The upload limit is exceeded');
                    }
                    // remove blank value : skipped emptycheck in the loop
                    $allFileNames = array_filter($allFileNames);
                    // number of uploaded files
                    $uploadingFilesNo = count($allFileNames);

                    foreach ($allFileNames as $eachFile) {
                        $saveBackgroundList = [
                            'store_id' => $getStoreDetails['store_id'],
                            'name' => $allPostPutVars['name'],
                            'price' => $allPostPutVars['price'],
                            'type' => $allPostPutVars['type'],
                            'value' => $eachFile,
                            'cloud_storage' => 0
                        ];
                        if ($isS3Enabled) {
                            $thumbnailFile = "thumb_" . $eachFile;
                            $backgroundFile = path('abs', 'background') . $eachFile;
                            $thumbUpload =  path('abs', 'background') . $thumbnailFile;
                            $this->uploadFileToS3("background", $thumbUpload, $getStoreDetails['store_id']);
                            $this->uploadFileToS3("background", $backgroundFile, $getStoreDetails['store_id']);
                            $saveBackgroundList['cloud_storage'] = 1;
                        }
                        $saveEachBackground = new Background($saveBackgroundList);
                        if ($saveEachBackground->save()) {
                            $backgroundLastId = $saveEachBackground->xe_id;
                            $recordBackgroundIds[] = $backgroundLastId;
                            /**
                             * Save category and subcategory data
                             * Category id format. [4,78,3]
                             */
                            // Save Background Categories
                            $this->saveBackgroundCategories($backgroundLastId, $catIdArr);
                            /**
                             * - Save tags with respect to the Backgrounds
                             * - Tag Names format.: tag1,tag2,tag3
                             */
                            if (!empty($allPostPutVars['tags'])) {
                                $tags = $allPostPutVars['tags'];
                                $this->saveBgTags(
                                    $getStoreDetails['store_id'],
                                    $backgroundLastId,
                                    $tags
                                );
                            }
                            $success++;
                        }
                    }
                } else {
                    $allPostPutVars += [
                        'value' => $allPostPutVars['upload'],
                        'store_id' => $getStoreDetails['store_id']
                    ];
                    $saveBackgroundColor = new Background($allPostPutVars);
                    if ($saveBackgroundColor->save()) {
                        $backgroundLastId = $saveBackgroundColor->xe_id;
                        /**
                         * Save category and subcategory
                         * Category id format: [4,78,3]
                         */
                        // Save Background Categories
                        $this->saveBackgroundCategories($backgroundLastId, $catIdArr);
                        /**
                         * - Save tags
                         * - Tag Names format: tag1,tag2,tag3
                         */
                        if (isset($allPostPutVars['tags']) && $allPostPutVars['tags'] != "") {
                            $tags = $allPostPutVars['tags'];
                            $this->saveBgTags(
                                $getStoreDetails['store_id'],
                                $backgroundLastId,
                                $tags
                            );
                        }
                        $success++;
                        $uploadingFilesNo = 1;
                    }
                }
                // delete the memcache
                $this->memcache('deleteMulti', '', '', "backgrounds_cat");
                // build the mem cache
                $assetTypeArr = $this->assetsTypeId('backgrounds');
                $ppAssetCatRelGtInit = new PrintProfileModels\PrintProfileAssetsCategoryRel();
                $ppAssetCatRelQuery = $ppAssetCatRelGtInit->select('print_profile_id')->distinct()->where('asset_type_id', '=', $assetTypeArr['asset_type_id'])
                ->whereIn('category_id', $catIdArr);
                if ($ppAssetCatRelQuery->exists()) {
                    $printProfileIds = $ppAssetCatRelQuery->get()->pluck('print_profile_id');
                    $this->createUpdateAssetJsonCache($getStoreDetails['store_id'], $printProfileIds, 'backgrounds', $request, $response);
                }
            }

            if (!empty($success)) {
                $jsonResponse = [
                    'status' => 1,
                    'message' => $success . ' out of ' . $uploadingFilesNo . ' Background(s) uploaded successfully'
                ];
            }
        } catch (\Exception $e) {
            // Store exception in logs
            create_log('Assets', 'error', [
                'message' => $e->getMessage(),
                'extra' => [
                    'module' => 'Backgrounds'
                ]
            ]);
        }
        // Flush background memcached
        $this->memcache('deleteMulti', '', '', 'background');
        return response($response, [
            'data' => $jsonResponse, 'status' => $serverStatusCode
        ]);
    }

    /**
     * Save Categories/Sub-categories w.r.t Background
     *
     * @param $backgroundId Background ID
     * @param $categoryIds  (in  an array with comma separated)
     *
     * @author satyabratap@riaxe.com
     * @date   4th Nov 2019
     * @return boolean
     */
    protected function saveBackgroundCategories($backgroundId, $getAllCategoryArr)
    {
        $assetTypeArr = $this->assetsTypeId('backgrounds');
        # update asset_available_flag for background categories
        Category::where('asset_type_id', '=', $assetTypeArr['asset_type_id'])
        ->whereIn('xe_id', $getAllCategoryArr)
        ->update(['asset_available_flag' => 1]);

        // SYNC Categories to the Background_Category Relationship Table
        $backgroundInit = new Background();
        $findBackground = $backgroundInit->find($backgroundId);
        if ($findBackground->categories()->sync($getAllCategoryArr)) {
            return true;
        }
        return false;
    }

    /**
     * Save tags w.r.t Background
     *
     * @param $storeId      Store Id
     * @param $backgroundId Background ID
     * @param $tags         Multiple Tags
     *
     * @author satyabratap@riaxe.com
     * @author tanmayap@riaxe.com
     * @date   4th Nov 2019
     * @return boolean
     */
    protected function saveBgTags($storeId, $backgroundId, $tags)
    {
        // Save Backgrounds and tags relation
        if (!empty($tags)) {
            $getTagIds = $this->saveTags($storeId, $tags);
            // SYNC Tags into Backgrounds Tag Relationship Table
            $backgroundInit = new Background();
            $findBackground = $backgroundInit->find($backgroundId);
            if ($findBackground->tags()->sync($getTagIds)) {
                return true;
            }
        } else {
            // Clean relation in case no tags supplied
            $tagRelInit = new BackgroundTagRelation();
            $backgroundTags = $tagRelInit->where('background_id', $backgroundId);
            if ($backgroundTags->delete()) {
                return true;
            }
        }

        return false;
    }

    /**
     * GET: Single Background
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author dan@imprintnext.com
     * @date   19 July 2022
     * @return Single Background
     */
    public function getSingleBackground($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 1,
            'data' => [],
            'message' => message('Background', 'not_found')
        ];

        $getStoreDetails = get_store_details($request);
        $backgroundId = to_int($args['id']);


        if (!empty($backgroundId)) {
            $backgroundInit = new Background();
            // get single background matching with the id
            $getBackgrounds = $backgroundInit->where([
                ['xe_id', '>', 0],
                ['store_id', '=', $getStoreDetails['store_id']],
                ['xe_id', '=', $backgroundId]
            ])->select([
                'xe_id', 'name', 'value', 'price', 'type', 'cloud_storage'
            ]);

            // remove the unused appends (category_names) and get the data
            $backgroundData = $getBackgrounds->first()->setAppends(['thumbnail'])->toArray();

            // get the file / thumbnail
            if ($backgroundData['cloud_storage'] == 1) {
                $fileName =  $this->getS3URL($backgroundData['value'], $getStoreDetails['store_id']);
                $thumbnail = $this->getS3URL($backgroundData['thumbnail'], $getStoreDetails['store_id']);
                $backgroundData['value'] = $fileName;
                $backgroundData['thumbnail'] = $thumbnail;
            }

            // Get Category Ids
            if (!empty($backgroundData)) {
                $getCategories = $this->getCategoriesById(
                    'Backgrounds',
                    'BackgroundCategoryRelation',
                    'background_id',
                    $backgroundId
                );
                $getTags = $this->getTagsById(
                    'Backgrounds',
                    'BackgroundTagRelation',
                    'background_id',
                    $backgroundId
                );
                $backgroundData['categories'] = !empty($getCategories)
                    ? $getCategories : [];
                $backgroundData['tags'] = !empty($getTags) ? $getTags : [];
            }

            $jsonResponse = [
                'status' => 1,
                'records' => 1,
                'data' => [$backgroundData]
            ];
        }
        return response(
            $response,
            ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET: List of Backgrounds
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author satyabratap@riaxe.com
     * @date   4th Nov 2019
     * @return All Background List
     */
    public function getBackgrounds($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 1,
            'data' => [],
            'message' => message('Background', 'not_found')
        ];
        $getStoreDetails = get_store_details($request);
        $storeId = $getStoreDetails['store_id'];
        // Collect all Filter columns from url
        $categoryId = $request->getQueryParam('category') ?
        json_clean_decode($request->getQueryParam('category'), true) : [];
        $sortBy = $request->getQueryParam('sortby');
        $order = $request->getQueryParam('order');
        $name = $request->getQueryParam('name');
        $type = $request->getQueryParam('type');
        $printProfileKey = $request->getQueryParam('print_profile_id');
        $page = ($request->getQueryParam('page') != '') ? $request->getQueryParam('page') : 1;
        $perpage = ($request->getQueryParam('perpage') != '') ? $request->getQueryParam('perpage') : 10;

        //GET MEMCACHEDATA
        $memcacheData = [];
        if (IS_MEMCACHE && empty($name) && !empty($printProfileKey)) {
            //MEMCACHED KEY
            $thisCacheKey = "background" . "_page" . $page . "_order" . $order . "_perpage" . $perpage . "_pp" . $printProfileKey . "_s" . $storeId . "_type" . $type;

            //Register MEMCACHED KEY in Local Cache
            $this->createUpdateMemCacheGroup('background', $thisCacheKey, 'SET');

            $memcacheData = $this->memcache("get", $thisCacheKey);
        }
        if (!empty($memcacheData)) {
            if (MEM_MODE) {
                $memcacheData['mode'] = 'memcache';
            }
            return response($response, [
                'data' => $memcacheData, 'status' => $serverStatusCode
            ]);
        }

        $backgroundInit = new Background();
        $getBackgrounds = $backgroundInit->where([
            ['xe_id', '>', 0],
            ['store_id', '=', $getStoreDetails['store_id']]
        ]);
        
        // Proceed if record exists on the table
        if ($getBackgrounds->exists()) {
            // For multiple Background data
            $getBackgrounds->select([
                'xe_id', 'name', 'value', 'price', 'type', 'cloud_storage'
            ]);

            // Filter Search as per type
            if (isset($type) && $type != "") {
                $getBackgrounds->where(function ($query) use ($type) {
                    $query->where('type', $type);
                });
            }

            // Multiple Table search for name attribute
            if (isset($name) && $name != "") {
                $getBackgrounds->where(function ($query) use ($name) {
                    $query->where('name', 'LIKE', '%' . $name . '%')
                        ->orWhereExists(function ($q) use ($name) {
                            $q->select(DB::raw(1))->from('background_tag_rel as btr')->join('tags as tg', 'btr.tag_id', '=', 'tg.xe_id')
                            ->whereRaw('btr.background_id = backgrounds.xe_id')
                            ->where('tg.name', '=', $name);
                        });
                });
            }

            // Filter By Print Profile's category Id
            if (!empty($printProfileKey)) {
                $profileCatRelObj = new \App\Modules\PrintProfiles\Models\PrintProfileAssetsCategoryRel();
                $assetTypeArr = $this->assetsTypeId('backgrounds');
                $profileCatRelDetails = $profileCatRelObj->where([
                    ['asset_type_id', '=', $assetTypeArr['asset_type_id']],
                    ['print_profile_id', '=', $printProfileKey]
                ]);
                // get the print profile category ids
                $profileCatIds = $profileCatRelDetails->get()->pluck('category_id')->toArray();
                if ($profileCatIds) {
                    $categoryId = array_merge($categoryId, $profileCatIds);
                }
            }
            
            // Filter by Category ID
            if (!empty($categoryId)) {
                $getBackgrounds->whereHas('backgroundCategory', function ($q) use ($categoryId) {
                    return $q->whereIn('category_id', $categoryId);
                });
            }

            // Total records including all filters
            $getTotalPerFilters = $getBackgrounds->count();

            // Get pagination data
            if (isset($page) && $page != "") {
                $totalItem = empty($perpage) ? PAGINATION_MAX_ROW : $perpage;
                $offset = $totalItem * ($page - 1);
                $getBackgrounds->skip($offset)->take($totalItem);
            }
            // Sorting by column name and sord order parameter
            if (!empty($sortBy) && !empty($order)) {
                $getBackgrounds->orderBy($sortBy, $order);
            }

            $backgroundData = $getBackgrounds->get()->toArray();
            foreach ($backgroundData as $key => $value) {
                if ($value['cloud_storage'] == 1) {
                    $thisFileName = $value['value'];
                    $thisThumbnail = $value['thumbnail'];
                    $backgroundData[$key]['value'] =  $this->getS3URL($thisFileName, $getStoreDetails['store_id']);
                    $backgroundData[$key]['thumbnail'] = $this->getS3URL($thisThumbnail, $getStoreDetails['store_id']);
                }
            }

            $jsonResponse = [
                'status' => 1,
                'records' => count($backgroundData),
                'total_records' => $getTotalPerFilters,
                'data' => $backgroundData
            ];
            if (IS_MEMCACHE && empty($name) && isset($thisCacheKey)) {
                $this->memcache("set", $thisCacheKey, $jsonResponse);
            }
        }
        return response($response, [
            'data' => $jsonResponse, 'status' => $serverStatusCode
        ]);
    }

    /**
     * PUT: Update a single background
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author satyabratap@riaxe.com
     * @date   4th Nov 2019
     * @return json response wheather data is updated or not
     */
    public function updateBackground($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Background', 'error'),
        ];
        try {
            $getStoreDetails = get_store_details($request);
            $storeId = $getStoreDetails['store_id'];
            $allPostPutVars = $updateData = $request->getParsedBody();
            $catIdArr = !empty($allPostPutVars['categories']) ? json_clean_decode($allPostPutVars['categories'], true) : [];
            $backgroundId = to_int($args['id']);
            $getOldBG = false;
            $backgroundInit = new Background();
            if (!empty($backgroundId)) {
                $getOldBG = $backgroundInit->setAppends(['thumbnail', 'category_id'])->where('xe_id', $backgroundId)->get()->first()->toArray();
            }

            if (!$getOldBG) {
                $jsonResponse['message'] = 'Background not found!';
            } elseif (empty($allPostPutVars['name'])) {
                $jsonResponse['message'] = 'Name should not be empty!';
            } elseif (empty($catIdArr)) {
                $jsonResponse['message'] = "Please select category";
            } else {
                $oldCategoryArr = explode(",", $getOldBG['category_id']);
                $deletableBgCatRels = array_diff($oldCategoryArr, $catIdArr);
                // get all deletable rel category id with relcounts
                $bgCatRelInit = new BackgroundCategoryRelation();
                $bgRelCatsQuery = $bgCatRelInit->select(['category_id', DB::raw('COUNT(category_id) as rel_count')])
                ->whereIn('category_id', $deletableBgCatRels)
                ->groupBy('category_id');
                $bgRelCats = $bgRelCatsQuery->get()->toArray();
                // update the asset_available_flag based on rel count value (>1 = 1, <=1 = 0 )
                if (!empty($bgRelCats)){
                    // devide the cat_ids based on single_cats, multi_cats rels counts
                    $groupedCats = array_reduce($bgRelCats, function ($accumulator, $termValue) {
                            if (empty($termValue['rel_count']) || $termValue['rel_count'] <= 1) {
                                $accumulator['single_cats'][] = $termValue['category_id'];
                            } else {
                                $accumulator['multi_cats'][] = $termValue['category_id'];
                            }
                            return $accumulator;
                        },
                        ['single_cats' => [], 'multi_cats' => []]
                    );
                    if(!empty($groupedCats['single_cats'])) {
                        Category::whereIn('xe_id', $groupedCats['single_cats'])->update(['asset_available_flag' => 0]);
                    }
                    if(!empty($groupedCats['multi_cats'])) {
                        Category::whereIn('xe_id', $groupedCats['multi_cats'])->update(['asset_available_flag' => 1]);
                    }
                }

                unset(
                    $updateData['id'],
                    $updateData['tags'],
                    $updateData['categories'],
                    $updateData['upload'],
                    $updateData['value'],
                    $updateData['backgroundId']
                );

                if (isset($updateData['type']) && $updateData['type'] == 0 && !empty($allPostPutVars['upload'])) {
                    $updateData['value'] = $allPostPutVars['upload'];
                } else {
                    if ($request->getUploadedFiles()) {
                        $getUploadedFileName = do_upload(
                            'upload',
                            path('abs', 'background'),
                            [100],
                            'string'
                        );
                        if ($getOldBG['cloud_storage'] == 1) {
                            $updateData['cloud_storage'] = 1;
                            $thumbUpload = path('abs', 'background') . "thumb_" . $getUploadedFileName;
                            $fileToUpload = path('abs', 'background') . $getUploadedFileName;
                            $this->uploadFileToS3("background", $fileToUpload, $storeId);
                            $this->uploadFileToS3("background", $thumbUpload, $storeId);
                        }
                        $updateData['value'] = $getUploadedFileName;
                    }
                }
                if (
                    $getOldBG['type'] == 1 && ((isset($updateData['type']) && $updateData['type'] == 0) || !empty($getUploadedFileName))
                ) {
                    if ($getOldBG['cloud_starage'] == 1) {
                        $this->deleteS3File($getOldBG['value'], $storeId);
                        $this->deleteS3File($getOldBG['thumbnail'], $storeId);
                    } else {
                        // Delete old file
                        $this->deleteOldFile(
                            "backgrounds",
                            "value",
                            ['xe_id' => $backgroundId],
                            path('abs', 'background'),
                            false
                        );
                    }
                }
                $updateData['store_id'] = $storeId;

                // Update record
                $backgroundInit->where('xe_id', '=', $backgroundId)->update($updateData);
                // Save category
                $this->saveBackgroundCategories($backgroundId, $catIdArr);

                // Save tags
                $tags = !empty($allPostPutVars['tags']) ? $allPostPutVars['tags'] : "";
                $this->saveBgTags($storeId, $backgroundId, $tags);

                // clear the memcache
                $this->memcache('deleteMulti', '', '', "backgrounds_cat");
                // build the memcache
                $assetTypeArr = $this->assetsTypeId('backgrounds');
                $ppAssetCatRelGtInit = new PrintProfileModels\PrintProfileAssetsCategoryRel();
                $ppAssetCatRelQuery = $ppAssetCatRelGtInit->select('print_profile_id')->distinct()
                ->where('asset_type_id', '=', $assetTypeArr['asset_type_id'])
                ->whereIn('category_id', $catIdArr);
                if ($ppAssetCatRelQuery->exists()) {
                    $printProfileIds = $ppAssetCatRelQuery->get()->pluck('print_profile_id');
                    $this->createUpdateAssetJsonCache($getStoreDetails['store_id'], $printProfileIds, 'backgrounds', $request, $response);
                }
                
                $jsonResponse = [
                    'status' => 1,
                    'message' => message('Background', 'updated')
                ];
                
            }
        } catch (\Exception $e) {
            // Store exception in logs
            create_log('Assets', 'error', [
                'message' => $e->getMessage(),
                'extra' => [
                    'module' => 'Backgrounds'
                ]
            ]);
        }
        // Flush background memcached
        $this->memcache('deleteMulti', '', '', 'background');
        return response($response, [
            'data' => $jsonResponse, 'status' => $serverStatusCode
        ]);
    }

    /**
     * DELETE: Delete single/multiple background
     *
     * @param $request  Slim's Argument parameters
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author satyabratap@riaxe.com
     * @date   4th Nov 2019
     * @return json response wheather data is deleted or not
     */
    public function deleteBackground($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Background', 'error'),
        ];
        try {
            // get the store id
            $getStoreDetails = get_store_details($request);
            $storeId = $getStoreDetails['store_id'];
            // deletable ids
            $getDeleteIdsToArray = !empty($args['id']) ? json_clean_decode($args['id'], true) : [];

            if ($getDeleteIdsToArray) {
                // total number of requested for delete
                $totalCount = count($getDeleteIdsToArray);
                // get the backgrounds
                $backgroundInit = new Background();
                $backgrounds = $backgroundInit->whereIn('xe_id', $getDeleteIdsToArray);
                // go through and delete files + background
                if ($backgrounds->exists()) {
                    $getBackgroundDetails = $backgrounds->get()->toArray();
                    $success = 0; // total success delete
                    foreach ($getBackgroundDetails as $bg) {
                        $deletableBgCatRels = explode(",", $bg['category_id']);
                        
                        $bgCatRelInit = new BackgroundCategoryRelation();
                        $bgRelCatsQuery = $bgCatRelInit->select(['category_id', DB::raw('COUNT(category_id) as rel_count')])
                        ->whereIn('category_id', $deletableBgCatRels)
                        ->groupBy('category_id');
                        $bgRelCats = $bgRelCatsQuery->get()->toArray();
                        // update the asset_available_flag based on rel count value (>1 = 1, <=1 = 0 )
                        if (!empty($bgRelCats)) {
                            // devide the cat_ids based on single_cats, multi_cats rels counts
                            $groupedCats = array_reduce($bgRelCats, function ($accumulator, $termValue) {
                                    if (empty($termValue['rel_count']) || $termValue['rel_count'] <= 1) {
                                        $accumulator['single_cats'][] = $termValue['category_id'];
                                    } else {
                                        $accumulator['multi_cats'][] = $termValue['category_id'];
                                    }
                                    return $accumulator;
                                },
                                ['single_cats' => [], 'multi_cats' => []]
                            );
                            if(!empty($groupedCats['single_cats'])) {
                                Category::whereIn('xe_id', $groupedCats['single_cats'])->update(['asset_available_flag' => 0]);
                            }
                            if(!empty($groupedCats['multi_cats'])) {
                                Category::whereIn('xe_id', $groupedCats['multi_cats'])->update(['asset_available_flag' => 1]);
                            }
                        }
                        
                        if ($bg['type'] == 1) {
                            if ($bg['cloud_storage'] == 1) {
                                $fileName = $bg['value'];
                                $thumbnail = $bg['thumbnail'];
                                $this->deleteS3File($fileName, $storeId);
                                $this->deleteS3File($thumbnail, $storeId);
                            } else {
                                $this->deleteOldFile(
                                    "backgrounds",
                                    "value",
                                    ['xe_id' => $bg['xe_id']],
                                    path('abs', 'background'),
                                    false
                                );
                            }
                        }
                        $bgCatRelInit->where('background_id', $bg['xe_id'])->delete();
                        $backgroundInit->where('xe_id', $bg['xe_id'])->delete();
                        $success++;
                    }
                    // delete the memcache
                    $this->memcache('deleteMulti', '', '', "backgrounds_cat");

                    // get categories of all deleted background
                    $bgCatRelInit = new BackgroundCategoryRelation();
                    $allBgId = array_column($getBackgroundDetails, 'xe_id');
                    $bgRelCatsQuery = $bgCatRelInit->select('category_id')->distinct()->whereIn('background_id', $allBgId);
                    // build the mem cache
                    $assetTypeArr = $this->assetsTypeId('backgrounds');
                    $ppAssetCatRelGtInit = new PrintProfileModels\PrintProfileAssetsCategoryRel();
                    $ppAssetCatRelQuery = $ppAssetCatRelGtInit->select('print_profile_id')->where('asset_type_id', '=', $assetTypeArr['asset_type_id'])
                    ->whereIn('category_id', $bgRelCatsQuery);
                    if ($ppAssetCatRelQuery->exists()) {
                        $printProfileIds = $ppAssetCatRelQuery->distinct()->get()->pluck('print_profile_id');
                        $this->createUpdateAssetJsonCache($getStoreDetails['store_id'], $printProfileIds, 'backgrounds', $request, $response);
                    }

                    if ($success > 0) {
                        $jsonResponse = [
                            'status' => 1,
                            'message' => $success . ' out of ' . $totalCount . ' Background(s) deleted successfully'
                        ];
                    }
                }
            }
        } catch (\Exception $e) {
            // Store exception in logs
            create_log('Assets', 'error', [
                'message' => $e->getMessage(),
                'extra' => [
                    'module' => 'Backgrounds'
                ]
            ]);
        }
        // Flush background memcached
        $this->memcache('deleteMulti', '', '', 'background');
        return response($response, [
            'data' => $jsonResponse, 'status' => $serverStatusCode
        ]);
    }

    /**
     * Delete a category from the table
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author satyabratap@riaxe.com
     * @date   20 Jan 2020 Satyabrata
     * @return Delete Json Status
     */
    public function deleteCategory($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $getStoreDetails = get_store_details($request);
        $storeId = $getStoreDetails['store_id'];
        $jsonResponse = [
            'status' => 0,
            'message' => message('Category', 'error')
        ];
        if (!empty($args['id'])) {
            $categoryId = $args['id'];
            $jsonResponse = $this->deleteCat(
                $storeId,
                'backgrounds',
                $categoryId,
                'Backgrounds',
                'BackgroundCategoryRelation'
            );
        }
        $this->memcache('deleteMulti', '', '', "backgrounds_cat");
        if (!empty($args['id'])) {
            $ppAssetCatRelGtInit = new PrintProfileModels\PrintProfileAssetsCategoryRel();
            $printProfileIds = $ppAssetCatRelGtInit->where('category_id', $args['id'])->pluck('print_profile_id');
            $this->createUpdateAssetJsonCache($getStoreDetails['store_id'], $printProfileIds, "backgrounds", $request, $response);
        }
        return response($response, [
            'data' => $jsonResponse, 'status' => $serverStatusCode
        ]);
    }
}
