<?php

/**
 * Manage Color Swatches
 *
 * PHP version 5.6
 *
 * @category  Settings
 * @package   Eloquent
 * @author    Sanjeeb Dakhinaray <steve@imprintnext.com>
 * @copyright 2021-2022 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\Artwork\Controllers;

use App\Components\Controllers\Component as ParentController;
use App\Modules\Orders\Controllers\OrderDownloadController;
use App\Dependencies\Zipper as Zipper;
use App\Modules\Artwork\Models\SalesChannelArtwork;
use Illuminate\Database\Capsule\Manager as DB;

class ArtworkController extends ParentController
{
    public $dpi = 72;

    /**
     * Get All Artwork
     *
     * @param $request Slim Request
     * @param $response  Slim Response
     *
     * @author steve@imprintnext.com
     * @date   19 May 2022
     * @return json
     */
    public function getAllArtwork($request, $response)
    {

        $getStoreDetails = get_store_details($request);
        $storeId = $getStoreDetails['store_id'];
        $isS3Enabled = $this->checkS3Settings($storeId);

        $name = $request->getQueryParam('name') ? $request->getQueryParam('name') : '';
        $orderby = $request->getQueryParam('orderby') ? $request->getQueryParam('orderby') : 'desc';
        $page = $request->getQueryParam('page') ? $request->getQueryParam('page') : 1;
        $perPage = $request->getQueryParam('perpage') ? $request->getQueryParam('perpage') : 10;
        if ($page == 1) {
            $startLimit = 0;
        } else {
            $startLimit = ($page - 1) * $perPage;
        }
        $allArtworkSql = DB::table('sales_channel_artwork')->select("*")
            ->Join('sales_channel_artwork_relation', 'sales_channel_artwork_relation.artwork_id', '=', 'sales_channel_artwork.xe_id')
            ->Join('sales_channel', 'sales_channel.xe_id', '=', 'sales_channel_artwork_relation.sales_channel_id')
            ->orWhere('sales_channel.channel_name', 'like', $name . "%")
            ->orWhere('sales_channel_artwork.sku', 'like', $name . "%")->groupBy('sales_channel_artwork_relation.artwork_id');
        $totalRecords = sizeof($allArtworkSql->get()->toArray());
        $allArtwork = $allArtworkSql->orderBy('sales_channel_artwork_relation.artwork_id', $orderby)->offset($startLimit)->limit($perPage)->get()->toArray();
        $jsonResponse = [];
        foreach ($allArtwork as $key => $value) {
            $serverStatusCode = OPERATION_OKAY;
            $getFormValues = DB::table('sales_channel_artwork_relation')
                ->Join('sales_channel', 'sales_channel_artwork_relation.sales_channel_id', '=', 'sales_channel.xe_id')
                ->where('sales_channel_artwork_relation.artwork_id', '=', $value->artwork_id)
                ->get()->toArray();
            $salesChannel = [];
            foreach ($getFormValues as $salesvalue) {
                if (!in_array($salesvalue->channel_name, $salesChannel)) {
                    array_push($salesChannel, $salesvalue->channel_name);
                }
            }

            $salesChannel = implode(",", $salesChannel);
            $jsonResponse[$key]['sales_channel'] =  $salesChannel;
            $ref_id = $value->ref_id;
            $downloadKey =  base64_encode("IMP-" . $ref_id);
            $jsonPath = ASSETS_PATH_W . "design_states/templates/" . $ref_id . ".json";
            $jsonValue = file_get_contents($jsonPath);
            $jsonData = json_clean_decode($jsonValue, true);

            $previewImage = $jsonData['design_product_data'][0]['design_urls'][0];
            $imagePath = explode("templates", $previewImage);
            $fileLocationDir = path('abs', 'design_preview') . 'templates' . $imagePath[1];

            if (!file_exists($fileLocationDir) && $isS3Enabled) {
                $previewImage = $this->getS3URL($previewImage, $storeId);
            }

            $jsonResponse[$key]['artwork_id'] = $salesvalue->artwork_id;
            $jsonResponse[$key]['ref_id'] = $ref_id;
            $jsonResponse[$key]['download_key'] = $downloadKey;
            $jsonResponse[$key]['used_colors'] =  $jsonData['sides'][0]['print_area']['bound_0']['used_colors'];
            $jsonResponse[$key]['preview_image'] = $previewImage;
            $jsonResponse[$key]['sku'] = $value->sku;
        }
        $jsonResponse = [
            'data' => $jsonResponse,
            'records' => sizeof($jsonResponse),
            'total_records' => $totalRecords,
            'status' => 1
        ];
        return response(
            $response,
            ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * save Marketplace artwork
     *
     * @param $request Slim Request
     * @param $response  Slim Response
     *
     * @author steve@imprintnext.com
     * @date   19 May 2022
     * @return json
     */
    public function saveMarketPlaceArtwork($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $allPostPutVars = $request->getParsedBody();
        // Initilize json Response
        $jsonResponse = [
            'status' => 0,
            'message' => message('Design Data', 'error'),
        ];
        $reffId = $allPostPutVars['ref_id'];
        $sku =  base64_encode("IMP-" . $reffId);
        $artworkData['ref_id'] = $reffId;
        $artworkData['sku'] = $sku;
        $getAssocCaptures = $this->getCaptureImages($request, $reffId);

        $artworkObj = new SalesChannelArtwork($artworkData);
        $checkRecord = $artworkObj->where(['ref_id' => $reffId, 'sku' => $sku]);

        if ($checkRecord->count() > 0) {
            $recordData = $checkRecord->first()->toArray();
            $artworkId = $recordData['xe_id'];
        } else {
            $artworkObj->save();
            $artworkId = $artworkObj->xe_id;
            $this->getArtworkPrintFiles($request, $reffId, 'create');
        }
        $jsonResponse = [
            'status' => 1,
            'ref_id' => $reffId,
            'artwork_id' => $artworkId,
            'sku' => $sku,
            'capture_images' => $getAssocCaptures,
            'message' => message('Design Template', 'saved'),
        ];
        return response(
            $response,
            ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }


    /**
     * Get SVG Files json data associated to the Template's Ref ID
     *
     * @param $refId Custom Design Id
     * @param $type  Type of the design
     *
     * @author tanmayap@riaxe.com
     * @date   19 Feb 2020
     * @return Array
     */
    public function getSVGFile($refId, $type)
    {
        $svgDataArray = [];
        $svgJsonPath = path('abs', 'design_state') . $type;
        $svgJsonPath .= '/' . $refId . '.json';
        if (file_exists($svgJsonPath)) {
            $svgData = read_file($svgJsonPath);
            $svgDataArray = json_clean_decode($svgData, true);
        } else {
            $svgSourceJsonPath = path('abs', 'design_state') . "templates";
            $svgSourceJsonPath .= '/' . $refId . '.json';
            copy($svgSourceJsonPath, $svgJsonPath);
            $svgData = read_file($svgSourceJsonPath);
            $svgDataArray = json_clean_decode($svgData, true);
        }
        return $svgDataArray;
    }



    /**
     * Get Captured Images associated to the Template's Ref ID
     *
     * @param $refId Design ID
     * @param $isRaw Flag
     *
     * @author tanmayap@riaxe.com
     * @date   14 aug 2019
     * @return Array
     */
    public function getCaptureImages($request, $refId, $isRaw = false)
    {
        $getStoreDetails = get_store_details($request);
        $storeId = $getStoreDetails['store_id'];
        $isS3Enabled = $this->checkS3Settings($storeId);

        $getCaptures = [];
        $withOutProductFile = [];
        $withProductFile = [];
        $fileLocationDir = path('read', 'design_preview') . 'templates';
        $absDirectoryName = path('abs', 'design_state') . 'marketplace_artworks';
        $finalSortedFileList = [];
        if (file_exists($absDirectoryName . '/' . $refId . '.json')) {
            $getImageFileHistory = read_file(
                $absDirectoryName . '/' . $refId . '.json'
            );
            // Get Capture Records as json format
            $finalSortedFileList = json_clean_decode($getImageFileHistory, true);
            if (!empty($isRaw)) {
                return $finalSortedFileList;
            }

            if (!empty($finalSortedFileList['other_file_details']['without_product_file'])) {
                foreach ($finalSortedFileList['other_file_details']['without_product_file'] as $woFile) {
                    $src = $fileLocationDir . '/' . $woFile['filename'];
                    $thumb = $fileLocationDir . '/' . 'thumb_' . $woFile['filename'];

                    if ($isS3Enabled) {
                        $src = $this->getS3URL($src, $storeId);
                        $thumb = $this->getS3URL($thumb, $storeId);
                    }
                    $withOutProductFile[] = [
                        'src' => $src,
                        'thumb' => $thumb,
                    ];
                }
                $getCaptures['without_product_file'] = $withOutProductFile;
            } elseif (isset($finalSortedFileList['without_product_file']) && !empty($finalSortedFileList['without_product_file'])) {
                foreach ($finalSortedFileList['without_product_file'] as $woFile) {
                    $src = $fileLocationDir . '/' . $woFile['filename'];
                    $thumb = $fileLocationDir . '/' . 'thumb_' . $woFile['filename'];

                    if ($isS3Enabled) {
                        $src = $this->getS3URL($src, $storeId);
                        $thumb = $this->getS3URL($thumb, $storeId);
                    }

                    $withOutProductFile[] = [
                        'src' => $src,
                        'thumb' => $thumb,
                    ];
                }
                $getCaptures['without_product_file'] = $withOutProductFile;
            }
            if (!empty($finalSortedFileList['other_file_details']['with_product_file'])) {
                foreach ($finalSortedFileList['other_file_details']['with_product_file'] as $woFile) {
                    $src = $fileLocationDir . '/' . $woFile['filename'];
                    $thumb = $fileLocationDir . '/' . 'thumb_' . $woFile['filename'];

                    if ($isS3Enabled) {
                        $src = $this->getS3URL($src, $storeId);
                        $thumb = $this->getS3URL($thumb, $storeId);
                    }
                    $withProductFile[] = [
                        'src' => $src,
                        'thumb' => $thumb,
                    ];
                }
                $getCaptures['with_product_file'] = $withProductFile;
            } elseif (isset($finalSortedFileList['with_product_file']) && !empty($finalSortedFileList['with_product_file'])) {
                foreach ($finalSortedFileList['with_product_file'] as $woFile) {
                    $src = $fileLocationDir . '/' . $woFile['filename'];
                    $thumb = $fileLocationDir . '/' . 'thumb_' . $woFile['filename'];

                    if ($isS3Enabled) {
                        $src = $this->getS3URL($src, $storeId);
                        $thumb = $this->getS3URL($thumb, $storeId);
                    }

                    $withOutProductFile[] = [
                        'src' => $src,
                        'thumb' => $thumb,
                    ];
                }
                $getCaptures['with_product_file'] = $withOutProductFile;
            }
        }

        return $getCaptures;
    }

    public function downloadArtworkData($request, $response, $args)
    {
        $content = $request->getQueryParam('type');
        $designId = to_int($args['id']);
        if ($content == "printFile") {
            $this->getArtworkPrintFiles($request, $designId);
        }
    }

    public function getArtworkPrintFiles($request, $designId, $type = '')
    {
        $getStoreDetails = get_store_details($request);
        $storeId = $getStoreDetails['store_id'];

        $jsonContent = $this->getSVGFile($designId, "marketplace_artworks");
        $baseDIR = path('abs', 'marketplace_artwork');
        $orderDwonloadObj = new OrderDownloadController();
        if (!is_dir($baseDIR . $designId) || 1) {
            mkdir($baseDIR . $designId, 0755, true);

            foreach ($jsonContent['sides'] as $k => $v) {

                if (isset($v['svg']) && !empty($v['svg'])) {
                    $sideNo = $k + 1;
                    $itemSidePath = $baseDIR . $designId . "/side_" . $sideNo . "";
                    //for preview folder image file
                    $sidePrvw = $itemSidePath . "/preview/side_" . $sideNo;
                    $pngFile = $sidePrvw . "_" . $designId . "_preview.png";
                    if (!is_dir($itemSidePath) && !file_exists($itemSidePath)) {
                        mkdir($itemSidePath, 0755, true);
                    }
                    if (!is_dir($previewItemPath)) {
                        mkdir($itemSidePath . "/preview", 0755, true);
                    }
                    $isS3Enabled = $this->checkS3Settings($storeId);

                    $previewUrl = $jsonContent['design_product_data'][0]['design_urls'][0];

                    if ($isS3Enabled) {
                        $previewUrl = $this->getS3URL($previewUrl, $storeId);
                    }

                    $imageContent = fileGetContentsCurl($previewUrl);

                    file_put_contents($pngFile, $imageContent);

                    $svgPrvwPath = $itemSidePath . "/preview_0";
                    $svgSidePath = $svgPrvwPath . $sideNo . ".svg";
                    $parameter = array(
                        'key' => $k, 'ref_id' => $designId,
                        'item_path' => $itemSidePath,
                        'svg_preview_path' => $svgSidePath,
                        'value' => $v,
                    );
                    $status = $orderDwonloadObj->createSideSvgByOrderId($parameter);
                    if ($status) {
                        $this->generateSvgPrintFile($svgSidePath, $designId, $jsonContent);
                    }
                }
            }
        }
        $sku =  base64_encode("IMP-" . $designId);
        $zipName = $sku . '.zip';
        if (file_exists($baseDIR . $zipName)) {
            unlink($baseDIR . $zipName);
        }
        $pathdir = $baseDIR . $designId . "/";
        $zip = new Zipper();
        $fileExtention = 'svg,png,pdf';
        $zipStatus = $zip->make($baseDIR . '/' . $zipName);
        if ($zipStatus) {
            $zip->addEmptyDir($designId);
            $sideDIR = scandir($pathdir);
            foreach ($sideDIR as $sideDirectory) {
                if ($sideDirectory != "." && $sideDirectory != "..") {
                    $optionsSide = array(
                        'add_path' => $designId . "/" . $sideDirectory . "/",
                        'remove_path' => $baseDIR . $designId . "/" . $sideDirectory,
                    );
                    $zip->addGlob($baseDIR . $designId . "/" . $sideDirectory . '/*{' . $fileExtention . '}', $optionsSide);
                }
            }
            $zip->close();
        }

        if ($type == 'create') {
            return true;
        }

        $status = $orderDwonloadObj->zipFileDownload($baseDIR . '/' . $zipName);
    }

    /**
     * GET: Create svg file according to print area dimension
     *
     * @param $reqSvgFile   The is current request SVG string
     * @param $orderId      The is current request order ID
     * @param $itemId       The is current request Item ID
     * @param $resultDesign The is current request design data
     *
     * @author radhanatham@riaxe.com
     * @date   03 Jan 2020
     * @return boolean
     */
    private function generateSvgPrintFile($reqSvgFile, $designId, $resultDesign, $artworkStatus = false)
    {


        $svgStatus = false;
        $status = false;
        //Filter tag for invert color
        $filterS = '<filter xmlns="http://www.w3.org/2000/svg" id="invertcolor" ';
        $filterM = 'color-interpolation-filters="sRGB" x="0" y="0" height="100%" ';
        $filterE = 'width="100%">';
        $feColorMatrixS = '<feColorMatrix in="SourceGraphic" type="matrix" ';
        $feColorMatrixE = 'values="-1 0 0 0
            1 0 -1 0 0
            1 0 0 -1 0
            1 0 0 0 1 0"/></filter>';
        $this->filter = $filterS . $filterM . $filterE . $feColorMatrixS . $feColorMatrixE;

        if ($reqSvgFile != '') {
            $svgFileStr = read_file($reqSvgFile);
            $oldReplaceStr = array(
                'data: png',
                'data: jpg',
                'data: jpeg',
                'data:png',
                'data:jpg',
                'data:jpeg',
                'data:image/jpg',
            );
            $newReplaceStr = array(
                'data:image/png',
                'data:image/jpeg',
                'data:image/jpeg',
                'data:image/png',
                'data:image/jpeg',
                'data:image/jpeg',
                'data:image/jpeg',
            );
            $svgFileStr = str_replace($oldReplaceStr, $newReplaceStr, $svgFileStr);
            $svgFileExtention = basename($reqSvgFile);
            $sideNo = str_replace(
                "preview_0",
                "",
                str_replace(".svg", "", $svgFileExtention)
            );

            $this->sidePath = "side_" . $sideNo . "_" . $designId;
            $multiPrintFileName = $this->sidePath . ".svg";
            $itemPath = $designId . '/side_' . $sideNo;
            $baseDIR = path('abs', 'marketplace_artwork');
            $this->svgSavePath = $baseDIR . $itemPath . '/';
            $sideIdIndex = $sideNo - 1;

            $sidePrintSvg = $resultDesign['sides'][$sideIdIndex];
            $this->printUnit = $resultDesign['sides'][$sideIdIndex]['print_unit']
                ? $resultDesign['sides'][$sideIdIndex]['print_unit'] : 'inch';
            $stickerInfo = $resultDesign['sides'][$sideIdIndex]['stickerInfo']
                ? $resultDesign['sides'][$sideIdIndex]['stickerInfo'] : array();
            $htmlStr = new \simple_html_dom();
            $htmlStr->load($svgFileStr, false);
            $svg = $htmlStr->find('image#svg_1', 0);
            $countLayer = substr_count($htmlStr, 'Layer_');

            if ($svg) {
                if (!is_dir($this->svgSavePath)) {
                    mkdir($this->svgSavePath, 0777, true);
                    chmod($this->svgSavePath, 0777);
                }
                if ($countLayer >= 2) {
                    $htmlStr->save();
                    //For single svg file for multiple boundary
                    /* $svgStatus = $this->generateSingleSvgFile(
                    $htmlStr, $svgAbsPath
                     */
                    //For multiple svg files for multiple boundary
                    $svgStatus = $this->generateMultiplePrintSvgFile(
                        $htmlStr,
                        $multiPrintFileName,
                        $sidePrintSvg,
                        $stickerInfo,
                        $artworkStatus
                    );
                    if ($artworkStatus) {
                        return $svgStatus;
                    }
                }
                $status = $svgStatus;
            }
        }
        return $status;
    }

    /**
     * GET: To create separate svg file for every print area
     *
     * @param $reqStr             The is current request SVG string
     * @param $multiPrintFileName The is current request SVG file name
     *
     * @author radhanatham@riaxe.com
     * @date   03 Jan 2020
     * @return boolean
     */
    public function generateMultiplePrintSvgFile(
        $reqStr,
        $multiPrintFileName,
        $sidePrintSvg,
        $stickerInfo,
        $artworkStatus = false
    ) {
        $orderDwonloadObj = new OrderDownloadController();
        $orderDwonloadObj->printUnit = $this->printUnit;
        $stickerPath = '';
        $isStickerEnable = $isContourSvg = 0;
        if (!empty($stickerInfo)) {
            $stickerAHeight = $stickerInfo['height'];
            $stickerAWidht = $stickerInfo['width'];
            if ($stickerInfo['cutline'] == 'Small' || $stickerInfo['cutline'] == 'Medium' || $stickerInfo['cutline'] == 'Large' && $stickerInfo['contourSvg'] != '') {
                $contourSvg = $stickerInfo['contourSvg'];
                if ($contourSvg != '') {
                    $isContourSvg = 1;
                    $htmlSticker = new \simple_html_dom();
                    $htmlSticker->load($contourSvg, false);
                    $stickerPath = $htmlSticker->find('path', 0);
                    $stickerGroup = $htmlSticker->find('g', 0);
                    $stickerGroupHeight = $stickerGroup->height;
                    $stickerGroupWidth = $stickerGroup->width;
                    $stickerGroupX = $stickerGroup->x;
                    $stickerGroupY = $stickerGroup->y;
                }
            }
            if ($stickerInfo['cutline'] == 'Circle' || $stickerInfo['cutline'] == 'Rectangle' || $stickerInfo['cutline'] == 'Heart' || $stickerInfo['cutline'] == 'Star' || $stickerInfo['cutline'] == 'Round corner') {
                $isStickerEnable = 1;
            }
        }
        $printArea = $sidePrintSvg['print_area'];
        $fileStr = chop($multiPrintFileName, '.svg');
        $svgStartTag = '<svg xmlns="http://www.w3.org/2000/svg"';
        $svgXlink = ' id="svgroot" xmlns:xlink="http://www.w3.org/1999/xlink"';
        $svgEndTag = '</g></svg>';
        $svgTagStr = $svgStartTag . $svgXlink;
        $html = new \simple_html_dom();
        $html->load($reqStr, false);
        $svg = $html->find('image#svg_1', 0);
        $borderGStr = '';
        $borderG = $html->find('g#borderG', 0);
        if (isset($borderG) && $borderG != '') {
            $borderGStr = $borderG;
        }
        $svgFileStatus = false;
        if ($svg) {
            $mainLayer = '';
            $mainLayer = $html->find("g[id^=Layer_]");
            $defs = $html->find('defs', 0);
            $embroideryFill = '#000000';

            $clipPath = $defs->find('clipPath[id^=mask_xe_]');
            if (isset($clipPath) && $clipPath != '') {
                foreach ($clipPath as $ck => $cv) {
                    $clipTransform = $clipPath[$ck]->transform;
                    unset($clipPath[$ck]->transform);
                    $firstChild = $clipPath[$ck]->first_child();
                    $firstChild->transform = $clipTransform;
                }
            }
            $feImage = $defs->find('feImage', 0);
            $envgFilter = $defs->find('filter', 0);
            $isEngrave = 0;
            $fillColor = '';
            if (isset($envgFilter) && $envgFilter != '') {
                $floodColor = 'flood-color';
                $envgFilterId = $envgFilter->id;
                $feFlood = $envgFilter->find('feFlood', 0);
                if (isset($feFlood) && $feFlood != '') {
                    $fillColor = $feFlood->$floodColor;
                }
                if (strpos($envgFilterId, 'engrave_') !== false) {
                    $isEngrave = 1;
                }
            }
            if (isset($feImage) && $feImage != '') {
                $isEngrave = 1;
                $feImage->outertext = '';
            }
            $vAlignWidthInch = $cropVal = $cropValPx = $bleedMarkMaxValue = 0;
            if (isset($mainLayer)) {
                $bounds = $gbleedM = '';
                $gbleedM = $html->find('g#bleedM', 0);
                if (isset($gbleedM) && $gbleedM !== '') {
                    $vAlignBright = $gbleedM->find('rect#vAlignBRight', 0);
                    $vAlignHeight = $vAlignBright->height;
                    $vAlignWidth = $vAlignBright->width;
                    $vAlignHeight = $vAlignBright->height;
                    $bleedMarkMaxValue = max($vAlignWidth, $vAlignHeight);
                    $vAlignWidthInch = (2 * $bleedMarkMaxValue) / $this->dpi;
                }
                $bounds = $html->find('g#bounds', 0);
                if (!isset($bounds)) {
                    $mainLayer = $html->find("g[xe_id^=Layer_]");
                    $bounds = $html->find("g[xe_id^=bounds]", 0);
                }
                if ($isStickerEnable) {
                    $bounds->display = 'block';
                } else {
                    $bounds->display = 'none';
                }

                foreach ($mainLayer as $k => $v) {
                    $isEmbroidery = false;
                    $printAreaId = 'bound_' . $k;
                    $path = $bounds->find('path#bound_' . $k, 0);
                    if (!isset($path)) {
                        $path = $bounds->find("g[xe_id^=bound_" . $k . "]", 0);
                    }
                    if ($isStickerEnable) {
                        $path->style = "display:block";
                    } else {
                        $path->style = "display:none";
                    }
                    if (!isset($path) || $path == '') {
                        $path = $bounds->find('path#bounds_' . $k, 0);
                    }
                    $id = $mainLayer[$k]->id;
                    $isBleed = $path->isBleed;
                    if (isset($isBleed) && $isBleed) {
                        if ($this->printUnit == 'Feet') {
                            $this->printUnit = 'Inch';
                        }
                        $cropVal = $path->cropVal;
                        if ($this->printUnit == 'Pixel') {
                            $cropValPx = $cropVal;
                        } else {
                            $cropVal = $orderDwonloadObj->unitConvertionToInch($cropVal);
                            $cropValPx = $cropVal * $this->dpi;
                        }
                        $path->aHeight = $path->aHeight + ($cropVal * 2);
                        $path->aWidth = $path->aWidth + ($cropVal * 2);
                    }
                    if ($isContourSvg) {
                        $height = $stickerGroupHeight;
                        $width = $stickerGroupWidth;
                        $aHeight = $stickerAHeight;
                        $aWidth = $stickerAWidht;
                    } else {
                        $height = $path->height;
                        $width = $path->width;
                        $aHeight = $path->aHeight ? $path->aHeight : 0;
                        $aWidth = $path->aWidth ? $path->aWidth : 0;
                    }
                    //Print area dimension swapping height and width
                    if ((intval($aWidth) > intval($aHeight)) && (intval($height) > intval($width))) {
                        $temp = 0;
                        $temp = $aHeight;
                        $aHeight = $aWidth;
                        $aWidth = $temp;
                    }
                    if ((intval($aHeight) > intval($aWidth)) && (intval($width) > intval($height))) {
                        $temp = 0;
                        $temp = $aWidth;
                        $aWidth = $aHeight;
                        $aHeight = $temp;
                    }
                    if ($isContourSvg) {
                        $x = ($stickerGroupX) - ($bleedMarkMaxValue);
                        $y = ($stickerGroupY) - ($bleedMarkMaxValue);
                    } else {
                        $x = ($path->x) - ($bleedMarkMaxValue);
                        $y = ($path->y) - ($bleedMarkMaxValue);
                    }
                    if ($this->printUnit == 'Pixel') {
                        $acWidth = $aWidth;
                        $acHeight = $aHeight;
                    } else {
                        $aWidth = $orderDwonloadObj->unitConvertionToInch($aWidth);
                        $aHeight = $orderDwonloadObj->unitConvertionToInch($aHeight);
                        $acWidth = $aWidth * $this->dpi;
                        $acHeight = $aHeight * $this->dpi;
                    }
                    $acHeight = $acHeight / $height;
                    $acWidth = $acWidth / $width;
                    if ($id == "Layer_" . $k . "" && strpos($mainLayer[$k], "layer") !== false) {
                        $isEmbroidery = $mainLayer[$k]->isEmb;
                        $xeProps = '';
                        $xeProps = $mainLayer[$k]->find(
                            'g[xe-props]',
                            0
                        );
                        if (isset($xeProps) && $xeProps != '') {
                            //Start engrave mode diabled for color
                            $defFilter = $defs->find("filter#engrave_" . $k . "", 0);
                            if (isset($defFilter) && $defFilter != '') {
                                $defFilter->outertext = '';
                            }
                            //Start engrave mode diabled for image
                            if ($isEngrave || $isEmbroidery) {
                                unset($mainLayer[$k]->filter);
                                $pathEvg = $mainLayer[$k]->find('path');
                                if (isset($pathEvg) && $pathEvg != '') {
                                    foreach ($pathEvg as $gkd => $gid) {
                                        if ($isEmbroidery) {
                                            $patt = $pathEvg[$gkd]->fill;
                                            if ($patt != 'none' && strpos($patt, 'url(#') !== false) {
                                                $pattID = substr(str_replace('url(#', '', $patt), 0, -1);
                                                $pattern = $mainLayer[$k]->find('pattern#' . $pattID, 0);
                                                $polygone = $pattern->find('polygon', 0);
                                                $embroideryFill = $polygone->fill;
                                                $pathEvg[$gkd]->fill = $embroideryFill;
                                            }
                                        }
                                        if (isset($fillColor) && $fillColor != '' && !$isEmbroidery) {
                                            $pathEvg[$gkd]->fill = $fillColor;
                                        }
                                    }
                                }
                            }
                            //End
                            $this->productImageTag = '';
                            //Check product with desin enable or not
                            if (
                                isset($printArea[$printAreaId]['is_include_product_image'])
                                && $printArea[$printAreaId]['is_include_product_image'] == 'include'
                            ) {
                                $this->productImageTag = $svg;
                            }
                            //Prepared SVG

                            //Implemented For Brilliant Tech Start
                            if ($mainLayer[$k]->height > 0 && $mainLayer[$k]->width > 0) {
                                $height = $mainLayer[$k]->height;
                                $width = $mainLayer[$k]->width;
                                $aWidth = $mainLayer[$k]->awidth;
                                $aHeight = $mainLayer[$k]->aheight;
                                $aWidth = $orderDwonloadObj->unitConvertionToInch($aWidth);
                                $aHeight = $orderDwonloadObj->unitConvertionToInch($aHeight);
                                $acWidth = $aWidth * $this->dpi;
                                $acHeight = $aHeight * $this->dpi;
                                $acHeight = $acHeight / $height;
                                $acWidth = $acWidth / $width;
                                $x = $mainLayer[$k]->ax;
                                $y = $mainLayer[$k]->ay;
                            }
                            //Implemented For Brilliant Tech End

                            $aWidth = $aWidth * $this->dpi;
                            $aWidth = $aWidth + (2 * $cropValPx) + $vAlignWidthInch;
                            $aHeight = $aHeight * $this->dpi;
                            $aHeight = $aHeight + (2 * $cropValPx) + $vAlignWidthInch;
                            $svgWidth = ' width="' . $aWidth . '"';
                            $svgHeight = ' height="' . $aHeight . '"';
                            $svgXY = ' x="0" y="0" overflow="visible">';
                            //Check horizontal enabled or not
                            $hFilp = $printArea[$printAreaId]['is_horizontally_flip'];
                            if ($hFilp) {
                                $filpY = $aHeight + (($y) * 0);
                                $fTransform = '<g transform="translate(-0';
                                $transformS = $fTransform . ',' . $filpY . ') scale(';
                                if ($acHeight != $acWidth) {
                                    $sDimension = $acWidth . ',' . $acHeight . ')';
                                    $scaleValue = $transformS . $sDimension;
                                } else {
                                    $scaleValue = $transformS . $acHeight . ')';
                                }
                                $filpSacle = ' scale(1,-1) translate(';
                                $xyValue = '-' . $x . ',-' . $y . ')">' . $stickerPath;
                                $transForm = $scaleValue . $filpSacle . $xyValue;
                            } else {
                                $scaleStr = '<g transform="scale(';
                                $scale = $scaleStr . $acWidth . ',' . $acHeight;
                                $translateX = ' translate(-' . $x . '';
                                $translateY = ',-' . $y . ')">' . $stickerPath;
                                $translate = $translateX . $translateY;
                                $transForm = $scale . ')' . $translate;
                            }
                            //Implemented For Brilliant Tech Start
                            $transForm = '<g>';

                            $mainLayer[$k]->setAttribute('transform', 'scale(' . $acWidth . ',' . $acHeight . ') translate(-' . $x . ',-' . $y . ')');
                            //Implemented For Brilliant Tech End
                            //Start engrave mode diabled for image
                            $feImages = $mainLayer[$k]->find('feImage');
                            if (isset($feImages) && !empty($feImages)) {
                                $imageFilter = $mainLayer[$k]->find('image');
                                if (isset($imageFilter) && $imageFilter != '') {
                                    foreach ($imageFilter as $imgk => $imgid) {
                                        unset($imageFilter[$imgk]->filter);
                                    }
                                }
                                foreach ($feImages as $keys => $img) {
                                    $feImages[$keys]->outertext = '';
                                }
                            }
                            //Start engrave mode diabled for color
                            $filterG = $mainLayer[$k]->find("g");
                            if (isset($filterG) && $filterG != '') {
                                foreach ($filterG as $fg => $fgv) {
                                    $filterValue = $filterG[$fg]->filter;
                                    if ($filterValue == "url(#engrave_" . $k . ")") {
                                        unset($filterG[$fg]->filter);
                                    }
                                }
                            }
                            //End
                            $svgTag = $svgTagStr . $svgWidth . $svgHeight;
                            $svgTagXY = $svgTag . $svgXY . $transForm . $this->productImageTag;
                            $svgMiddleTag = $svgTagXY . $defs . $bounds . $gbleedM;
                            $finalSvg = $svgMiddleTag . $mainLayer[$k] . $borderGStr . $svgEndTag;
                            $htmlSvg = $svgFinalString = '';
                            //Check invert color option enabled or not
                            $invertColor = $printArea[$printAreaId]['is_invert_color_enabled'];
                            if ($invertColor) {
                                $htmlSvg = new \simple_html_dom();
                                $htmlSvg->load($finalSvg, false);
                                $def = $htmlSvg->find('defs', 0);
                                $firstTag = $def->first_child();
                                $firstTag->outertext = $this->filter;
                                $groupLayer = $htmlSvg->find('g.layer');
                                foreach ($groupLayer as $key => $gl) {
                                    $groupLayer[$key]->filter = "url(#invertcolor)";
                                }
                            } else {
                                $htmlSvg = $finalSvg;
                            }
                            // echo $htmlSvg; exit;
                            $svgPath = $this->svgSavePath . $id;
                            $svgFilePath = $svgPath . '_' . $multiPrintFileName;
                            //png and pdf file name
                            $pngAbsPath = $svgPath . '_' . $fileStr . '.png';
                            $rgbPdfPath = $svgPath . '_' . $fileStr . '_rgb.pdf';
                            $cmykPdfAbsPath = $svgPath . '_' . $fileStr . '.pdf';
                            //Check bleed mark enabled or not per print profile
                            $bleedMarkEnabled = $printArea[$printAreaId]['is_bleed_mark_enabled'];

                            if ($bleedMarkEnabled && (isset($isBleed) && $isBleed)) {
                                $bleedMark = $printArea[$printAreaId]['bleed_mark'];
                                if ($bleedMark['cut_mark']) {
                                    $htmlDom = new \simple_html_dom();
                                    $htmlDom->load($htmlSvg, false);
                                    $domBleedG = $htmlDom->find('g#bleedM', 0);
                                    $domBleedG->display = 'block';
                                    $svgFinalString = $htmlDom;
                                }
                            } else {
                                $svgFinalString = $htmlSvg;
                            }

                            //Check file format
                            $fileFormat = $printArea[$printAreaId]['allowed_order_formats'];
                            //Check used color for every individual product side
                            $isColorSeparation = $printArea[$printAreaId]['is_color_separation_enabled'];
                            if ($isColorSeparation && !$artworkStatus) {
                                //Used color list
                                $this->printColorsArr = $printArea[$printAreaId]['used_colors'];
                                $orderDwonloadObj->generateSvgFileByColor($svgFinalString, $id, $fileFormat);
                            }

                            if (!in_array('svg', $fileFormat)) {
                                array_push($this->svgFileArr, $id . '_' . $multiPrintFileName);
                            }

                            if (!file_exists($svgFilePath)) {
                                $svgFileStatus = $artworkReturnStatus = write_file(
                                    $svgFilePath,
                                    $svgFinalString
                                );
                            } else {
                                $svgFileStatus = $artworkReturnStatus = true;
                            }


                            if (!$artworkStatus) {
                                if (!file_exists($pngAbsPath)) {
                                    $orderDwonloadObj->svgConvertToPng(
                                        $pngAbsPath,
                                        $svgFilePath
                                    );
                                }
                                if (!file_exists($rgbPdfPath)) {
                                    $orderDwonloadObj->svgConvertToRGBPdf(
                                        $rgbPdfPath,
                                        $svgFilePath
                                    );
                                }
                                if (!file_exists($cmykPdfAbsPath)) {
                                    $orderDwonloadObj->rgbPdfConvertToCMYKPdf(
                                        $cmykPdfAbsPath,
                                        $rgbPdfPath
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }
        if ($artworkStatus) {
            return $artworkReturnStatus;
        } else {
            return $svgFileStatus;
        }
    }
}
