<?php

/**
 * Order artwork details on various endpoints
 *
 * PHP version 5.6
 *
 * @category  Order
 * @package   OrderArtwork
 * @author    Diana <diana@imprintnext.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 */
namespace App\Modules\Orders\Controllers;

use App\Components\Controllers\Component as ParentController;
use App\Modules\Orders\Models\ArtworkApproval;
use App\Modules\Orders\Models\ArtworkApprovalConversations;
use App\Modules\Orders\Models\ArtworkApprovalConvFiles;
use App\Modules\Orders\Controllers\OrderDownloadController;
use App\Modules\Orders\Models\OrderLog;
use App\Modules\Products\Controllers\ProductsController;
use OrderStoreSpace\Controllers\StoreOrdersController;
use App\Modules\Orders\Models\Orders;
use ProductStoreSpace\Controllers\StoreProductsController;
use App\Modules\Orders\Controllers\OrdersController;

/**
 * Order Download Controller
 *
 * @category Class
 * @package  OrderArtwork
 * @author   Diana <diana@imprintnext.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 */
class OrderArtworkController extends ParentController {

    /**
     * Post: Save Order artwork approval
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author diana@imprintnext.com
     * @date   12 Oct 2023
     * @return Order logs in Json format
     */
    public function editOrderArtwork($request, $response, $args) {
        $serverStatusCode = OPERATION_OKAY;
        $allPostPutVars = $request->getParsedBody();
        $jsonResponse = [
            'status' => 0,
            'message' => message('Order Log', 'error'),
        ];
        $storeDetails = get_store_details($request);
        $storeID = $storeDetails['store_id'] ? $storeDetails['store_id'] : 1;
        $isS3Enabled = $this->checkS3Settings($storeID);
        $allPostPutVars = $request->getParsedBody();
        if (isset($args['id']) && $args['id'] > 0) {
            $orderId = $args['id'];
            $oldCustomDesignId = $allPostPutVars['old_custom_design_id'] ? $allPostPutVars['old_custom_design_id'] : '';
            $newCustomDesignId = $allPostPutVars['new_custom_design_id'] ? $allPostPutVars['new_custom_design_id'] : '';
            $orderItemId = $allPostPutVars['order_item_id'] ? $allPostPutVars['order_item_id'] : [];
            $type = $allPostPutVars['type'] ? $allPostPutVars['type'] : '';
            if ($oldCustomDesignId != '' && $newCustomDesignId != '') {
                //Check if record is present or not
                $artworkApprovalInit = new ArtworkApproval();
                $checkData = $artworkApprovalInit->where(['order_id' => $orderId, 'old_ref_id' => $oldCustomDesignId]);
                $status = ($type == 'update_design') ? 0 : 1;
                if ($checkData->count() > 0) {
                    $checkDataArr = $checkData->first()->toArray();
                    $orderArtworkId = $checkDataArr['xe_id'];
                    //Update data
                    $updateData = [
                        'new_ref_id' => $newCustomDesignId,
                        'status' => $status,
                    ];
                    $artworkApprovalInit->where('xe_id', $orderArtworkId)->update($updateData);
                } else {
                    //Save data 
                    $saveData = [
                        'order_id' => $orderId,
                        'order_item_id' => $orderItemId,
                        'old_ref_id' => $oldCustomDesignId,
                        'new_ref_id' => $newCustomDesignId,
                        'status' => $status
                    ];
                    $saveArtworkApprovalData = new ArtworkApproval($saveData);
                    $saveArtworkApprovalData->save();
                    $orderArtworkId = $saveArtworkApprovalData->xe_id;
                }
                $this->changeOrderArtworkStatus($orderId);
                //Update the new custom design id for order
                if ($type == 'update_design') {
                    $itemArr = json_clean_decode($orderItemId);
                    if (strtolower(STORE_NAME) == "shopify") {
                        $ordersInit = new Orders();
                        $orderDetails = $ordersInit->where('order_id', $orderId)->first();
                        $getOrderId = $orderDetails['order_number'];
                    } else {
                        $getOrderId = $orderId;
                    }
                    $updateArtworkStatus = $this->updateArtworkApproval($oldCustomDesignId, $newCustomDesignId, $getOrderId, $itemArr, $isS3Enabled, $storeID);
                    if ($updateArtworkStatus) {
                        $jsonResponse = [
                            'status' => 1,
                            'message' => message('Order artwork', 'done'),
                        ];
                    }
                    $message = '#'.$orderArtworkId.' artwork is changed and updated for order.';
                } else {
                    //Send for approval operation
                    $customerEmail = $allPostPutVars['customer_email'] ? $allPostPutVars['customer_email'] : '';
                    if ($customerEmail != '') {
                        $customerData = [
                            'name' => $customerEmail,
                            'email' => $customerEmail
                        ];
                        $token = 'order_id=' . $orderId. '&order_artwork_id='.$orderArtworkId.'&store_id='. $storeDetails['store_id'];
                        $token = base64_encode($token);
                        $url = API_URL . 'quotation/art-work?token=' . $token . '&artwork_type=order';

                        $prev = "<!DOCTYPE html>
                                    <html>
                                        <title>Quote</title>
                                        <style>a{color:#1b41c7}</style>
                                        <body>
                                            <table style='border-collapse: collapse; width: 100%; max-width: 835px; min-width: 320px;'>
                                                <tbody>
                                                    <tr>
                                                        <td valign='top' style='padding:0 0px'><table cellspacing='0' cellpadding='0' border='0' align='center' style='border-collapse:collapse;border-radius:3px;color:#545454;font-family:Helvetica Neue,Arial,sans-serif;font-size:13px;line-height:20px;margin:0 auto;width:100%'><tbody><tr><td valign='top'>";

                        $next = "</td></tr></tbody></table></td></tr><tr><td valign='top' height='20'/></tr></tbody></table></body></html>";

                        $html = "<table cellspacing='0' cellpadding='0' border='0' style='border-collapse:collapse;border-color:#dddddd;border-radius:0 0 3px 3px;border-style:solid solid none; padding: 10px; display: block;color:#525252;'>
                                    <tbody>
                                        <tr>
                                            <td bgcolor='white' style='background:white;border-radius:0 0 3px 3px;color:#525252;font-family:Helvetica Neue,Arial,sans-serif;font-size:15px;line-height:22px;overflow:hidden;padding:10px 10px 10px'>
                                                    <p align='left' style='line-height:1.5;margin:0 0 5px;text-align:left!important;color:#525252;'>Thank you for your order request.</strong></p>
                                                    <p align='left' style='line-height:1.5;margin:0 0 5px;text-align:left!important;color:#525252;'>We have evaluated your project details and created an artwork for your review. Please click the link below to review the artwork we have proposed:</strong></p>
                                                    <p align='left' style='line-height:1.5;margin:0 0 5px;text-align:left!important;color:#525252;'><br/>Link : <a target='_blank' href='" . $url . "'> " . $url . " </a> <br/></p>
                                                    <p align='left' style='line-height:1.5;margin:0 0 5px;text-align:left!important;color:#525252;'>Once you have looked over your order, you can go ahead and approve or decline it. If you need any more help, please chat with the sales associate.</p>
                                                    <p align='left' style='line-height:1.5;margin:10px 0 5px;text-align:left!important;color:#525252'>Thank you</p>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>";
                        $emailBody = $prev . $html . $next;
                        $templateData = [
                            'subject' => 'Artwork approval #'.$orderId,
                            'message' => $emailBody,
                        ];
                        $mailStatus = $this->sendEmail($templateData, $customerData);
                        if ($mailStatus['status'] == 1) {
                            $jsonResponse = [
                                'status' => 1,
                                'message' => message('Order artwork', 'done'),
                            ];
                            $message = '#'.$orderArtworkId.' artwork is changed and sent for approval.';
                        }
                    }
                }
                $artworkDeisgnStatePath = path('abs', 'design_state') . 'artwork_approval'.'/' . $newCustomDesignId . ".json";
                if (file_exists($artworkDeisgnStatePath)) {
                    //Delete folder
                    delete_directory(path('abs', 'order') .  'artwork_approval/' . $orderArtworkId);
                    $orderJson = read_file($artworkDeisgnStatePath);
                    $jsonContent = json_clean_decode($orderJson, true);
                    $getSideDataArr = $jsonContent['sides'];
                    $orderDwonloadObj = new OrderDownloadController();
                    foreach ($getSideDataArr as $sideKey => $sideData) {
                        $skey = $sideKey+1;
                        $svgFileName = 'preview_0'. $skey . ".svg";
                        $path = path('abs', 'order') .  'artwork_approval/' . $orderArtworkId . '/side_'.$skey.'/';
                        $svgPath = $path . $svgFileName;
                        if (!file_exists($path)) {
                            create_directory($path);
                        }
                        if (!file_exists($orderJson)) {
                            $parameter = array(
                                'key' => $sideKey,
                                'ref_id' => $newCustomDesignId,
                                'item_path' => '',
                                'svg_preview_path' => $svgPath,
                                'value' => $sideData,
                                'is_s3_enabled' => $isS3Enabled,
                            );
                            $orderDwonloadObj->createSideSvgByOrderId($parameter);
                            $orderDwonloadObj->generateSvgFile(
                                $svgPath,
                                'artwork_approval',
                                $orderArtworkId,
                                $jsonContent,
                                false,
                                false,
                                false
                            );
                        }
                    }
                }
                //Add log data 
                if ($orderArtworkId > 0 && $message != '') {
                    $saveLogData = [
                        'order_id' => $orderId,
                        'agent_type' => 'admin',
                        'agent_id' => 1,
                        'store_id' => $storeDetails['store_id'],
                        'message' => $message,
                        'log_type' => 'artwork',
                        'status' => 'new',
                        'artwork_approval_id' => $orderArtworkId,
                        'created_at' => date_time(
                            'today', [], 'string'
                        )
                    ];
                    $this->addArtworkLog($saveLogData);
                }
            }
        }
        return response($response, [
            'data' => $jsonResponse, 'status' => $serverStatusCode
        ]);
    }

    /**
     * Internal function for sending email to customer
     *
     * @param $templateData  Email body 
     * @param $customerData  Customer info
     * @param $attachments   Attachment files array
     *
     * @author diana@imprintnext.com
     * @date   12 Oct 2023
     * @return Email response status
     */
    public function sendEmail($templateData, $customerData, $attachments = [])
    {
        //Get smtp email setting data for sending email
        $smtpSettingData = $this->getSmtpSettings(1, 1);
        $emailData = $smtpSettingData['email_data'];
        $smtpData = $smtpSettingData['smtp_data'];

        $fromName = isset($emailData['from_email']) ? $emailData['from_email'] : '';
        $fromEmail = isset($smtpData['smtp_from']) ? $smtpData['smtp_from'] : '';
        $replyToEmail = isset($emailData['to_email']) ? $emailData['to_email'] : '';
        $emailBody = $templateData['message'];
        if (empty($customerData)) {
            $customerData['email'] = $customerData['name'] = $replyToEmail;
        }
        $mailContaint = ['from' => ['email' => $fromEmail, 'name' => $fromName],
            'recipients' => [
                'to' => [
                    'email' => $customerData['email'],
                    'name' => $customerData['name'],
                ],
                'reply_to' => [
                    'email' => $replyToEmail,
                    'name' => $replyToEmail,
                ],
            ],
            'attachments' => ($attachments != '') ? $attachments : [],
            'subject' => $templateData['subject'],
            'body' => $emailBody,
            'smptData' => $smtpData
        ];
        if (isset($smtpData['smtp_host']) && $smtpData['smtp_host'] !='' 
            && isset($smtpData['smtp_user']) && $smtpData['smtp_user'] != ''
            && isset ($smtpData['smtp_pass']) && $smtpData['smtp_pass'] != ''
        ) {
                $mailResponse = email($mailContaint);
        } else {
            $mailResponse['status'] = 0;
        }
        return $mailResponse;
    }

    /**
     * Internal function for updating artwork related data
     *
     * @param $oldCustomDesignId  old artwork custom design id
     * @param $newCustomDesignId  new artwork custom design id
     * @param $orderId   Order id
     * @param $itemArr   Order items array
     *
     * @author diana@imprintnext.com
     * @date   12 Oct 2023
     * @return boolean
     */
    private function updateArtworkApproval($oldCustomDesignId, $newCustomDesignId, $orderId, $itemArr, $isS3Enabled = false, $storeId = 1)
    {
        $operationStatus = false;
        $deisgnStatePath = path('abs', 'design_state') . 'carts';
        $predecoPath = path('abs', 'design_state') . 'predecorators';
        $quotationPath = path('abs', 'design_state') . 'artworks';
        $orderJsonPath = $deisgnStatePath . '/' . $oldCustomDesignId . ".json";
        $orderPredecoPath = $predecoPath . '/' . $oldCustomDesignId . ".json";
        $orderQuotationPath = $quotationPath . '/' . $oldCustomDesignId . ".json";
        
        if (file_exists($orderJsonPath)) {
            $orderJson = read_file($orderJsonPath);
            $directory = 'carts';
        } elseif (file_exists($orderPredecoPath)) {
            $orderJson = read_file($orderPredecoPath);
            $directory = 'predecorators';
        } elseif (file_exists($orderQuotationPath)) {
            $orderJson = read_file($orderQuotationPath);
            $directory = 'artworks';
        } else {
            $orderJson = '';
            $directory = '';
        }
        //backup json file
        if ($orderJson != '') {
            $backupJsonName = $oldCustomDesignId.'-artwork-backup';
            $svgSaveLoc = path('abs', 'design_state') . $directory;
            $saveLocation = $svgSaveLoc . '/' . $backupJsonName . '.json';
            if (!file_exists($saveLocation)) {
                write_file($saveLocation, $orderJson);
            }
        }
        //rewrite new json data to old json file
        $artworkDeisgnStatePath = path('abs', 'design_state') . 'artwork_approval'.'/' . $newCustomDesignId . ".json";
        if (file_exists($artworkDeisgnStatePath)) {
            $artworkApprovalJson = read_file($artworkDeisgnStatePath);
            $newLoc = path('abs', 'design_state') . $directory;
            $editLocation = $newLoc . '/' . $oldCustomDesignId . '.json';
            write_file($editLocation, $artworkApprovalJson);
        }
        //Update assets file
        $createStatus = $this->createArtworkAfterApproval($orderId, $itemArr, $oldCustomDesignId, $isS3Enabled);
        if ($createStatus) {
            if ($isS3Enabled) {
                $thisOrderDIR = path('abs', 'order') . $orderId;
                if(strtolower(STORE_NAME) == "bigcommerce"){
                    sleep(4);
                }
                $this->uploadDIRToS3Recurse("/assets/orders/".$orderId, $thisOrderDIR, $storeId);
            }
            $operationStatus = true;
        }
        return $operationStatus;
    }

    /**
     * Internal function for creating artwork after approval
     *
     * @param $orderId   Order id
     * @param $itemArr   Order items array
     * @param $customDesignId  artwork custom design id
     * @param $isS3Enabled  S3 enabled flag
     *
     * @author diana@imprintnext.com
     * @date   12 Oct 2023
     * @return boolean
     */
    public function createArtworkAfterApproval($orderId, $itemArr, $customDesignId, $isS3Enabled = false)
    {
        $orderDownloadControllerInit = new OrderDownloadController();
        $status = 0;
        if ($orderId != '' && $orderId > 0 && !empty($itemArr)) {
            $orderAbsPath = path('abs', 'order');
            $orderPath = $orderAbsPath . $orderId;
            $deisgnStatePath = path('abs', 'design_state') . 'carts';
            $deisgnStatePredecoPath = path('abs', 'design_state') . 'predecorators';
            $quoteDeisgnStatePath = path('abs', 'design_state') . 'artworks';
            $orderJson = read_file($orderPath . '/order.json');
            $orderJsonContent = json_clean_decode($orderJson, true);
            $orderAllItemDataArr = $orderJsonContent['order_details']['order_items'];
            foreach ($itemArr as $items) {
                $itemId = $items;
                $orderItemArr = array_filter($orderAllItemDataArr, function ($item) use ($itemId) {
                    return $item['item_id'] == $itemId;
                });
                $orderItemArr = $orderItemArr[array_keys($orderItemArr)[0]];
                $variantId = $orderItemArr['variant_id'];
                if (strtolower(STORE_NAME) == "shopify") {
                    $storeProductInit = new StoreProductsController();
                    $parentProductID = $storeProductInit->getOriginalVarID($variantId);
                    $variantId = $parentProductID;
                }
                
                $itemPath = $orderPath . "/" . $itemId;
                //Delete the previous folder and then create the new one
                delete_directory($itemPath);
                if (!is_dir($itemPath)) {
                    mkdir($itemPath, 0755, true);
                }
                $refId = $customDesignId;
                $isPredecoFlag = false;
                if (file_exists($deisgnStatePath . '/' . $refId . '.json')) {
                    $isPredecoFlag = false;
                    $designStateJson = read_file($deisgnStatePath . '/' . $refId . '.json');
                } elseif (file_exists($quoteDeisgnStatePath . '/' . $refId . '.json')) {
                    $isPredecoFlag = true;
                    $designStateJson = read_file($quoteDeisgnStatePath . '/' . $refId . '.json');
                } else {
                    $isPredecoFlag = true;
                    $designStateJson = read_file($deisgnStatePredecoPath . '/' . $refId . '.json');
                }
                $jsonContent = json_clean_decode($designStateJson, true);
                //If order created from quotation for pre-deco product
                if (empty($jsonContent)) {
                    $isPredecoFlag = true;
                    $designStateJson = read_file($deisgnStatePredecoPath . '/' . $refId . '.json');
                    $jsonContent = json_clean_decode($designStateJson, true);
                }
                $captureUrls = [];
                if (!empty($jsonContent['design_product_data'])) {
                    foreach ($jsonContent['design_product_data'] as $deisgnUrl) {
                        if ($isPredecoFlag) {
                            if (!empty($deisgnUrl['design_urls'])) {
                                $captureUrls = $deisgnUrl['design_urls'];
                            }
                        } else {
                            if (in_array($variantId, $deisgnUrl['variant_id']) && !empty($deisgnUrl['design_urls'])) {                     
                                    $captureUrls = $deisgnUrl['design_urls'];
                            }
                        }
                    }
                }
                if (is_dir($itemPath)) {
                    $status = write_file(
                        $itemPath . '/designState.json', $designStateJson
                    );
                }
                //For name and number
                if (isset($jsonContent['name_number']) && !empty($jsonContent['name_number'])) {
                    $headerData = $jsonContent['name_number'][0];
                    $rowData = $jsonContent['name_number'];
                    $csvFilename = 'nameNumber.csv';
                    $this->jsonToCSV($rowData, $csvFilename, $headerData, $itemPath, $isS3Enabled, $storeID);
                }
                //For preview folder image file
                foreach ($jsonContent['sides'] as $k => $v) {
                    if (isset($v['svg']) && !empty($v['svg'])) {
                        $sideNo = $k + 1;
                        $itemSidePath = $itemPath . "/side_" . $sideNo . "";
                        //for preview folder image file
                        $customizeImage = '';
                        if (isset($captureUrls[$k])
                            && !empty($captureUrls[$k])
                        ) {
                            $customizeImage = fileGetContentsCurl($captureUrls[$k]);
                        }
                        $previewItemPath = $itemSidePath . "/preview/";
                        $sidePrvw = $itemSidePath . "/preview/side_" . $sideNo;
                        $itemPrvw = $sidePrvw . "_" . $itemId . "_";
                        $pngFile = $itemPrvw . $orderId . "_preview.png";
                        if (!is_dir($previewItemPath)) {                                   
                                mkdir($previewItemPath, 0755, true);
                        }

                        if (is_dir($previewItemPath) && !file_exists($pngFile)) {
                                write_file($pngFile, $customizeImage);
                        }

                        if (!is_dir($itemSidePath)) {
                                mkdir($itemSidePath, 0755, true);
                        }
                        // Create Embroidery files
                        foreach($v['print_area'] as $pvalue){
                            if($pvalue['isEmb'] == 1){
                                $embAbsPath = path('abs', 'embroidery');
                                $embPath = $itemSidePath . "/embroidery_files";
                                $embPreviewPath = $embPath . "/preview";
                                if (!is_dir($embPath)) {                                   
                                    mkdir($embPath, 0755, true);
                                }
                                if (!is_dir($embPreviewPath)) {                                   
                                    mkdir($embPreviewPath, 0755, true);
                                }
                                $embPreviewUrl = $pvalue['embInfo']['embroidery_preview'];
                                $embPreviewUrl = explode('embroidery/', $embPreviewUrl);
                                $embPreviewFilename = $embPreviewUrl[1];
                                copy($embAbsPath . '/' . $embPreviewFilename, $embPreviewPath . '/' . $embPreviewFilename);
                                $embMachineUrl = $pvalue['embInfo']['embroidery_machine'];
                                $embMachineUrl = explode('embroidery/', $embMachineUrl);
                                $embMachineFilename = $embMachineUrl[1];
                                copy($embAbsPath . '/' . $embMachineFilename, $embPath . '/' . $embMachineFilename);
                            }
                        }
                        $svgPrvwPath = $itemSidePath . "/preview_0";
                        $svgSidePath = $svgPrvwPath . $sideNo . ".svg";
                        $previewFilePath = "side_".$sideNo."_".$itemId."_".$orderId."_preview.svg";
                        $parameter = array(
                            'key' => $k, 'ref_id' => $refId,
                            'item_path' => $itemSidePath,
                            'svg_preview_path' => $svgSidePath,
                            'is_s3_enabled' => $isS3Enabled,
                            'value' => $v,
                            'preview_path' => $previewFilePath
                        );
                        $status = $orderDownloadControllerInit->createSideSvgByOrderId($parameter);
                    }
                }
            }
        }
        return $status;
    }

    /**
     * Post: Change Order artwork approval status
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author diana@imprintnext.com
     * @date   12 Oct 2023
     * @return Order logs in Json format
     */
    public function changeApprovalStatus($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Order Log', 'error'),
        ];
        $storeDetails = get_store_details($request);
        $storeID = $storeDetails['store_id'] ? $storeDetails['store_id'] : 1;
        $isS3Enabled = $this->checkS3Settings($storeID);
        $allPostPutVars = $request->getParsedBody();
        if (isset($args['id']) && $args['id'] > 0) {
            $artworkApprovalId = $args['id'];
            $type = $allPostPutVars['type'] ? $allPostPutVars['type'] : '';
            //Check if record is present or not
            $artworkApprovalInit = new ArtworkApproval();
            $checkData = $artworkApprovalInit->where('xe_id', $artworkApprovalId);
            if ($checkData->count() > 0) {
                $checkDataArr = $checkData->first()->toArray();
                $orderArtworkId = $checkDataArr['xe_id'];
                $orderId = $checkDataArr['order_id'];
                //Update data
                $updateData = [
                    'status' => ($type == 'approve') ? 2 : 3,
                ];
                $artworkApprovalInit->where('xe_id', $artworkApprovalId)->update($updateData);
            
                //Update the new custom design id for order
                if ($type == 'approve') {
                    $itemArr = json_clean_decode($checkDataArr['order_item_id']);
                    $oldCustomDesignId = $checkDataArr['old_ref_id'];
                    $newCustomDesignId = $checkDataArr['new_ref_id'];
                    $orderId = $checkDataArr['order_id'];
                    if (strtolower(STORE_NAME) == "shopify") {
                        $ordersInit = new Orders();
                        $orderDetails = $ordersInit->where('order_id', $orderId)->first();
                        $getOrderId = $orderDetails['order_number'];
                    } else {
                        $getOrderId = $orderId;
                    }
                    $updateArtworkStatus = $this->updateArtworkApproval($oldCustomDesignId, $newCustomDesignId, $getOrderId, $itemArr, $isS3Enabled, $storeID);
                    if ($updateArtworkStatus) {
                        $message = '#'.$orderArtworkId.' artwork is approved and updated for order.';
                    }
                } else {
                    $message = '#'.$orderArtworkId.' artwork is rejected.';
                    if (isset($allPostPutVars['reject_msg'])) {
                        $message .= " Reason: ".$allPostPutVars['reject_msg'];
                    }
                }
                $this->changeOrderArtworkStatus($orderId);
                //Add log data
                if ($orderArtworkId > 0 && $message != '') {
                    $saveLogData = [
                        'order_id' => $orderId,
                        'agent_type' => $allPostPutVars['user_type'],
                        'agent_id' =>$allPostPutVars['user_id'],
                        'store_id' => $storeDetails['store_id'],
                        'message' => $message,
                        'log_type' => 'artwork',
                        'status' => 'new',
                        'artwork_approval_id' => $orderArtworkId,
                        'created_at' => date_time(
                            'today', [], 'string'
                        )
                    ];
                    $this->addArtworkLog($saveLogData);
                    $jsonResponse = [
                        'status' => 1,
                        'message' => message('Order artwork', 'done'),
                    ];
                }
            }
        }
        return response($response, [
            'data' => $jsonResponse, 'status' => $serverStatusCode
        ]);
    }

    public function addArtworkLog($logData)
    {
        $saveOrderLog = new OrderLog($logData);
        $saveOrderLog->save();
    }

    /**
     * GET: Get order artwork approval conversation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author diana@imprintnext.com
     * @date   06 Nov 2023
     * @return json response
     */
    public function getArtworkConversations($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Conversation', 'not_found'),
        ];
        if (!empty($args['id'])) {
            $artworkAppId = to_int($args['id']);
            $artworkApprovalInit = new ArtworkApproval();
            $checkData = $artworkApprovalInit->where('xe_id', $artworkAppId);
            if ($checkData->count() > 0) {
                $conversationInit = new ArtworkApprovalConversations();
                $conversations = $conversationInit->with('files')->where('order_artwork_id', $artworkAppId);
                if ($conversations->count() > 0) {
                    $conversationArr = $conversations->get();
                    $jsonResponse = [
                        'status' => 1,
                        'data' => $conversationArr,
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Add order artwork approval conversation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author diana@imprintnext.com
     * @date   06 Nov 2023
     * @return json response wheather data is saved or any error occured
     */
    public function saveArtworkConversations($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Conversation', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        $artworkAppId = to_int($allPostPutVars['order_artwork_id']);
        if ($artworkAppId != '') {
            $artworkApprovalInit = new ArtworkApproval();
            $checkData = $artworkApprovalInit->where('xe_id', $artworkAppId);
            if ($checkData->count() > 0) {
                $allPostPutVars['created_date'] = date_time(
                    'today', [], 'string'
                );
                $allPostPutVars['seen_flag'] = 1;
                $artworkConversations = new ArtworkApprovalConversations($allPostPutVars);
                if ($artworkConversations->save()) {
                    $convInsertId = $artworkConversations->xe_id;
                    $allFileNames = do_upload(
                        'upload',
                        path('abs', 'order') . 'conversation/', [150],
                        'array'
                    );
                    //Save file name w.r.t note
                    if (!empty($allFileNames)) {
                        foreach ($allFileNames as $eachFile) {
                            $fileData = [
                                'conv_id' => $convInsertId,
                                'file' => $eachFile,
                            ];
                            $saveConversationFile = new ArtworkApprovalConvFiles($fileData);
                            $saveConversationFile->save();
                        }
                    }
                    $jsonResponse = [
                        'status' => 1,
                        'message' => message('Conversation', 'saved'),
                        'conversation_id' => $convInsertId
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }


    /**
     * GET: Get order artwork design details
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author diana@imprintnext.com
     * @date   06 Nov 2023
     * @return json response wheather data is saved or any error occured
     */
    public function getArtworkViewData($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Artwork design', 'error'),
        ];
        $storeDetails = get_store_details($request);
        $isS3Enabled = $this->checkS3Settings($storeDetails['store_id']);
        $type = $request->getQueryParam('type');
        if (!empty($args['id'])) {
            $artworkAppId = to_int($args['id']);
            $artworkApprovalInit = new ArtworkApproval();
            $artworkApproval = $artworkApprovalInit->where('xe_id', $artworkAppId);
            if ($artworkApproval->count() > 0) {
                $artworkApprovalData = $artworkApproval->first()->toArray();
                $orderId = $artworkApprovalData['order_id'];
                $newRefId = $artworkApprovalData['new_ref_id'];
                $artworkDeisgnStatePath = path('abs', 'design_state') . 'artwork_approval'.'/' . $newRefId . ".json";
                if (file_exists($artworkDeisgnStatePath)) {
                    $artworkApprovalJson = read_file($artworkDeisgnStatePath);
                    $artworkApprovalJsonData = json_clean_decode($artworkApprovalJson, true);
                    $finalDesignData = [];
                    foreach ($artworkApprovalJsonData['sides'] as $sideKey => $sides) {
                        if ($sides['is_designed'] == 1) {
                            $sKey = $sideKey+1;
                            foreach ($sides['print_area'] as $layerKey => $printArea) {
                                $lKey = explode('bound_', $layerKey);
                                $digits = 3;
                                $rvnUniqeNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);
                                if ($printArea['isDesigned'] == 1) {
                                    $artworkUrl = path('read', 'order').'artwork_approval/'.$artworkAppId.'/side_'.$sKey.'/Layer_'.$lKey[1].'_side_'.$sKey.'_'.$artworkAppId.'_artwork_approval.svg?rvn='. $rvnUniqeNo;
                                    $tempDesignData = [
                                        'artwork_url' => $artworkUrl,
                                        'side_name' => $sides['side_name'],
                                        'print_area' => $printArea['print_area']['name'],
                                        'print_area_width' => $printArea['print_area']['width'],
                                        'print_area_height' => $printArea['print_area']['height'],
                                        'print_method' => $printArea['print_method_name'],
                                        'used_colors' => $printArea['used_colors'],
                                        'design_width' => $printArea['design_width'],
                                        'design_height' => $printArea['design_height'],
                                        'artwork_coordinates' => $printArea['artwork_coordinates'],
                                        'print_unit' => $sides['print_unit'],
                                    ];
                                    array_push($finalDesignData, $tempDesignData);
                                }
                            }
                        }
                    }
                    $productData = [];
                    if (strtolower(STORE_NAME) == "shopify") {
                        $ordersInit = new Orders();
                        $orderDetails = $ordersInit->where('order_id', $orderId)->first();
                        $getOrderId = $orderDetails['order_number'];
                    } else {
                        $getOrderId = $orderId;
                    }
                    $orderJsonPath = path('abs', 'order')  . $getOrderId . "/order.json";
                    if (!file_exists($orderJsonPath) && $isS3Enabled) {
                        $this->downloadS3Content("/assets/orders/".$getOrderId, path('abs', 'order') . $getOrderId, $storeDetails['store_id']);
                    }
                    $orderJson = read_file($orderJsonPath);
                    $orderJsonData = json_clean_decode($orderJson, true);
                    foreach ($artworkApprovalJsonData['design_product_data'] as $designProductData) {
                        $designUrls = [];
                        foreach ($designProductData['design_urls'] as $designKey => $value) {
                            $tempDesignUrl = [
                                'img' => $value,
                                'is_designed' => ($artworkApprovalJsonData['sides'][$designKey]['is_designed'] == 1) ? 1: 0,
                                'side_name' => $artworkApprovalJsonData['sides'][$designKey]['side_name'],
                            ];
                            array_push($designUrls, $tempDesignUrl);
                        }
                        foreach ($designProductData['variant_id'] as $varKey => $variantIdArr) {
                            $variantId = $variantIdArr;
                            $variantArr = array_filter($orderJsonData['order_details']['order_items'], function ($item) use ($variantId) {
                                return $item['variant_id'] == $variantId;
                            });
                            $variantArr = $variantArr[array_keys($variantArr)[0]];
                            $tempProductData = [
                                'product_name' => $variantArr['product_name'],
                                'sku' => $variantArr['product_sku'],
                                'preview_url' => $designUrls,
                                'attributes' => $variantArr['attributes'],
                                'quantity' => $variantArr['quantity'],
                                'price' => $variantArr['price'],
                                'currency' => $orderJsonData['order_details']['currency'],
                            ];
                            array_push($productData, $tempProductData);
                        }
                    }
                    $returnData = [
                        'product_data' => $productData,
                        'artwork_data' => $finalDesignData,
                    ];
                    if (isset($type) && $type == 'customer_view') {
                        $productsControllerInit = new ProductsController();
                        $productDecorationArr = $productsControllerInit->getProductDetails($request, $response, ['id' => $artworkApprovalJsonData['product_info']['product_id']], 1);
                        $productDecorationArr = $productDecorationArr['data'];
                        $productInfo = [
                            'name' => $productDecorationArr['name'],
                            'description' => $productDecorationArr['description'],
                            'image' => $productDecorationArr['images'],
                        ];
                        $ordersControllerInit = new OrdersController();
                        $orderStoreResponse = $ordersControllerInit->getOrders($request, $response, ['id'=> $orderId]);
                        $orderData = [
                            'order_id' => $orderStoreResponse['order_details']['id'],
                            'order_number' => $orderStoreResponse['order_details']['order_number'],
                            'created_date' => $orderStoreResponse['order_details']['created_date'],
                            'customer_name' => $orderStoreResponse['order_details']['customer_first_name'].' '.$orderStoreResponse['order_details']['customer_last_name'],
                            'customer_email' => $orderStoreResponse['order_details']['billing']['email'],
                            'billing' => $orderStoreResponse['order_details']['billing'],
                            'shipping' => $orderStoreResponse['order_details']['shipping'],
                        ];
                        $returnData['order_data'] = $orderData;
                        $returnData['product_info'] = $productInfo;
                        $returnData['status'] = $artworkApprovalData['status'];
                        if ($artworkApprovalData['status'] == 0) {
                            $statusText = 'Artwork updated';
                            $statuSlug = 'artwork_updated';
                            $statusColor = '#cef6e6';
                        } elseif ($artworkApprovalData['status'] == 1) {
                            $statusText = 'Sent for approval';
                            $statuSlug = 'sent_for_approval';
                            $statusColor = '#d9f0ff';
                        } elseif($artworkApprovalData['status'] == 2) {
                            $statusText = 'Approved';
                            $statuSlug = 'approved';
                            $statusColor = '#aef5cf';
                        } elseif($artworkApprovalData['status'] == 3) {
                            $statusText = 'Rejected';
                            $statuSlug = 'rejected';
                            $statusColor = '#ffdfdf';
                        } else {
                            $statusText = '';
                            $statuSlug = '';
                            $statusColor = '';
                        }
                        $returnData['status_text'] = $statusText;
                        $returnData['status_slug'] = $statuSlug;
                        $returnData['status_color'] = $statusColor;
                    }
                    $jsonResponse = [
                        'status' => 1,
                        'data' => $returnData,
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET: Sending mail for conversation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author diana@imprintnext.com
     * @date   09 Sept 2022
     * @return json response
     */
    public function sendConversationMail($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Conversation Mail', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        if (!empty($args['conv_id'])) {
            $conversationId = $args['conv_id'];
            $conversationsInit = new ArtworkApprovalConversations();
            $conversations = $conversationsInit->where('xe_id', $conversationId);
            $conversationData = $conversations->first();
            if (!empty($conversationData)) {
                $conversationData = $conversationData->toArray();
                $artworkAppId = $conversationData['order_artwork_id'];
                $senderType = $conversationData['user_type'];
               // $senderId = $conversationData['user_id'];
                $artworkApprovalInit = new ArtworkApproval();
                $artworkApprovalData = $artworkApprovalInit->where('xe_id', $artworkAppId);
                $artworkApprovalData = $artworkApprovalData->first()->toArray();
                $orderId = $artworkApprovalData['order_id'];
                //Get customer details
                $orderJsonPath = path('abs', 'order')  . $orderId . "/order.json";
                $orderJson = read_file($orderJsonPath);
                $orderJsonData = json_clean_decode($orderJson, true);
                $customerName = ($orderJsonData['order_details']['customer']['first_name'] != '') ? $orderJsonData['order_details']['customer']['first_name'].' '. $orderJsonData['order_details']['customer']['last_name'] : $orderJsonData['order_details']['customer']['user_email'];
                $customerEmail = $orderJsonData['order_details']['customer']['user_email'];
                $customerData = [];
                if ($senderType == 'customer') {
                    //Send mail to Agent/Superadmin
                    $subject = 'A new message sent by '. $customerName . ' - Order #'.$orderId;
                    $message = '<div>Hello,</div><div><br></div><div>A new message is sent by customer '.$customerName.' for order #'.$orderId.'.</div><div><br></div><div><b>Message:</b> '.$conversationData['message'].'</div><div><br></div>';
                } else {
                    //Send Mail to Customer
                    $token = 'order_id=' . $orderId. '&order_artwork_id='.$artworkAppId.'&store_id='. $getStoreDetails['store_id'];
                    $token = base64_encode($token);
                    $publicUrl = API_URL . 'quotation/art-work?token=' . $token . '&artwork_type=order';
                    
                    $subject = 'A new message sent by Admin - Order #'.$orderId;
                    $message = '<div>Hello '.$customerName.',</div><div><br></div><div>A new message is sent by Admin for Order #'.$orderId.'.</div><div><br></div><div><b>Message:</b> '.$conversationData['message'].'</div><div><br></div><div>You can click on the link below to see the status of your quotation</div><div>'.$publicUrl.'</div><div><br></div>';

                    $customerData = [
                        'name' => $customerName,
                        'email' => $customerEmail,
                    ];
                }
                //Attachment files
                $conversationFileInit = new ArtworkApprovalConvFiles();
                $file = $conversationFileInit->where('conv_id', $conversationId);
                $fileData = $file->get();
                $attachments = [];
                if (!empty($fileData)) {
                    $fileData = $fileData->toArray();
                    foreach ($fileData as $files) {
                        $filePath = path('abs', 'order') . 'conversation/'.$files['file'];
                        array_push($attachments, $filePath);
                    }
                }
                $templateData = [
                    'subject' => $subject,
                    'message' => $message,
                ];
                $mailStatus = $this->sendEmail($templateData, $customerData, $attachments);
                if ($mailStatus['status'] == 1) {
                    $jsonResponse = [
                        'status' => 1,
                        'message' => message('Conversation Mail', 'done'),
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Change quotation conversation seen flag
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author diana@imprintnext.com
     * @date   29 Nov 2020
     * @return json response
     */
    public function changeConversationSeenFlag($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Conversation Seen Flag', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        $artworkId = to_int($allPostPutVars['artwork_id']);
        if ($artworkId != '') {
            $conversationsInit = new ArtworkApprovalConversations();
            $conversationsInit->where('order_artwork_id', $artworkId)
                ->update(['seen_flag' => '0']);
            $jsonResponse = [
                'status' => 1,
                'message' => message('Conversation Seen Flag', 'done'),
            ];
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET: Get order item attribute details
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author diana@imprintnext.com
     * @date   15 Dec 2023
     * @return json response wheather data is saved or any error occured
     */
    public function getOrderItemAttributes($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Artwork design', 'error'),
        ];
        
        if (!empty($args['id'])) {
            $getStoreDetails = get_store_details($request);
            $storeId = $getStoreDetails['store_id'] ? $getStoreDetails['store_id']: 1;
            $orderId = to_int($args['id']);
            $storeOrdersControllerInit = new StoreOrdersController();
            $storeRes = $storeOrdersControllerInit->orderItemAttribute($orderId, $storeId);
            $jsonResponse = [
                'status' => 1,
                'data' => $storeRes,
            ];
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * Function to change the order artwork status
     *
     * @param $orderId  Order id
     *
     * @author diana@imprintnext.com
     * @date   13 June 2024
     * @return boolean 
     */
    private function changeOrderArtworkStatus ($orderId) {
        //Update the order artwork status as Approved if all the artwork were approved
        //Get all the order item status
        $artworkApprovalInit = new ArtworkApproval();
        $ordersInit = new Orders();
        $getlineItem = $artworkApprovalInit->where('order_id', $orderId);
        $lineItemCount = $getlineItem->count();
        //For approve status
        $getLineItemApproveStatus = $artworkApprovalInit->where('order_id', $orderId)
            ->where(
           function($query) {
             return $query
                    ->where('status', 2)
                    ->orWhere('status', 0);
            });
        $lineItemApproveStatusCount = $getLineItemApproveStatus->count();
        if ($lineItemCount == $lineItemApproveStatusCount) {
            $getArtworkStatus = $ordersInit->where('order_id', $orderId);
            if ($getArtworkStatus->count() > 0) {
                $ordersInit->where('order_id', $orderId)
                    ->update(['artwork_status' => 'approved']);
            }
        } else {
            $getArtworkStatus = $ordersInit->where('order_id', $orderId);
            if ($getArtworkStatus->count() > 0) {
                $ordersInit->where('order_id', $orderId)
                    ->update(['artwork_status' => 'pending']);
            }
        }
        return true;
    }
    
}