<?php
/**
 * Manage Quotations
 *
 * PHP version 5.6
 *
 * @category  Quotations
 * @package   Production_Hub
 * @author    Debashri Bhakat <debashrib@riaxe.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 */

namespace App\Modules\Quotations\Controllers;

use App\Components\Controllers\Component as ParentController;
use App\Modules\Orders\Controllers\OrderDownloadController;
use App\Modules\Orders\Controllers\OrdersController;
use App\Modules\Quotations\Models\ProductionHubSetting;
use App\Modules\Quotations\Models\ProductionStatus;
use App\Modules\Quotations\Models\ProductionTags;
use App\Modules\Quotations\Models\QuotationConversationFiles;
use App\Modules\Quotations\Models\QuotationConversations;
use App\Modules\Settings\Models\QuotationDynamicForm;
use App\Modules\Quotations\Models\QuotationDynamicFormAttributes;
use App\Modules\Quotations\Models\QuotationInternalNote;
use App\Modules\Quotations\Models\QuotationInternalNoteFiles;
use App\Modules\Quotations\Models\QuotationItemFiles;
use App\Modules\Quotations\Models\QuotationItems;
use App\Modules\Quotations\Models\QuotationItemVariants;
use App\Modules\Quotations\Models\QuotationLog;
use App\Modules\Quotations\Models\QuotationPayment;
use App\Modules\Quotations\Models\QuotationRequestDetails;
use App\Modules\Quotations\Models\QuotationRequestFormValues;
use App\Modules\Quotations\Models\Quotations;
use App\Modules\Quotations\Models\QuotationTagRelation;
use App\Modules\Customers\Controllers\CustomersController;
use App\Components\Models\ProductionAbbriviations;
use App\Modules\Quotations\Controllers\QuotationPaymentController;
use App\Modules\Products\Models\AppUnit;
use App\Modules\DecorationAreas\Models\PrintArea;
use App\Modules\Users\Models\User;
use App\Modules\Products\Controllers\ProductDecorationsController;
use App\Modules\Products\Controllers\ProductsController;
use Illuminate\Database\Capsule\Manager as DB;
use App\Modules\Orders\Models\Orders;
use ComponentStoreSpace\Controllers\StoreComponent;
use App\Modules\Quotations\Models\TeamJerseyData;
use App\Modules\Quotations\Models\QuoteStickerData;
use App\Modules\Integration\Models\PluginSettings;
use App\Modules\Integration\Controllers\IntegrationController;
use App\Modules\Integration\Controllers\QuickBookController;
use App\Modules\Products\Models\ProductSide;
use App\Modules\Settings\Models\Currency;
use App\Modules\Settings\Models\Language;
use App\Modules\Products\Models\ProductSetting;
use App\Modules\Products\Models\ProductImageSettingsRel;
use App\Modules\Products\Models\ProductImageSides;
use App\Modules\Products\Models\ProductImage;

/**
 * Quotations Controller
 *
 * @category Quotations
 * @package  Production_Hub
 * @author   Debashri Bhakat <debashrib@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 */
class QuotationController extends ParentController
{
    /**
     * GET: Quotation Id
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   27 mar 2020
     * @return json response
     */
    public function getQuoteId($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Id', 'error'),
        ];
        $quotationInit = new Quotations();
        $lastQuoteId = '';
        $lastRecord = $quotationInit->select('quote_id')->latest()->first();
        if (!empty($lastRecord)) {
            $lastQuoteId = $lastRecord->quote_id;
        }
        //Generate Quote Id
        $quoteId = $this->generateQuoteId($request, $lastQuoteId);
        if ($quoteId != '') {
            $jsonResponse = [
                'status' => 1,
                'data' => $quoteId,
            ];
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    private function generateQuoteId($request, $lastQuoteId = '')
    {
        //Get quotation setting data
        $getStoreDetails = get_store_details($request);
        $settingInit = new ProductionHubSetting();
        $settingData = $settingInit->select('setting_value', 'flag')
            ->where([
                'module_id' => 1,
                'setting_key' => 'quote_id',
                'store_id' => $getStoreDetails['store_id'],
            ]);
        if ($settingData->count() > 0) {
            $settingDataArr = $settingData->first()->toArray();
            $settingValue = json_clean_decode($settingDataArr['setting_value'], true);
            $preFix = $settingValue['prefix'];
            $startingNum = $settingValue['starting_number'];
            $postFix = $settingValue['postfix'];
            $flag = 0;
            if ($settingDataArr['flag'] == 1 && $flag == 1) {
                $flag = 1;
                $newQuoteId = $preFix . $startingNum . $postFix;
            } elseif ($lastQuoteId == '') {
                $newQuoteId = $preFix . $startingNum . $postFix;
            } else {
                $postFixLen = strlen($postFix);
                $preFixLen = strlen($preFix);
                if ($preFixLen > 0) {
                    if(0 === strpos($lastQuoteId, $preFix)){
                        $withoutPrefix = substr($lastQuoteId, strlen($preFix)).'';
                    }
                } else {
                    $withoutPrefix = $lastQuoteId;
                }
                if ($postFixLen > 0) {
                    $quoteNum = substr($withoutPrefix, 0, -$postFixLen);
                } else {
                    $quoteNum = $withoutPrefix;
                }
                $newQuoteNum = $quoteNum + 1;
                $newQuoteId = $preFix . $newQuoteNum . $postFix;
            }
            $quotationInit = new Quotations();
            $quoteData = $quotationInit->where(
                [
                    'store_id' => $getStoreDetails['store_id'],
                    'quote_id' => $newQuoteId,
                ]);
            if ($quoteData->count() > 0) {
                return $this->generateQuoteId($request, $newQuoteId);
            } else {
                return $newQuoteId;
            }
        }
    }

    /**
     * GET: Quotation Listing
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   24 Mar 2020
     * @return json response
     */
    public function getQuotationList($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        // Collect all Filter columns from url
        $page = $request->getQueryParam('page');
        $perpage = $request->getQueryParam('perpage');
        $sortBy = $request->getQueryParam('sortby');
        $order = $request->getQueryParam('order');
        $keyword = $request->getQueryParam('keyword');
        $customerId = $request->getQueryParam('customer_id');
        $tagId = $request->getQueryParam('tag_id');
        $from = $request->getQueryParam('from');
        $to = $request->getQueryParam('to');
        $statusId = $request->getQueryParam('status_id');
        $statusId = json_clean_decode($statusId, true);
        $agentId = $request->getQueryParam('agent_id');
        $paymentStatus = $request->getQueryParam('payment_status');
        $loginId = $request->getQueryParam('login_id');
        $quoteSource = $request->getQueryParam('quote_source');
        $archiveStatus = $request->getQueryParam('archive_status');
        $isUserAccount = $request->getQueryParam('is_user_account');

        $quotationInit = new Quotations();
        $conversationInit = new QuotationConversations();
        $getQuotations = $quotationInit->join(
            'production_status',
            'quotations.status_id',
            '=',
            'production_status.xe_id')
            ->select('quotations.xe_id as id', 'quotations.quote_id', 'quotations.customer_id', 'quotations.quote_total as total_amount', 'quotations.status_id', 'quotations.agent_id', 'quotations.created_at as created_date', 'quotations.draft_flag', 'quotations.invoice_id', 'quotations.request_payment', 'quotations.request_date', 'production_status.status_name as quote_status', 'production_status.slug', 'production_status.color_code', 'quotations.customer_name', 'quotations.customer_email', 'quotations.customer_availability', 'quotations.order_id', 'quotations.is_ready_to_send', 'quotations.quote_source', 'quotations.currency_id', DB::raw("(SELECT count(xe_id) FROM `quote_items` WHERE quote_id = quotations.xe_id) as total_item"))
            ->where('quotations.store_id', $getStoreDetails['store_id']);
        $withoutFilterCount = $getQuotations->count();
        //$getQuotations->whereIn('quotations.customer_id', $allCustomerIds);
        

        //Search by quote title and quote id
        if (isset($keyword) && $keyword != "") {
            $getQuotations->where('quotations.title', 'LIKE', '%' . $keyword . '%')
                ->orWhere('quotations.quote_id', 'LIKE', '%' . $keyword . '%');
        }
        //Filter by customer
        if (isset($customerId) && $customerId > 0) {
            $getQuotations->where('quotations.customer_id', $customerId);
        }
        //Filter by archive status
        if (isset($archiveStatus) && $archiveStatus == 1) {
            $getQuotations->where('quotations.archive_status', 1);
        } else {
            $getQuotations->where('quotations.archive_status', 0);
            if (isset($isUserAccount) && $isUserAccount == 1) {
                $getQuotations->Where(function ($query) {
                    $query->where('quotations.draft_flag', 0)
                    ->orWhere('quote_source', 'tool'); 
                });
                if (isset($statusId) && count($statusId) > 0) {
                    $getQuotations->whereIn('quotations.status_id', $statusId);
                }
            } else {
                //Filter by status
                if (isset($statusId) && count($statusId) > 0) {
                    $getQuotations->whereIn('quotations.status_id', $statusId);
                } else {
                    //Get Order status id
                    $statusInit = new ProductionStatus();
                    $orderStatusId = 0;
                    $getOrderedStatusData = $statusInit->select('xe_id')->where([
                        'store_id' => $getStoreDetails['store_id'], 
                        'slug' => 'ordered',
                        'module_id' => 1
                    ]);

                    if ($getOrderedStatusData->count() > 0) {
                       $getOrderedStatusDataArr = $getOrderedStatusData->first(); 
                       $getOrderedStatusDataArr = json_clean_decode($getOrderedStatusDataArr, true);
                       $orderStatusId = $getOrderedStatusDataArr['xe_id'];
                    }
                    $getQuotations->whereNotIn('quotations.status_id', [$orderStatusId]);
                }
            }
        }
        //Filter by agent
        if (isset($agentId) && $agentId > 0) {
            $getQuotations->where('quotations.agent_id', $agentId);
        }
        //Filter by login type
        if (isset($loginId) && $loginId > 0) {
            $getQuotations->where('quotations.agent_id', $loginId);
        }
        //Filter by tag
        if (isset($tagId) && $tagId != "") {
            $tagSearch = json_clean_decode($tagId, true);
            $getQuotations->whereHas(
                'quotationTag', function ($q) use ($tagSearch) {
                    return $q->whereIn('tag_id', $tagSearch);
                }
            );
        }
        //Filter by date
        if (isset($from) && isset($to)) {
            if ($from != "" && $to == '') {
                //Filter by only from date
                $getQuotations->where('quotations.created_at', '>=', $from);
            } elseif ($from == "" && $to != '') {
                $to = date('Y-m-d H:i:s', strtotime($to . ' +1 day'));
                //Filter by only to date
                $getQuotations->where('quotations.created_at', '<=', $to);
            } elseif (!empty($from) && !empty($to)) {
                $to = date('Y-m-d H:i:s', strtotime($to . ' +1 day'));
                //Filter by from and to date
                $getQuotations->where('quotations.created_at', '>=', $from)
                    ->where('quotations.created_at', '<=', $to);
            }
        }
        //Filter by quote source
        if (isset($quoteSource) && $quoteSource != '') {
            $getQuotations->where('quotations.quote_source', $quoteSource);
        }

        // Total records including all filters
        $getTotalPerFilters = $getQuotations->count();
        $offset = 0;
        if (isset($page) && $page != "") {
            $totalItem = empty($perpage) ? PAGINATION_MAX_ROW : $perpage;
            $offset = $totalItem * ($page - 1);
            $getQuotations->skip($offset)->take($totalItem);
        }
        // Sorting by column name and sord order parameter
        if (isset($sortBy) && $sortBy != "" && isset($order) && $order != "") {
            $getQuotations->orderBy('quotations.' . $sortBy, $order);
        }

        $userInit = new User();
        $agentData = $userInit->select('xe_id as id', 'name')->where('store_id', $getStoreDetails['store_id']);
        $agentListArr = json_clean_decode($agentData->get(), true);
        if ($getTotalPerFilters > 0) {
            $getQuotationData = $getQuotations->get();
            $quotationRes = [];
            foreach ($getQuotationData as $quotationData) {
                $cusId = $quotationData['customer_id'];
                $customerName = $quotationData['customer_name'];
                $customerEmail = $quotationData['customer_email'];
                if ($cusId != '') {
                    if ($customerName == '' && $customerEmail == '') {
                        if ($quotationData['customer_availability'] == 0) {
                            $customersControllerInit = new CustomersController();
                            $customerDetails = $customersControllerInit->getQuoteCustomerDetails($cusId, $getStoreDetails['store_id'], '');
                            if (!empty($customerDetails)) {
                                $customerName = $customerDetails['customer']['name'];
                                $customerEmail = $customerDetails['customer']['email'];
                            }
                        } else {
                            $customerName = 'No customer';
                            $customerEmail = 'No customer';
                        }
                    }
                } else {
                    $customerName = ' ';
                    $customerEmail = ' ';
                }
                
                $newQuoteArr = $quotationData;
                $newQuoteArr['customer_name'] = ($customerName != '') ? $customerName : $customerEmail;
                $newQuoteArr['edit_mode'] = ($customerName == 'No customer') ? false : true;
                // For due date
                $paymentInit = new QuotationPayment();
                $paymentData = $paymentInit->select('xe_id', 'payment_amount', 'payment_status')
                    ->where([
                        'quote_id' => $newQuoteArr['id'],
                        'payment_status' => 'paid'
                    ])->sum('payment_amount');
                $comPaidAmount = ($paymentData > 0) ? $paymentData : 0;
                $comPaidAmount = number_format($comPaidAmount, 2, '.', '');
                $newQuoteArr['due_amount'] = $newQuoteArr['total_amount'] - $comPaidAmount;
                $newQuoteArr['payment_status'] = 'pending';
                if ($newQuoteArr['due_amount'] == 0) {
                    $newQuoteArr['payment_status'] = 'paid';
                }
                //Calculate Paid payment percentage
                $percentage = 0;
                if ($newQuoteArr['total_amount'] != '' && $newQuoteArr['total_amount'] > 0) {
                    $percentage = ($comPaidAmount / $newQuoteArr['total_amount']) * 100;
                }
                $newQuoteArr['paid_percentage'] = $percentage;

                //Public Link
                $token = 'quote_id=' . $newQuoteArr['id'].'&store_id='.$getStoreDetails['store_id'];
                $token = base64_encode($token);
                $url = 'quotation/quotation-approval?token=' . $token;
                $newQuoteArr['public_url'] = API_URL . $url;
                //Get conversation unseen count
                $conversationCount = $conversationInit->where(['quote_id' => $newQuoteArr['id'], 'seen_flag' => '1'])->count();
                $newQuoteArr['conversation_unseen_count'] = $conversationCount;
                //Get Agent name
                if ($quotationData['agent_id'] != '') {
                    $agentId = $quotationData['agent_id'];
                    $agentArr = array_filter($agentListArr, function ($item) use ($agentId) {
                        return $item['id'] == $agentId;
                    });
                    $agentArr = $agentArr[array_keys($agentArr)[0]];
                }
                $newQuoteArr['agent_name'] = $quotationData['agent_id'] != '' ? $agentArr['name'] : '';
                $newQuoteArr['request_payment'] = ($newQuoteArr['request_payment'] == null) ? '0' : $newQuoteArr['request_payment'];
                //get order number 
                $orderNumber = '';
                if ($newQuoteArr['order_id'] != '' && $newQuoteArr['order_id'] > 0) {
                    //Get Order number
                    $ordersInit = new Orders;
                    $orders = $ordersInit->select('order_number')->where('order_id', $newQuoteArr['order_id']);
                    if ($orders->count() > 0) {
                        $orderData = json_clean_decode($orders->first(), true);
                        $orderNumber = $orderData['order_number'];
                    }
                }
                $newQuoteArr['order_number'] = ($orderNumber != '') ? $orderNumber : $newQuoteArr['order_id']; 
                unset(
                    $newQuoteArr['status_id']
                );
                //Get currency 
                $currencyId = $newQuoteArr['currency_id'];
                $newQuoteArr['currency'] = $this->getUsedCurrency($currencyId, $getStoreDetails['store_id']);
                //Filter by Payment Status
                if (isset($paymentStatus) && $paymentStatus != '') {
                    if ($newQuoteArr['payment_status'] == $paymentStatus) {
                        array_push($quotationRes, $newQuoteArr);
                    }

                } else {
                    array_push($quotationRes, $newQuoteArr);
                }
            }
            $jsonResponse = [
                'status' => 1,
                'records' => count($quotationRes),
                'total_records' => $getTotalPerFilters,
                'without_filter_count' => ($withoutFilterCount > 0) ? true : false,
                'data' => $quotationRes,
            ];
        }  else {
            $jsonResponse = [
                'status' => 1,
                'without_filter_count' => ($withoutFilterCount > 0) ? true : false,
                'message' => message('Quotation', 'not_found'),
                'data' => []
            ];
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Save Quotation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   24 Mar 2020
     * @return json response wheather data is saved or any error occured
     */
    public function saveQuotation($request, $response)
    {
        $getStoreDetails = get_store_details($request);
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        $getAllFormData = $quoteData = [];
        $allPostPutVars['store_id'] = $getStoreDetails['store_id'];
        $quotationInit = new Quotations();
        // Save Quotation Data
        if (isset($allPostPutVars['quote_data']) && $allPostPutVars['quote_data'] != "") {
            $getAllFormData = json_clean_decode($allPostPutVars['quote_data'], true);
            $eventType = isset($getAllFormData['event_type']) && $getAllFormData['event_type'] != '' ? $getAllFormData['event_type'] : 0;
            //Check for quote_id
            $quoteIdData = $quotationInit->where(
                [
                    'quote_id' => $getAllFormData['quote_id'],
                    'store_id' => $getStoreDetails['store_id'],
                ]);
            if ($quoteIdData->count() > 0) {
                $lastRecord = $quotationInit->select('quote_id')->latest()->first();
                if (!empty($lastRecord)) {
                    //Generate Quote Id
                    $quoteId = $this->generateQuoteId($request, $lastRecord->quote_id);
                    $getAllFormData['quote_id'] = $quoteId;
                }
            }

            $quoteData = $getAllFormData;
            unset($quoteData['tags'], $quoteData['items']);
            //Get customer data
            if (!empty($getAllFormData['customer_id']) && $getAllFormData['customer_id'] != '' && $getAllFormData['customer_id'] > 0) {
                $customersControllerInit = new CustomersController();
                $customerDetails = $customersControllerInit->getQuoteCustomerDetails($getAllFormData['customer_id'], $getStoreDetails['store_id'], '');
                if (!empty($customerDetails)) {
                    $customerName = $customerDetails['customer']['name'];
                    $customerEmail = $customerDetails['customer']['email'];
                }
                $quoteData += [
                    'customer_name' => (isset($customerName)) ? $customerName : '',
                    'customer_email' => (isset($customerEmail)) ? $customerEmail : '',
                ];
            }
            //Get Open status id
            $statusInit = new ProductionStatus();
            $getStatusData = $statusInit->select('xe_id')->where([
                'store_id' => $getStoreDetails['store_id'], 
                'slug' => 'open',
                'module_id' => 1
            ]);
            if ($getStatusData->count() > 0) {
               $getStatusDataArr = $getStatusData->first(); 
               $getStatusDataArr = json_clean_decode($getStatusDataArr, true);
            }
            $quoteData += [
                'store_id' => $getStoreDetails['store_id'],
                'status_id' => $getStatusDataArr['xe_id'],
            ];
            if ($quoteData['agent_id'] == '') {
                $quoteData['agent_id'] = 0;
            }
            //If quotation is created by agent
            if ($quoteData['created_by'] == 'agent') {
                $quoteData['agent_id'] = $quoteData['created_by_id'];
            }
            //Save currency id
            $currencyData = $this->getUsedCurrency('', $getStoreDetails['store_id']);
            $quoteData['currency_id'] = $currencyData['id'];
            //Check quotation is ready to send to customer or not
            if (!empty($getAllFormData['items']) 
                &&  !empty($getAllFormData['customer_id']) 
                && $getAllFormData['customer_id'] != '' 
                && $getAllFormData['customer_id'] > 0
                && $getAllFormData['title'] != ''
            ) {
                $quoteData += [
                    'is_ready_to_send' => 1,
                ];
            }
            $quoteData['quote_total'] = round($quoteData['quote_total'], 2);
            $quoteData['created_at'] = date_time(
                        'today', [], 'string'
                    );
            $quotation = new Quotations($quoteData);
            if ($quotation->save()) {
                $quotationLastId = $quotation->xe_id;
                //Change the quotation setting flag value after quotation is created
                $this->changeSettingFlagValue($getStoreDetails['store_id'], 1, 'quote_id'); 
                // Save tags
                $tagArr = $getAllFormData['tags'];
                $this->saveQuoteTags($quotationLastId, $tagArr);

                // Save items
                $itemsArr = $getAllFormData['items'];
                $this->saveQuotationItems($quotationLastId, $itemsArr, $request, $response);
                //Adding to quote log
                if ($eventType == 2) {
                    //Save and send to customer
                    $this->sendToCustomer($request, $response, ['id' => $quotationLastId], 1);
                    $description = 'Quotation is created and sent to customer';
                } elseif ($eventType == 4) {
                    //Save and download quotation
                    $description = 'Quotation is created and downloaded';
                } else{
                    $description = 'Quotation is created';
                }
                $logData = [
                    'quote_id' => $quotationLastId,
                    'title' => 'Quotation created',
                    'description' => $description,
                    'user_type' => $quoteData['created_by'],
                    'user_id' => $quoteData['created_by_id'],
                    'created_date' => date_time(
                        'today', [], 'string'
                    )
                ];
                $this->addingQuotationLog($logData);
                $jsonResponse = [
                    'status' => 1,
                    'quote_id' => $quotationLastId,
                    'type' => ($eventType == 0) ? 'draft' : 'send', 
                    'message' => message('Quotation', 'saved'),
                ];

                $pluginsInit = new PluginSettings();
                $printfulStatus = $pluginsInit->where('catalog_code', 'quickbooks')
                ->where('status', 1);
                $pluginCountprint = $printfulStatus->count();
                if($pluginCountprint > 0)
                {
                    $quickBookObj = new QuickBookController();
                    $quickBookObj->createEstimate($request, $response,$allPostPutVars,$quotationLastId);                    
                }

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

    /**
     * POST: Update Quotation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   26 Mar 2020
     * @return json response wheather data is updated or any error occured
     */
    public function updateQuotation($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $allPostPutVars = $updateData = json_clean_decode($allPostPutVars['quote_data'], true);
        $eventType = isset($allPostPutVars['event_type']) && $allPostPutVars['event_type'] != '' ? $allPostPutVars['event_type'] : 0;

        if (!empty($args['id'])) {
            $quotationId = to_int($args['id']);
            $quotationInit = new Quotations();
            $getOldQuotation = $quotationInit->where('xe_id', $quotationId);
            if ($getOldQuotation->count() > 0) {
                unset(
                    $updateData['tags'],
                    $updateData['items'],
                    $updateData['event_type'],
                    $updateData['user_type'],
                    $updateData['user_id'],
                    $updateData['created_by'],
                    $updateData['created_by_id'],
                    $updateData['quote_source']
                );
                if ($eventType == 2) {
                    //set flag as 0:send to customer
                    $updateData['draft_flag'] = "0";
                }
                //Get customer data 
                if (!empty($updateData['customer_id']) && $updateData['customer_id'] != '' && $updateData['customer_id'] > 0) {
                    $customersControllerInit = new CustomersController();
                    $customerDetails = $customersControllerInit->getQuoteCustomerDetails($updateData['customer_id'], $getStoreDetails['store_id'], '');
                    if (!empty($customerDetails)) {
                        $customerName = $customerDetails['customer']['name'];
                        $customerEmail = $customerDetails['customer']['email'];
                    }
                    $updateData += [
                        'customer_name' => (isset($customerName)) ? $customerName : '',
                        'customer_email' => (isset($customerEmail)) ? $customerEmail : ''
                    ];
                }
                //Check quotation is ready to send to customer or not
                if (!empty($allPostPutVars['items']) 
                    &&  !empty($updateData['customer_id']) 
                    && $updateData['customer_id'] != '' 
                    && $updateData['customer_id'] > 0
                    && $updateData['title'] != ''
                ) {
                    $updateData += [
                        'is_ready_to_send' => 1,
                    ];
                } else {
                    $updateData += [
                        'is_ready_to_send' => 0,
                    ];
                }
                $updateData['quote_total'] = round($updateData['quote_total'], 2);
                $quotationInit->where('xe_id', $quotationId)
                    ->update($updateData);
                $description = 'Quotation is updated';
                // Save tags
                $tagArr = $allPostPutVars['tags'];
                $this->saveQuoteTags($quotationId, $tagArr);
                // Save items
                $itemsArr = $allPostPutVars['items'];
                $this->saveQuotationItems($quotationId, $itemsArr, $request, $response);

                if ($eventType == 2) {
                    //Save and send to customer
                    $this->sendToCustomer($request, $response, ['id' => $quotationId], 1);
                    $description = 'Quotation is updated and sent to customer';
                }
                //Check quotation is ready to send to customer or not
                if (!empty($itemsArr) 
                    &&  !empty($updateData['customer_id']) 
                    && $updateData['customer_id'] != '' 
                    && $updateData['customer_id'] > 0
                    && $updateData['title'] != ''
                ) {
                    $quotationInit->where('xe_id', $quotationId)
                    ->update([
                        'is_ready_to_send' => 1,
                    ]);
                } else {
                    $quotationInit->where('xe_id', $quotationId)
                    ->update([
                        'is_ready_to_send' => 0,
                    ]);
                }
                $logData = [
                    'quote_id' => $quotationId,
                    'title' => 'Quotation updated',
                    'description' => $description,
                    'user_type' => $allPostPutVars['user_type'],
                    'user_id' => $allPostPutVars['user_id'],
                    'created_date' => date_time(
                        'today', [], 'string'
                    )
                ];
                $this->addingQuotationLog($logData);
                $jsonResponse = [
                    'status' => 1,
                    'quote_id' => $quotationId,
                    'type' => ($eventType == 0) ? 'update' : 'send', 
                    'message' => message('Quotation', 'updated'),
                ];

                $pluginsInit = new PluginSettings();
                $printfulStatus = $pluginsInit->where('catalog_code', 'quickbooks')
                ->where('status', 1);
                $pluginCountprint = $printfulStatus->count();
                if($pluginCountprint > 0)
                {
                    $quickBookObj = new QuickBookController();
                    $quickBookObj->updateEstimate($request, $response,$allPostPutVars,$quotationId);                    
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * Save tags w.r.t Quotation
     *
     * @param $quotationId  Quotation ID
     * @param $tags         Multiple Tags
     *
     * @author debashrib@riaxe.com
     * @date   25th Mar 2020
     * @return boolean
     */
    private function saveQuoteTags($quotationId, $tags)
    {
        if (!empty($tags) && count($tags) > 0) {
            $tagsRelInit = new QuotationTagRelation();
            // Delete from relation table in case of update
            $quoteTags = $tagsRelInit->where('quote_id', $quotationId);
            $quoteTags->delete();
            $tagArr = [];
            foreach ($tags as $tagData) {
                $tagArr = [
                    'quote_id' => $quotationId,
                    'tag_id' => $tagData,
                ];
                $tagsRelInit->insert($tagArr);
            }
            return true;
        }
        return false;
    }

    /**
     * Save items w.r.t Quotation
     *
     * @param $quotationId  Quotation ID
     * @param $items        Multiple Items
     *
     * @author debashrib@riaxe.com
     * @date   25th Mar 2020
     * @return boolean
     */
    private function saveQuotationItems($quotationId, $items, $request, $response)
    {
        if ($quotationId > 0) {
            // Delete items and its details
            $this->deleteQuoteItems($quotationId);
            // Save Quotation Items
            if (!empty($items) && count($items) > 0) {
                // Delete items and its details
                $this->deleteQuoteItems($quotationId);
                $itemsArr = [];
                $itemJsonArr = [];
                foreach ($items as $itemKey => $itemsData) {
                    $itemsArr = $itemsData;
                    $itemsArr['quote_id'] = $quotationId;
                    $itemsArr['product_type'] = isset($itemsData['type']) ? $itemsData['type'] : '';
                    unset($itemsArr['product_variant'], $itemsArr['type']);
                    $itemsInit = new QuotationItems($itemsArr);
                    if ($itemsInit->save()) {
                        $itemLastId = $itemsInit->xe_id;
                        $itemJsonArr[$itemLastId] = $itemsData['product_deco_data'];
                        $productVariant = $itemsData['product_variant'];
                        if ($itemsData['artwork_type'] == 'uploaded_file') {
                            //Get Upload Designs and Data
                            $uploadDesignsArr = $itemsData['upload_designs'];
                            foreach ($uploadDesignsArr as $designs) {
                                $decorationAreasArr = $designs['decoration_area'];
                                foreach ($decorationAreasArr as $decorationAreas) {
                                    //upload Design
                                    $designFileName = $itemsData['product_id'] . '_' . $designs['side_id'] . '_' . $decorationAreas['decoration_area_id'] . '_'. $decorationAreas['decoration_settings_id'] . '_' .$itemKey. '_design';
                                    $previewFileName = $itemsData['product_id'] . '_' . $designs['side_id'] . '_' . $decorationAreas['decoration_area_id'] . '_'. $decorationAreas['decoration_settings_id'] . '_' .$itemKey. '_preview';
                                    $designFile = do_upload(
                                        $designFileName,
                                        path('abs', 'quotation') . $quotationId . '/' . $itemLastId . '/' . $designs['side_id'] . '/', [],
                                        'string'
                                    );
                                    $previewFile = do_upload(
                                        $previewFileName,
                                        path('abs', 'quotation') . $quotationId . '/' . $itemLastId . '/' . $designs['side_id'] . '/', [],
                                        'string'
                                    );
                                    //Design height and width
                                    $extraDataValue = '';
                                    if ($decorationAreas['design_width'] != '' 
                                        && $decorationAreas['design_height'] != '') {
                                        $extraData = [
                                            'design_height' => $decorationAreas['design_height'],
                                            'design_width' => $decorationAreas['design_width']
                                        ];
                                        $extraDataValue = json_encode($extraData);
                                    }
                                    $saveFileData = [
                                        'item_id' => $itemLastId,
                                        'side_id' => $designs['side_id'],
                                        'decoration_area_id' => $decorationAreas['decoration_area_id'],
                                        'print_method_id' => $decorationAreas['print_method_id'],
                                        'decoration_settings_id' => $decorationAreas['decoration_settings_id'],
                                        'file' => $designFile,
                                        'preview_file' => $previewFile,
                                        'extra_data' => $extraDataValue
                                    ];
                                    $itemFilesInit = new QuotationItemFiles($saveFileData);
                                    $itemFilesInit->save();
                                }
                            }
                        }
                        //Save product variant
                        foreach ($productVariant as $variants) {
                            $variantData = [
                                'item_id' => $itemLastId,
                                'variant_id' => $variants['variant_id'],
                                'quantity' => $variants['quantity'],
                                'unit_price' => $variants['unit_price'],
                                'attribute' => !empty($variants['attribute']) ? json_encode($variants['attribute']) : '',
                                 'updated_price' => (isset($variants['updated_price']) && $variants['updated_price'] != '') ? $variants['updated_price'] : $variants['unit_price'],
                            ];
                            $variantsInit = new QuotationItemVariants($variantData);
                            $variantsInit->save();
                        }
                        //Save team jersey data
                        if (isset($itemsData['is_team_jersey']) && $itemsData['is_team_jersey'] == 1) {
                            $teamJerseyData = [
                                'quote_item_id' => $itemLastId,
                                'data' => json_clean_encode($itemsData['team_jersey_data']),
                            ];
                            $teamJerseyDataSave = new TeamJerseyData($teamJerseyData);
                            $teamJerseyDataSave->save();
                        }

                        //Save sticker data
                        if (isset($itemsData['is_sticker']) && $itemsData['is_sticker'] == 1) {
                            $teamJerseyData = [
                                'quote_item_id' => $itemLastId,
                                'data' => json_clean_encode($itemsData['sticker_data']),
                            ];
                            $stickerDataSave = new QuoteStickerData($teamJerseyData);
                            $stickerDataSave->save();
                        }
                    }
                }
                //Save item data in json file
                $filePath = path('abs', 'quotation') . $quotationId;
                if (!file_exists($filePath)) {
                    create_directory($filePath);
                }
                if (is_dir($filePath)) {
                    write_file(
                        $filePath . '/itemData.json', json_clean_encode($itemJsonArr)
                    );
                }
                return true;
            }
        }
        return false;
    }

    /**
     * Delete items files
     *
     * @param $quotationId   Quotation Id
     *
     * @author debashrib@riaxe.com
     * @date   26th Mar 2020
     * @return boolean
     */
    private function deleteQuoteItems($quotationId)
    {
        $itemsInit = new QuotationItems();
        $itemFilesInit = new QuotationItemFiles();
        $variantsInit = new QuotationItemVariants();
        $quoteItems = $itemsInit->where('quote_id', $quotationId);
        if ($quoteItems->count() > 0) {
            $getQuoteItems = $quoteItems->get();
            foreach ($getQuoteItems as $itemDetails) {
                if ($itemDetails['artwork_type'] == 'uploaded_file') {
                    // Fetch Items File details
                    $itemFilesDetails = $itemFilesInit->where(
                        'item_id', $itemDetails['xe_id']
                    )->get();
                    if (!empty($itemFilesDetails)) {
                        $itemFilesInit->where('item_id', $itemDetails['xe_id'])->delete();
                    }
                }
                //Delete data from variants table
                $variantsInit->where('item_id', $itemDetails['xe_id'])->delete();
            }
            //Delete quotation folder
            $quoteFilesPath = path('abs', 'quotation') . $quotationId;
            if (file_exists($quoteFilesPath)) {
                $this->deleteQuoteFolder($quoteFilesPath);
            }
            //Delete quotation folder
            $quoteFilesPath = path('abs', 'quotation') . $quotationId;
            if (file_exists($quoteFilesPath)) {
                $this->deleteQuoteFolder($quoteFilesPath);
            }
            $itemsInit->where('quote_id', $quotationId)->delete();
            return true;
        }
        return false;
    }

    /**
     * GET: Quotation Details
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     * @param $returnType     retun type
     *
     * @author debashrib@riaxe.com
     * @date   26 Mar 2020
     * @return json response
     */
    public function getQuotationDetails($request, $response, $args, $returnType = 0)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation', 'not_found'),
        ];
        $getStoreDetails = get_store_details($request);
        if (!empty($args['id'])) {
            $quotationId = to_int($args['id']);
            $customersControllerInit = new CustomersController();
            $quotationInit = new Quotations();
            $getQuotations = $quotationInit
                ->join('production_status', 'quotations.status_id', '=', 'production_status.xe_id')
                ->select('quotations.xe_id', 'quotations.store_id', 'quotations.quote_id', 'quotations.customer_id', 'quotations.shipping_id', 'quotations.agent_id', 'quotations.created_by', 'quotations.created_by_id', 'quotations.quote_source', 'quotations.title', 'quotations.description', 'quotations.ship_by_date', 'quotations.exp_delivery_date', 'quotations.is_artwork', 'quotations.is_rush', 'quotations.rush_type', 'quotations.rush_amount', 'quotations.discount_type', 'quotations.discount_amount', 'quotations.shipping_type', 'quotations.shipping_amount', 'quotations.tax_amount', 'quotations.design_total', 'quotations.quote_total', 'quotations.note', 'quotations.status_id', 'quotations.draft_flag', 'quotations.reject_note', 'quotations.invoice_id', 'quotations.order_id', 'quotations.request_payment', 'quotations.request_date', 'quotations.created_at', 'quotations.updated_at', 'production_status.status_name as quote_status', 'production_status.slug', 'production_status.color_code', 'quotations.customer_name', 'quotations.customer_email', 'quotations.customer_availability', 'quotations.order_id', 'quotations.is_ready_to_send', 'quotations.quotation_request_id', 'quotations.archive_status', 'quotations.currency_id')
                ->where(
                [
                    'quotations.store_id' => $getStoreDetails['store_id'],
                    'quotations.xe_id' => $quotationId,
                ]);
            $totalCounts = $getQuotations->count();
            if ($totalCounts > 0) {
                $notSetCustomerFlag = 0;
                $quotationData = $getQuotations->first();
                $quotationData = json_clean_decode($quotationData, true);
                // Get customer details
                $customerId = $quotationData['customer_id'];
                if ($customerId != '') {
                    $shippingId = ($quotationData['shipping_id'] != '') ? $quotationData['shipping_id'] : '';
                    $customerDetails = $customersControllerInit->getQuoteCustomerDetails($customerId, $getStoreDetails['store_id'], $shippingId, true);
                    if (!empty($customerDetails)) {
                        $quotationData['customer'] = $customerDetails['customer'];
                        //update customer name and email
                        if (($quotationData['customer_name'] == '' || ($quotationData['customer_name'] != $customerDetails['customer']['name'])) || ($quotationData['customer_email'] == '' || $quotationData['customer_email'] != $customerDetails['customer']['email'])) {
                            $updateData = [
                                'customer_name' => $customerDetails['customer']['name'],
                                'customer_email' => $customerDetails['customer']['email'],
                                'customer_availability' => 0
                            ];
                            $quotationInit->where('xe_id', $quotationId)
                                ->update($updateData);
                        }
                    } else {
                        $quotationData['customer'] = []; 
                        $updateData = [
                                'customer_name' => '',
                                'customer_email' => '',
                                'customer_availability' => 1
                            ];
                            $quotationInit->where('xe_id', $quotationId)
                                ->update($updateData);
                    }
                } else {
                    $notSetCustomerFlag = 1;
                    $quotationData['customer'] = []; 
                }
                // Get Tag
                $quotationData['tags'] = $this->getQuoteTags($quotationId);
                //Get Agent name
                if ($quotationData['agent_id'] != '') {
                    $userInit = new User();
                    $userData = $userInit->select('name')->where('xe_id', '=', $quotationData['agent_id'])->first();
                }
                $quotationData['agent_name'] = $quotationData['agent_id'] != '' ? $userData['name'] : '';
                //Get Payments Details
                $paymentInit = new QuotationPayment();
                $paymentData =  $paymentInit->select('payment_amount')->where([
                    'quote_id' => $quotationId,
                    'payment_status' => 'paid'
                ]);
                $paymentDataArr = $paymentData->get()->toArray();
                $comAmountArr = array_column($paymentDataArr, 'payment_amount');
                $comPaidAmount = array_sum($comAmountArr);
                $comPaidAmount = number_format($comPaidAmount, 2, '.', '');
                $quotationData['due_amount'] = $quotationData['quote_total'] - $comPaidAmount;
                //Calculate Paid payment percentage
                $percentage = 0;
                if ($quotationData['quote_total'] != '' && $quotationData['quote_total'] > 0) {
                    $percentage = ($comPaidAmount / $quotationData['quote_total']) * 100;
                }
                $quotationData['paid_percentage'] = $percentage;
                $quotationData['request_payment'] = ($quotationData['request_payment'] == null) ? '0' : $quotationData['request_payment'];
                $orderNumber = '';
                if ($quotationData['order_id'] != '' && $quotationData['order_id'] > 0) {
                    //Get Order number
                    $ordersInit = new Orders;
                    $orders = $ordersInit->select('order_number')->where('order_id', $quotationData['order_id']);
                    if ($orders->count() > 0) {
                        $orderData = json_clean_decode($orders->first(), true);
                        $orderNumber = $orderData['order_number'];
                    }
                }
                $quotationData['order_number'] = ($orderNumber != '') ? $orderNumber : $quotationData['order_id'];
                //Public Link
                $token = 'quote_id=' . $quotationData['xe_id'].'&store_id='.$getStoreDetails['store_id'];
                $token = base64_encode($token);
                $url = 'quotation/quotation-approval?token=' . $token;
                $quotationData['public_url'] = API_URL . $url;
                //Get quotation request data
                $quotationRequestData = [];
                if ($quotationData['quote_source'] == 'tool' || ($quotationData['quotation_request_id'] != '' && $quotationData['quotation_request_id'] > 0)) {
                    $quotationRequestFormValuesInit = new QuotationRequestFormValues();
                    $requestFormData = $quotationRequestFormValuesInit->select('form_key', 'form_value', 'form_type')->where('quote_id', $quotationData['quote_id']);
                    if ($requestFormData->count() > 0) {
                        $quotationRequestData = json_clean_decode($requestFormData->get(), true);
                        $finalQuotationRequestData = [];
                        foreach ($quotationRequestData as $requestData) {
                            $tempQuotationRequestData = $requestData;
                            $tempQuotationRequestData['is_file_type'] = false;
                            if ($requestData['form_type'] == 'file') {
                                $fileArr = explode(', ', $requestData['form_value']);
                                if (count($fileArr) > 1) {
                                    foreach ($fileArr as $multipleFile) {
                                        $multipleFileArr[] = path('read', 'quotation_request') . $multipleFile;
                                    }
                                    $tempQuotationRequestData['form_value'] = $multipleFileArr;

                                } else {
                                    $tempQuotationRequestData['form_value'] = path('read', 'quotation_request') . $fileArr[0];
                                }
                                $tempQuotationRequestData['is_file_type'] = true;
                            }
                            unset($tempQuotationRequestData['form_type']);
                            array_push($finalQuotationRequestData, $tempQuotationRequestData);
                        }
                    }
                }
                $quotationData['quotation_request_data'] = $finalQuotationRequestData;
                $quotationData['note'] = ($quotationData['note'] != '') ? $quotationData['note'] : '';
                $currencyId = $quotationData['currency_id'];
                $quotationData['currency'] = $this->getUsedCurrency($currencyId, $getStoreDetails['store_id']);
                if ($returnType == 1) {
                    return $quotationData;
                }

                if (!empty($quotationData)) {
                    if (!empty($customerDetails)) {
                        $jsonResponse = [
                            'status' => 1,
                            'data' => [
                                $quotationData,
                            ],
                        ];
                    } else {
                        if ($notSetCustomerFlag == 0) {
                            if ($quotationData['order_id'] != '') {
                                $jsonResponse = [
                                    'status' => 1,
                                    'data' => [
                                        $quotationData,
                                    ],
                                ];
                            } else {
                                $jsonResponse = [
                                    'status' => 0,
                                    'message' => 'Customer is deleted for this quotation'
                                ];
                            }
                        } else {
                            $jsonResponse = [
                                'status' => 1,
                                'data' => [
                                    $quotationData,
                                ],
                            ];
                        }
                    }
                }
            }
        }

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

    /**
     * Delete: Delete tag from the table if not
     * associate with quote
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   28 Mar 2020
     * @return Delete Json Status
     */
    public function deleteQuotationTag($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Tag', 'error'),
        ];
        if (!empty($args) && $args['id'] > 0) {
            $tagId = to_int($args['id']);
            $quoteTagRelInit = new QuotationTagRelation();
            $tags = $quoteTagRelInit->where('tag_id', $tagId);
            if ($tags->count() == 0) {
                $tagInit = new ProductionTags();
                $tag = $tagInit->find($tagId);
                if (isset($tag->xe_id) && $tag->xe_id != "" && $tag->xe_id > 0) {
                    $tag->delete();
                    $jsonResponse = [
                        'status' => 1,
                        'message' => message('Quotation Tag', 'deleted'),
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * Delete : Delete Status from the table if not
     * associate with quote
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   28 Mar 2020
     * @return Delete Json Status
     */
    public function deleteQuotationStatus($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Status', 'error'),
        ];
        if (!empty($args) && $args['id'] > 0) {
            $statusId = to_int($args['id']);
            $quotationInit = new Quotations();
            $statusInit = new ProductionStatus();
            $status = $statusInit->find($statusId);
            if (isset($status->xe_id) && $status->xe_id != "" && $status->xe_id > 0) {
                if ($status->delete()) {
                    //Get quotation id in which this status is assigned
                    $quote = $quotationInit->select('xe_id')->where('status_id', $statusId);
                    if ($quote->count() > 0) {
                        $quoteData = $quote->get();
                        $quoteData = json_clean_decode($quoteData, true);
                        $quoteIds = array_map(function ($item) {
                            return $item['xe_id'];
                        }, $quoteData);
                        //After delete change the quote status to default status
                        $quotationInit->whereIn('xe_id', $quoteIds)->update(['status_id' => 1]);
                    }
                }
                $jsonResponse = [
                    'status' => 1,
                    'message' => message('Quotation Status', 'deleted'),
                ];
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET: Sending pdf and email to customer
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     * @param $returnType     retun type
     *
     * @author debashrib@riaxe.com
     * @date   30 Mar 2020
     * @return boolean
     */
    public function sendToCustomer($request, $response, $args, $returnType = 0)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Mail', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        if (!empty($args['id'])) {
            $quotationId = to_int($args['id']);
            $quotationInit = new Quotations();
            $getOldQuotation = $quotationInit->where('xe_id', $quotationId);
            $quotationDetails = $getOldQuotation->first()->toArray();
            //Get Payments Details
            $paymentInit = new QuotationPayment();
            $paymentData =  $paymentInit->select('payment_amount')->where([
                'quote_id' => $quotationId,
                'payment_status' => 'paid'
            ])->sum('payment_amount');
            $comPaidAmount = ($paymentData > 0) ? $paymentData : 0;
            $comPaidAmount = number_format($comPaidAmount, 2, '.', '');
            $quotationDetails['due_amount'] = $quotationDetails['quote_total'] - $comPaidAmount;
            $oldStatusId = $quotationDetails['status_id'];
            //Bind email template
            $templateData = $this->bindEmailTemplate('quote_sent', $quotationDetails, $getStoreDetails);
            $templateData = $templateData[0];
            
            $mailResponse = $this->sendQuotationEmail(
                $templateData, 
                [
                    'name' => $quotationDetails['customer_name'], 
                    'email' => $quotationDetails['customer_email']
                ],  
                $getStoreDetails, []);
            if (!empty($mailResponse['status']) && $mailResponse['status'] == 1) {
                //Update quotation draft status
                $statusInit = new ProductionStatus();
                $approvedStatusId = 0;
                $sentStatusId = 0;
                //get approved status id
                $getApprovedStatusData = $statusInit->select('xe_id')->where([
                    'store_id' => $getStoreDetails['store_id'], 
                    'slug' => 'approved',
                    'module_id' => 1
                ]);
                if ($getApprovedStatusData->count() > 0) {
                   $getApprovedStatusDataArr = $getApprovedStatusData->first(); 
                   $getApprovedStatusDataArr = json_clean_decode($getApprovedStatusDataArr, true);
                   $approvedStatusId = $getApprovedStatusDataArr['xe_id'];
                }
                //get sent status id
                $getSentStatusData = $statusInit->select('xe_id')->where([
                    'store_id' => $getStoreDetails['store_id'], 
                    'slug' => 'sent',
                    'module_id' => 1
                ]);
                if ($getSentStatusData->count() > 0) {
                   $getSentStatusDataArr = $getSentStatusData->first(); 
                   $getSentStatusDataArr = json_clean_decode($getSentStatusDataArr, true);
                   $sentStatusId = $getSentStatusDataArr['xe_id'];
                }
                if ($oldStatusId == $approvedStatusId
                    && ($quotationDetails['quote_total'] != $quotationDetails['due_amount'])
                ) {
                    $updateArr = [
                        'draft_flag' => '0',
                    ];
                } else {
                    $updateArr = [
                        'draft_flag' => '0',
                        'status_id' => $sentStatusId, //3: Sent
                    ];
                }
                $quotationInit->where('xe_id', $quotationId)
                    ->update($updateArr);
                if ($returnType == 0) {
                    //Adding to quote log
                    $logData = [
                        'quote_id' => $quotationId,
                        'title' => 'Quotation sent',
                        'description' => 'Quotation sent to customer with attached pdf file',
                        'user_type' => $allPostPutVars['user_type'],
                        'user_id' => $allPostPutVars['user_id'],
                        'created_date' => date_time(
                            'today', [], 'string'
                        )
                    ];
                    $this->addingQuotationLog($logData);
                }
                $jsonResponse = [
                    'status' => 1,
                    'message' => message('Quotation Mail', 'done'),
                ];

            }
        }
        if ($returnType == 1) {
            return true;
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET: Quotation Listing for grid view
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   03 Apr 2020
     * @return json response
     */
    public function getQuotationCardView($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $quotationInit = new Quotations();
        $statusInit = new ProductionStatus();
        $conversationInit = new QuotationConversations();
        $itemsInit = new QuotationItems();
        $loginId = $request->getQueryParam('login_id');
        //Get agent data
        $userInit = new User();
        $agentData = $userInit->select('xe_id as id', 'name')->where('store_id', $getStoreDetails['store_id']);
        $agentListArr = json_clean_decode($agentData->get(), true);

        $quoteStatusData = $statusInit
            ->select('xe_id as status_id', 'status_name', 'color_code', 'slug as type')
            ->where(
                [
                    'store_id' => $getStoreDetails['store_id'],
                    'module_id' => 1,
                ])->orderBy('sort_order', 'ASC');
        if ($quoteStatusData->count() > 0) {
            $statusDataArr = $quoteStatusData->get();
            $statusDataRes = [];
            foreach ($statusDataArr as $statusData) {
                $newStatusArr = $statusData;
                $quoteDataRes = [];

                //Get total and pending amounts of quotation status wise
                $amountArr = $this->getTotalPaymentAmt($statusData['status_id'], $statusData['type']);
                $newStatusArr['total_amount'] = $amountArr['total_amount'];
                $newStatusArr['pending_amount'] = $amountArr['pending_amount'];
                //Get quotation
                $quotationDetails = [];
                $quotationData = $quotationInit
                    ->select('xe_id', 'quote_id', 'customer_id',
                        'agent_id', 'quote_source', 'title',
                        'quote_total as total_amount', 'created_at', 'invoice_id', 'request_payment', 'request_date', 'customer_name', 'customer_email', 'customer_availability', 'order_id', 'is_ready_to_send', 'currency_id')
                    ->where([
                        'store_id' => $getStoreDetails['store_id'],
                        'status_id' => $statusData['status_id'],
                        'archive_status' => 0,
                    ]);
                if (isset($loginId) && $loginId != "") {
                    $quotationData->where('agent_id', $loginId);
                }
                $quotationData->orderBy('created_at', 'DESC');
                if ($quotationData->count() > 0) {
                    $quotationDetails = $quotationData->get();
                    foreach ($quotationDetails as $quoteData) {
                        //Get customer details
                        $cusId = $quoteData['customer_id'];
                        $customerName = $quoteData['customer_name'];
                        $customerEmail = $quoteData['customer_email'];
                        if ($cusId != '') {
                            if ($customerName == '' && $customerEmail == '') {
                                if ($quoteData['customer_availability'] == 0) {
                                    $customersControllerInit = new CustomersController();
                                    $customerDetails = $customersControllerInit->getQuoteCustomerDetails($cusId, $getStoreDetails['store_id'], '');
                                    if (!empty($customerDetails)) {
                                        $customerName = $customerDetails['customer']['name'];
                                        $customerEmail = $customerDetails['customer']['email'];
                                    }
                                } else {
                                    $customerName = 'No customer';
                                    $customerEmail = 'No customer';
                                }
                            }
                        } else {
                            $customerName = ' ';
                            $customerEmail = ' ';
                        }
                        $newQuoteArr = $quoteData;
                        $newQuoteArr['customer_name'] = ($customerName != '') ? $customerName : $customerEmail;
                        $newQuoteArr['edit_mode'] = ($customerName == 'No customer') ? false : true;
                        //Get Agent name
                        if ($quoteData['agent_id'] != '') {
                            $agentId = $quoteData['agent_id'];
                            $agentArr = array_filter($agentListArr, function ($item) use ($agentId) {
                                return $item['id'] == $agentId;
                            });
                            $agentArr = $agentArr[array_keys($agentArr)[0]];
                        }
                        $newQuoteArr['agent_name'] = $quoteData['agent_id'] != '' ? $agentArr['name'] : '';
                        //Get Tags
                        $newQuoteArr['tags'] = $this->getQuoteTags($quoteData['xe_id']);
                        // For due date
                        $paymentInit = new QuotationPayment();
                        $paymentDataArr = $paymentInit->select('xe_id', 'payment_amount', 'payment_status')
                            ->where([
                                'quote_id' => $newQuoteArr['xe_id'],
                                'payment_status' => 'paid'
                            ])->sum('payment_amount');
                        $comPaidAmount = ($paymentDataArr > 0) ? $paymentDataArr : 0;
                        $comPaidAmount = number_format($comPaidAmount, 2, '.', '');
                        $newQuoteArr['due_amount'] = $newQuoteArr['total_amount'] - $comPaidAmount;
                        //Calculate Paid payment percentage
                        $percentage = 0;
                        if ($newQuoteArr['total_amount'] != '' && $newQuoteArr['total_amount'] > 0) {
                            $percentage = ($comPaidAmount / $newQuoteArr['total_amount']) * 100;
                        }
                        $newQuoteArr['paid_percentage'] = $percentage;
                        //Get conversation unseen count
                        $conversationCount = $conversationInit->where(['quote_id' => $newQuoteArr['xe_id'], 'seen_flag' => '1'])->count();
                        $newQuoteArr['conversation_unseen_count'] = $conversationCount;
                        //Total item quantity of quotation
                        $getItemQuantityArr = $itemsInit->select('quantity')->where('quote_id', $newQuoteArr['xe_id'])->get()->toArray();
                        $quantity = array_column($getItemQuantityArr, 'quantity');
                        $totalQuantity = array_sum($quantity);
                        $newQuoteArr['total_quantity'] = $totalQuantity;
                        //Public Link
                        $token = 'quote_id=' . $newQuoteArr['xe_id'].'&store_id='.$getStoreDetails['store_id'];
                        $token = base64_encode($token);
                        $url = 'quotation/quotation-approval?token=' . $token;
                        $newQuoteArr['public_url'] = API_URL.$url;
                        //Get Order number
                        $orderNumber = '';
                        if ($newQuoteArr['order_id'] != '' && $newQuoteArr['order_id'] > 0) {
                            //Get Order number
                            $ordersInit = new Orders;
                            $orders = $ordersInit->select('order_number')->where('order_id', $newQuoteArr['order_id']);
                            if ($orders->count() > 0) {
                                $orderData = json_clean_decode($orders->first(), true);
                                $orderNumber = $orderData['order_number'];
                            }
                        }
                        $newQuoteArr['order_number'] = ($orderNumber != '') ? $orderNumber : $newQuoteArr['order_id'];
                        $currencyId = $quoteData['currency_id'];
                        $newQuoteArr['currency'] = $this->getUsedCurrency($currencyId, $getStoreDetails['store_id']);
                        $checkLineItem = $this->checkForLineItems($request, $response, ['id' => $newQuoteArr['xe_id']], 1);
                        $newQuoteArr['show_item_msg'] = $checkLineItem['show_item_msg'];
                        $newQuoteArr['slug'] = $statusData['type'];
                        array_push($quoteDataRes, $newQuoteArr);
                    }
                }
                $newStatusArr['quotations'] = $quoteDataRes;
                array_push($statusDataRes, $newStatusArr);
            }
            $jsonResponse = [
                'status' => 1,
                'data' => $statusDataRes,
            ];
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET Quotation total and pending amount status wise
     *
     * @param $statusId  Quotation status Id
     *
     * @author debashrib@riaxe.com
     * @date   03 Apr 2019
     * @return json response
     */
    private function getTotalPaymentAmt($statusId, $type= '')
    {
        $amountArr = [
            'total_amount' => 0,
            'pending_amount' => 0,
        ];
        if (!empty($statusId)) {
            $quotationInit = new Quotations();
            $totalAmount = 0;
            $pendingAmount = 0;
            $quotation = $quotationInit->select('xe_id', 'quote_total')
                ->where('status_id', $statusId);
            if ($type != '' && $type == 'ordered') {
                $quotation->where('archive_status', 0);
            }
            if ($quotation->count() > 0) {
                $quotationData = $quotation->get();
                $quotationData = json_clean_decode($quotationData, true);
                $quotationTotalArr = array_column($quotationData, 'quote_total');
                $quotationIdArr = array_column($quotationData, 'xe_id');
                $totalAmount = array_sum($quotationTotalArr);
                if (!empty($quotationIdArr)) {
                    $paymentInit = new QuotationPayment();
                    $payment = $paymentInit->select('payment_amount')
                        ->whereIn('quote_id', $quotationIdArr)
                        ->where('payment_status', 'paid')->sum('payment_amount');
                    $totalPaidAmount = ($payment > 0) ? $payment : 0;
                }
                $pendingAmount = $totalAmount - $totalPaidAmount;
            }
            $amountArr = [
                'total_amount' => $totalAmount,
                'pending_amount' => $pendingAmount,
            ];
        }
        return $amountArr;
    }

    /**
     * Tags w.r.t quotation
     *
     * @param $quotationId  Quotation Id
     *
     * @author debashrib@riaxe.com
     * @date   04 Apr 2020
     * @return array
     */
    private function getQuoteTags($quotationId)
    {
        if ($quotationId != '') {
            $productionTagInit = new ProductionTags();
            $quoteTagRelInit = new QuotationTagRelation();
            $getTags = $quoteTagRelInit->where('quote_id', $quotationId);
            $tagRes = [];
            if ($getTags->count() > 0) {
                $tagDataArr = $getTags->get();
                foreach ($tagDataArr as $tagData) {
                    $newTagArr = [];
                    $tagName = $productionTagInit
                        ->where('xe_id', $tagData['tag_id'])->first();
                    $newTagArr = [
                        'id' => $tagName['xe_id'],
                        'name' => $tagName['name'],
                    ];
                    array_push($tagRes, $newTagArr);
                }
            }
        }
        return $tagRes;
    }

    /**
     * POST: Assign agent to quotation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   04 Apr 2020
     * @return json response wheather data is updated or any error occured
     */
    public function assignAgent($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Assign Agent', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        if (!empty($args['id'])) {
            $quotationId = to_int($args['id']);
            $quotationInit = new Quotations();
            $getOldQuotation = $quotationInit->select('xe_id', 'agent_id')->where('xe_id', $quotationId);
            if ($getOldQuotation->count() > 0) {
                $getOldQuotationArr = json_clean_decode($getOldQuotation->first(), true);
                $previousAgentId = $getOldQuotationArr['agent_id']; 
                //print_r($getOldQuotationArr);exit;
                $userType = (isset($allPostPutVars['user_type']) && $allPostPutVars['user_type'] != '') ? $allPostPutVars['user_type'] : 'admin';
                $userId = (isset($allPostPutVars['user_id']) && $allPostPutVars['user_id'] != '') ? $allPostPutVars['user_id'] : 1;
                unset($allPostPutVars['user_type'], $allPostPutVars['user_id']);
                $quotationInit->where('xe_id', $quotationId)
                    ->update($allPostPutVars);
                //Adding to quote log
                $userName = '';
                $previousUserName = '';
                $userInit = new User();
                $agent = $userInit->select('xe_id', 'name')->where('xe_id', $allPostPutVars['agent_id']);
                if ($agent->count() > 0) {
                    $agentDetails = json_clean_decode($agent->first(), true);
                    $userName = $agentDetails['name'];
                }
                if ($previousAgentId == '') {
                   $description = 'Agent '.$userName.' is assigned';
                } else {
                    $previousAgent = $userInit->select('xe_id', 'name')->where('xe_id', $previousAgentId);
                    if ($previousAgent->count() > 0) {
                        $previousAgentDetails = json_clean_decode($previousAgent->first(), true);
                        $previousUserName = $previousAgentDetails['name'];
                    }
                    $description = 'Agent '.$userName.' is assigned and unassigned '.$previousUserName;
                }
                $logData = [
                    'quote_id' => $quotationId,
                    'title' => 'Agent assigned',
                    'description' => $description,
                    'user_type' => $userType,
                    'user_id' => $userId,
                    'created_date' => date_time(
                        'today', [], 'string'
                    )
                ];
                
                $this->addingQuotationLog($logData);
                $jsonResponse = [
                    'status' => 1,
                    'message' => message('Assign Agent', 'updated'),
                ];
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * Adding data to quotation log
     *
     * @param $logData  Log data array
     *
     * @author debashrib@riaxe.com
     * @date   06 Apr 2020
     * @return boolean
     */
    public function addingQuotationLog($logData)
    {
        if (!empty($logData)) {
            $quotationLog = new QuotationLog($logData);
            if ($quotationLog->save()) {
                return true;
            }
        }
        return false;
    }

    /**
     * GET : Quotation log
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   03 Apr 2019
     * @return json response
     */
    public function getQuotationLog($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 1,
            'data' => [],
            'message' => message('Quotation Log', 'not_found'),
        ];
        $getStoreDetails = get_store_details($request);
        $quotationInit = new Quotations();
        if (!empty($args['id'])) {
            $quoteId = to_int($args['id']);
            $quotation = $quotationInit->where(
                [
                    'xe_id' => $quoteId,
                    'store_id' => $getStoreDetails['store_id'],
                ]);
            $noteRes = [];
            $logRes = [];
            if ($quotation->count() > 0) {
                $quotationLogInit = new QuotationLog();
                $logs = $quotationLogInit->where('quote_id', $quoteId)
                    ->orderBy('created_date', 'DESC');

                if ($logs->count() > 0) {
                    $logArr = $logs->get();
                    foreach ($logArr as $logData) {
                        $newLogArr = $logData;
                        $userName = $newLogArr['user_type'];
                        if ($newLogArr['user_type'] == 'customer') {
                            // Get customer name
                            if ($newLogArr['user_id'] != '') {
                                $customersControllerInit = new CustomersController();
                                $customerDetails = $customersControllerInit->getQuoteCustomerDetails($newLogArr['user_id'], $getStoreDetails['store_id'], '');
                                if (!empty($customerDetails)) {
                                    $userName = ($customerDetails['customer']['name'] != '') ? $customerDetails['customer']['name'] : $customerDetails['customer']['email'];
                                }
                            }
                        } else {
                            //Get agent name
                            $userInit = new User();
                            $agent = $userInit->select('xe_id', 'name')->where('xe_id', $newLogArr['user_id']);
                            if ($agent->count() > 0) {
                                $agentDetails = json_clean_decode($agent->first(), true);
                                $userName = $agentDetails['name'];
                            }
                        }
                        $description = $newLogArr['description'] . ' by ' . $userName;
                        if ($newLogArr['description'] == 'Agent is assigned') {
                            $description = 'Agent ' . $userName . ' is assigned by Admin';
                        }
                        $newLogArr['title'] = ($newLogArr['title'] != '') ? $newLogArr['title'] : 'Quotation log';
                        $newLogArr['description'] = $description;
                        $newLogArr['log_type'] = 'quote_log';
                        $newLogArr['created_at'] = $newLogArr['created_date'];
                        unset($newLogArr['created_date']);
                        array_push($logRes, $newLogArr);
                    }

                }
                //Get internal note data
                $internalNoteInit = new QuotationInternalNote();
                $internalNotes = $internalNoteInit->with('files')->where('quote_id', $quoteId)
                    ->orderBy('created_date', 'DESC');
                if ($internalNotes->count() > 0) {
                    $noteDataArr = $internalNotes->get();
                    foreach ($noteDataArr as $noteData) {
                        $newNoteArr = $noteData;
                        $userName = $newNoteArr['user_type'];
                        if ($newNoteArr['user_type'] == 'agent') {
                            //Get agent name
                            $userInit = new User();
                            $agent = $userInit->select('xe_id', 'name')->where('xe_id', $newNoteArr['user_id']);
                            if ($agent->count() > 0) {
                                $agentDetails = json_clean_decode($agent->first(), true);
                                $userName = $agentDetails['name'];
                            }
                        }
                        $newLogArr['title'] = 'Internal note';
                        $newNoteArr['description'] = $newNoteArr['note'] . ' by ' . $userName;
                        $newNoteArr['log_type'] = 'internal_note';
                        $newNoteArr['created_at'] = $newNoteArr['created_date'];
                        unset(
                            $newNoteArr['note'],
                            $newNoteArr['seen_flag'],
                            $newNoteArr['created_date']
                        );
                        array_push($noteRes, $newNoteArr);
                    }
                }
                $totalQuotationLogs = array_merge($logRes, $noteRes);
                // Sort the array by Created Date and time
                usort($totalQuotationLogs, 'date_compare');
                if (is_array($totalQuotationLogs) && !empty($totalQuotationLogs) > 0) {
                    $jsonResponse = [
                        'status' => 1,
                        'data' => $totalQuotationLogs,
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Assign agent to quotation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   07 Apr 2020
     * @return json response wheather data is updated or any error occured
     */
    public function changeQuotationStatus($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Status Change', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $updateData = $request->getParsedBody();
        //Get status data
        $updateType = $updateData['type'];
        $statusId = 0;
        $statusInit = new ProductionStatus();
        $getStatusData = $statusInit->select('xe_id')->where([
            'store_id' => $getStoreDetails['store_id'], 
            'slug' => $updateType,
            'module_id' => 1
        ]);
        if ($getStatusData->count() > 0) {
           $getStatusDataArr = $getStatusData->first(); 
           $getStatusDataArr = json_clean_decode($getStatusDataArr, true);
           $statusId = $getStatusDataArr['xe_id'];
        }
        unset($updateData['user_id'], $updateData['user_type'], $updateData['type']);
        $updateData['status_id'] = $statusId;
        $oldStatus = $newStatus = '';
        if (!empty($args['id'])) {
            $quotationId = to_int($args['id']);
            $quotationInit = new Quotations();
            $newStatusId = $statusId;
            $getOldQuotation = $quotationInit
                ->join('production_status', 'quotations.status_id', '=', 'production_status.xe_id')
                ->select('quotations.xe_id', 'quotations.store_id', 'quotations.quote_id', 'quotations.customer_id', 'quotations.shipping_id', 'quotations.agent_id', 'quotations.created_by', 'quotations.created_by_id', 'quotations.quote_source', 'quotations.title', 'quotations.description', 'quotations.ship_by_date', 'quotations.exp_delivery_date', 'quotations.is_artwork', 'quotations.is_rush', 'quotations.rush_type', 'quotations.rush_amount', 'quotations.discount_type', 'quotations.discount_amount', 'quotations.shipping_type', 'quotations.shipping_amount', 'quotations.tax_amount', 'quotations.design_total', 'quotations.quote_total', 'quotations.note', 'quotations.status_id', 'quotations.draft_flag', 'quotations.reject_note', 'quotations.invoice_id', 'quotations.order_id', 'quotations.request_payment', 'quotations.request_date', 'quotations.created_at', 'quotations.updated_at', 'production_status.status_name as quote_status', 'production_status.color_code', 'quotations.customer_name', 'quotations.customer_email', 'quotations.customer_availability', DB::raw("(SELECT status_name FROM production_status WHERE xe_id = $newStatusId) as new_status"))
                ->where(
                [
                    'quotations.xe_id' => $quotationId,
                ]);
            if ($getOldQuotation->count() > 0) {
                $quoteData = $getOldQuotation->first()->toArray();
                $oldStatus = $quoteData['quote_status'];
                $newStatus = $quoteData['new_status'];
                $updateData['draft_flag'] = '0';
                $quotationInit->where('xe_id', $quotationId)->update($updateData);
            }
            //Adding to quote log
            $logData = [
                'quote_id' => $quotationId,
                'title' => 'Status changed',
                'description' => 'Status is changed to ' . $newStatus . ' from ' . $oldStatus,
                'user_type' => $allPostPutVars['user_type'],
                'user_id' => $allPostPutVars['user_id'],
                'created_date' => date_time(
                    'today', [], 'string'
                )
            ];
            $this->addingQuotationLog($logData);
            //If status is approved

            if ($updateType == 'approved') {
                //Get Payments Details
                $paymentInit = new QuotationPayment();
                $paymentData =  $paymentInit->select('payment_amount')->where([
                    'quote_id' => $quotationId,
                    'payment_status' => 'paid'
                ])->sum('payment_amount');
                $comPaidAmount = ($paymentData > 0) ? $paymentData : 0;
                $comPaidAmount = number_format($comPaidAmount, 2, '.', '');
                $quoteData['due_amount'] = $quoteData['quote_total'] - $comPaidAmount;
                //Bind email template
                $templateData = $this->bindEmailTemplate('quote_approval', $quoteData, $getStoreDetails);
                $templateData = $templateData[0];
                //Send Email
                $this->sendQuotationEmail(
                    $templateData, 
                    [
                        'name' => $quoteData['customer_name'], 
                        'email' => $quoteData['customer_email']
                    ],  
                    $getStoreDetails, []);
            }
            $jsonResponse = [
                'status' => 1,
                'message' => message('Status Change', 'updated'),
            ];
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * DELETE: Delete a quotation along with tags, items and files
     *
     * @param $request  Slim's Argument parameters
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   08 Apr 2019
     * @return json response wheather data is deleted or not
     */
    public function deleteQuotation($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation', 'error'),
        ];
        $success = 0;
        $quotationDelIds = $args['id'];

        $getDeleteIdsToArray = json_clean_decode($quotationDelIds, true);
        $totalCount = count($getDeleteIdsToArray);

        if (!empty($getDeleteIdsToArray)
            && count($getDeleteIdsToArray) > 0
        ) {
            $quotationInit = new Quotations();
            if ($quotationInit->whereIn('xe_id', $getDeleteIdsToArray)->count() > 0) {
                foreach ($getDeleteIdsToArray as $quotationId) {
                    $quotationData = $quotationInit->select('quote_id', 'quote_source', 'quotation_request_id')->where('xe_id', $quotationId);
                    $quotationDataArr = json_clean_decode($quotationData->first(), true); 
                    //Delete quotation tags
                    $tagRelationInit = new QuotationTagRelation();
                    $tagRelationInit->where(
                        'quote_id', $quotationId
                    )->delete();
                    //Delete quotation items
                    $this->deleteQuoteItems($quotationId);
                    //Delete quotation internal note and files
                    $internalNoteInit = new QuotationInternalNote();
                    $notes = $internalNoteInit->where('quote_id', $quotationId);
                    if ($notes->count() > 0) {
                        $noteDataArr = $notes->get();
                        $noteFilesInit = new QuotationInternalNoteFiles();
                        foreach ($noteDataArr as $noteData) {
                            $noteFiles = $noteFilesInit->where('note_id', $noteData['xe_id']);
                            if ($noteFiles->count() > 0) {
                                $noteFileArr = $noteFiles->get();
                                foreach ($noteFileArr as $noteFiles) {
                                    $this->deleteOldFile(
                                        "quote_internal_note_files", "file", [
                                            'xe_id' => $noteFiles['xe_id'],
                                        ], path('abs', 'quotation') . 'internal-note/'
                                    );
                                }
                            }
                            //Delete note
                            $internalNoteInit->where(
                                'xe_id', $noteData['xe_id']
                            )->delete();
                        }

                    }
                    //Delete quotation payment
                    $paymentInit = new QuotationPayment();
                    $paymentInit->where(
                        'quote_id', $quotationId
                    )->delete();
                    //Delete quotation log
                    $quotationLogInit = new QuotationLog();
                    $quotationLogInit->where(
                        'quote_id', $quotationId
                    )->delete();
                    //delete quotation request data
                    if ($quotationDataArr['quote_source'] == 'tool') {
                        $quotationRequestDetailsInit = new QuotationRequestDetails();
                        $quotationRequestDetailsInit->where('quote_id', $quotationDataArr['quote_id'])->delete();
                        $quotationRequestFormValuesInit = new QuotationRequestFormValues();
                        $quotationRequestFormValuesInit->where('quote_id', $quotationDataArr['quote_id'])->delete();
                    }
                    $quotationInit->where('xe_id', $quotationId)->delete();
                    $success++;
                }
                $jsonResponse = [
                    'status' => 1,
                    'message' => $success . ' out of ' . $totalCount .
                    ' Quotation(s) deleted successfully',
                ];
            }
            $pluginsInit = new PluginSettings();
                $printfulStatus = $pluginsInit->where('catalog_code', 'quickbooks')
                ->where('status', 1);
                $pluginCountprint = $printfulStatus->count();
                if($pluginCountprint > 0){
                    $quickBookObj = new QuickBookController();
                    $quickBookObj->deleteEstimate($request, $response,$getDeleteIdsToArray);                 
                }
        }

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

    /**
     * Download Quotation pdf in local system
     *
     * @param $request  Slim's Argument parameters
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   09 Apr 2019
     * @return boolean
     */
    public function downloadQuotation($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Download', 'not_found'),
        ];
        if (!empty($args['id']) && $args['id'] > 0) {
            $quotationId = $args['id'];
            $quotationInit = new Quotations();
            $getOldQuotation = $quotationInit->where('xe_id', $quotationId);
            if ($getOldQuotation->count() > 0) {
                $quotationDetails = $getOldQuotation->first()->toArray();
                $dir = path('abs', 'quotation') . $quotationId . '/'.$quotationDetails['quote_id'].'.pdf';
                //if (!file_exists($dir)) { 
                    $this->createQuotationPdf($request, $response, $args, 1);
                //}
                //Download file in local system
                if (file_exists($dir) && (file_download($dir, 0))) {
                    $serverStatusCode = OPERATION_OKAY;
                    $jsonResponse = [
                        'status' => 1,
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * Create Quotation pdf
     *
     * @param $quotationId     Quotation Id
     * @param $quotationDetails    Quotation Details
     * @param $itemList    Quotation Items List
     * @param $getStoreDetails    Store id
     *
     * @author debashrib@riaxe.com
     * @date   15 Apr 2019
     * @return pdf file path
     */
    public function createQuotationPdf($request, $response, $args, $returnType = 0)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Pdf', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $isPublicLinkLang = !empty($request->getQueryParam('public_link_lang')) ? $request->getQueryParam('public_link_lang') : '';
        $globalSettingData = $this->readSettingJsonFile($getStoreDetails['store_id']);
        $languageData = $this->getQuotationDefaultLang($request, $response, 1);
        $toolLang = $isPublicLinkLang != '' ? $isPublicLinkLang : $languageData['default']['name'];
        $ordersInit = new OrdersController($toolLang);
        $pdfLanguage = $ordersInit->languageContent['quotation-pdf-and-public-link'];
        $quotationId = to_int($args['id']);
        if ($quotationId > 0 && $quotationId != '') {
            //Get quotation details
            $quotationDetails = $this->getQuotationDetails($request, $response, $args, 1);
            $itemList = $this->getQuoteItems($request, $response, $args, 1);

            $filePath = path('abs', 'quotation') . $quotationId . '/';
            $fileDir = $filePath.$quotationDetails['quote_id'].'.pdf'; 
            if (file_exists($fileDir)) {
                delete_file($fileDir);
            }

            //Get currency from global setting
            $separator = $globalSettingData['currency']['separator'];
            $currency = $quotationDetails['currency']['code'];//$quotationDetails['currency']['unicode_character'];
            //Get email setting data for sending email
            $emailSettingData = $this->getProductionSetting($request, $response, ['module_id' => 1, 'return_type' => 1]);
            $emailSettingData = $emailSettingData['data'];
            $customerName = ($quotationDetails['customer']['name'] != '') ? $quotationDetails['customer']['name'] : $quotationDetails['customer']['email'];
            $billingAddressArr = $quotationDetails['customer']['billing_address'];
            $billingAddress = $billingAddressArr['address_1'] != '' ? $billingAddressArr['address_1'] . ', ' . $billingAddressArr['address_2'] . '<br/>' . $billingAddressArr['country'] . ', ' . $billingAddressArr['state'] . ',<br/>' . $billingAddressArr['city'] . '-' . $billingAddressArr['postcode'] : '';
            $finalShippingArr = [];
            $shippingId = $quotationDetails['shipping_id'];
            if ($shippingId != '') {
                if (isset($quotationDetails['customer']['shipping_address'])) {
                    $finalShippingArr = array_filter($quotationDetails['customer']['shipping_address'], function ($item) use ($shippingId) {
                        return $item['id'] == $shippingId;
                    });
                }
                $finalShippingArr = $finalShippingArr[array_keys($finalShippingArr)[0]];
            }
            $shippingAddress = $finalShippingArr['address_1'] != '' ? $finalShippingArr['address_1'] . ', ' . $finalShippingArr['address_2'] . '<br/>' . $finalShippingArr['country'] . ', ' . $finalShippingArr['state'] . ',<br/>' . $finalShippingArr['city'] . '-' . $finalShippingArr['postcode'] : '';

            /** get font for default language */
            $languageFont =  $this->getDefaultLanguageFont($getStoreDetails['store_id'], "tool", $toolLang );
            if (strtolower($toolLang) == "japanese" || strtolower($toolLang) == "chinese") {
                $fontFamily = "simsun";
                $fontAll = "simsun";
                $fontUrl = "";
            } else {
                $fontFamily = "DejaVuSans";
                $fontAll = "DejaVuSans";
                $fontUrl = "";
            }
            $fontStyle = $languageFont['font_style'];
            $fontWeight = $languageFont['font_weight'];
            $trueType = $languageFont['true_type'];
            $class = (isset($languageFont['style']) && $languageFont['style']) == 'rtl' ? 'rtl' : '';

            $rtlLeftAlign = "right";
            $rtlRightAlign = "left";
            $leftTable = '58%';
            $rightTable = '42%';
            if (strtolower($toolLang) == 'arabic') {
                $leftTable = '60%';
                $rightTable = '40%';
                $rtlLeftAlign = "left";
                $rtlRightAlign = "right";
            }

            $html = '<!doctype html>
            <html lang="en-US">

            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                <style>@media print {
                            body {-webkit-print-color-adjust: exact;}
                        }
                        @font-face {
                            font-family: "'.$fontFamily.'";
                            font-style: '.$fontStyle.';
                            font-weight: '.$fontWeight.';
                            src: url('.$fontUrl.') format("'.$trueType.'");
                        }
                        * {
                            font-family: '.$fontAll.';
                        }
                    </style>
            </head>
            <body style="margin: 0; padding: 0;">
                <table cellpadding="5" style="margin: 0px; padding: 0px; background: #fff; -webkit-box-shadow: 0px 2px 20px 0px rgba(0, 0, 0, 0.06); box-shadow: 0px 2px 20px 0px rgba(0, 0, 0, 0.06); position: relative; box-sizing: border-box; font-family: '.$fontFamily.';">

                <table width="100%" cellspacing="0" cellpadding="0" border="0" style="min-width: 100%;">
              <tr>
                <td width="50%" style="vertical-align: top;"><br/>
                  <span style="font-size: 24px;"><strong>'.$pdfLanguage['title'].'</strong></span><br/><br/>
                  <table width="100%" cellspacing="0" cellpadding="0"  border="0" style="font-size: 12px;">
                    <tr>
                      <td style="padding: 0 20px 4px 0px;"><strong>'.$pdfLanguage['no'].'</strong></td>
                      <td style="padding: 0 20px 4px 0px;">
                        : ' . $quotationDetails['quote_id'] . '
                      </td>
                    </tr>
                    <tr>
                      <td style="padding: 0 20px 4px 0px;"><strong>'.$pdfLanguage['shipping-date'].'</strong></td>
                      <td style="padding: 0 20px 4px 0px;">
                        : ' . date("dS F, Y", strtotime($quotationDetails['ship_by_date'])) . '
                      </td>
                    </tr>
                    <tr>
                      <td style="padding: 0 20px 4px 0px;"><strong>'.$pdfLanguage['delivery-date'].'</strong></td>
                      <td style="padding: 0 20px 4px 0px;">
                        : ' . date("dS F, Y", strtotime($quotationDetails['exp_delivery_date'])) . '
                      </td>
                    </tr>
                  </table>
                </td>
                <td width="50%" align="'.$rtlLeftAlign.'" style="vertical-align: top; text-align: right; font-size: 14px;">';
            if ($emailSettingData['company_logo'] != '') {
                $html .= '<span style="margin: 0 0 0 auto; width: 120px; align:'.$rtlLeftAlign.'">
                    <img alt="logo" src="' . $emailSettingData['company_logo'] . '" style="width: auto; height:120px;" />
                  </span><br/>';
            }
            $html .= '<span style="font-size: 14px; line-height: 22px;">
                    ' . $emailSettingData['address'] . ',<br/>
                    ' . $emailSettingData['country'] . ',' . $emailSettingData['state'] . ',' . $emailSettingData['city'] . '-' . $emailSettingData['zip_code'] . ',<br/>
                    ' . $emailSettingData['sender_email'] . '<br/>
                    ' . $emailSettingData['phone_number'] . '
                  </span>
                </td>
              </tr>
              <tr>
              <td colspan="2" width="100%">
                <hr style="margin: 30px 0 0 0;">
              </td>
            </tr>
            </table>
            
            <table width="100%" cellspacing="0" cellpadding="0" border="0" style="min-width: 100%; margin-bottom: 30px;">
              <tr>';
            if (!empty($quotationDetails['customer'])) {
                $html .= '<td  width="50%" style="vertical-align: top; width:20%; padding-right:20px;"><br/>
                  <span style="font-size: 14px;font-weight:bold;">'.$pdfLanguage['quotation-for'].'</span><br/>
                  <span style="margin: 0 0 10px 0; font-size: 12px;">'.$customerName.'<br/>
                    ' . $quotationDetails['customer']['email'] . '<br/>
                    ' . $quotationDetails['customer']['phone'] . '
                  </span>
                </td>';
            }
                $html .= '<td width="50%" align="'.$rtlLeftAlign.'" style="vertical-align: top;">
                  <span style="font-size: 14px;font-weight:bold;">'.$pdfLanguage['balance-due'].'</span><br/>
                  <span style="margin: 7px 0; font-size: 12px;"><span> '.$currency.'</span> ' . number_format($quotationDetails['due_amount'], 2, $separator, '') . '</span>
                </td>
              </tr>
            </table>';
            $html .= '<table width="100%" cellspacing="0" cellpadding="0" border="0" style="min-width: 100%; margin-bottom: 30px;">
              <tr>';
                if ($billingAddress != '') {
                    $html .= '<td width="50%" style="vertical-align: top; font-size: 14px; line-height: 22px; width:50%;"><br/>
                      <span style="font-size: 14px;"><strong>'.$pdfLanguage['billing-address'].'</strong></span>
                      <span style="font-size: 12px;"><br/>
                        ' . $billingAddress . '
                      </span><br/>
                    </td>';
                }
                if ($shippingAddress != '') {
                    $html .= '<td width="50%" align="'.$rtlLeftAlign.'" style="vertical-align: top; font-size: 14px; line-height: 22px; width:50%;"><br/>
                      <span style="font-size: 14px;"><strong>'.$pdfLanguage['shipping-address'].'</strong></span>
                      <span style="font-size: 12px;"><br/>
                        ' . $shippingAddress . '
                      </span><br/>
                    </td>';
                }
            $html .= '</tr>
            </table>';
            $html .= '<table width="100%" cellpadding="5" cellspacing="" border="0" style="font-size: 12px; line-height: 20px;">
              <thead>
                <tr>
                <td align="center" width="10%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                    '.$pdfLanguage['sno'].'
                    </td>
                  <td align="center" width="20%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                    '.$pdfLanguage['product-name'].'
                  </td>
                  <td align="center" width="20%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                    '.$pdfLanguage['product-details'].'
                  </td>
                  <td align="center" width="10%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                    '.$pdfLanguage['unit-price'].'
                  </td>
                  <td align="center" width="10%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                    '.$pdfLanguage['total-qty'].'
                  </td>
                  <td align="center" width="10%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;">
                    <strong>'.$pdfLanguage['design-price'].'</strong>
                  </td>
                  <td align="center" width="20%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                    '.$pdfLanguage['total-price'].'
                  </td>
                </tr>
              </thead>
              <tbody>';
            $subtotal = 0;
            foreach ($itemList as $itemKey => $items) {
                $productName = ($items['product_name'] != '') ? $items['product_name'] : 'N/A';
                $slNo = $itemKey + 1;
                $backgroundColor = (($itemKey % 2) == 0) ? 'background-color: rgba(0, 0, 0, 0.05);' : '';
                $subtotal = $subtotal + $items['unit_total'];
                if ($items['product_availability']) {
                    $html .= '<tr>
                      <td valign="top" width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">' . $slNo . '</td>
                      <td valign="top" width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;" >' . $productName . '</td>
                      <td valign="top" width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">';
                    if (!empty($items['sticker_data']) && $items['sticker_data']['stickerOption'] == 'sheet' && !empty($items['sticker_data']['sheetInfo'])) {
                        foreach ($items['sticker_data']['sheetInfo'] as $sheetInfo) {
                            $html .= '<span>'.$pdfLanguage['sheet'].' - '.$sheetInfo['name'].' : '.$sheetInfo['quantity'].'</span><br/>';
                        }

                    } else {
                        foreach ($items['product_variant'] as $variants) {
                            if (!empty($variants['attribute'])) {
                                $html .= '<span>(';
                                foreach ($variants['attribute'] as $attribute) {
                                    $html .= $attribute['name'] . ' / ';
                                }
                                $html .= $variants['quantity'] . ')</span> <br/>';
                            } else {
                                $html .= 'Simple Product';
                            }
                        }
                    }
                    $html .= '</td>
                      <td valign="top" width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">';
                    if (!empty($items['sticker_data']) && $items['sticker_data']['stickerOption'] == 'sheet' && !empty($items['sticker_data']['sheetInfo'])) {
                        foreach ($items['sticker_data']['sheetInfo'] as $sheetInfo) {
                            $sheetPriceforticker = (isset($sheetInfo['updated_price'])) ? $sheetInfo['updated_price'] : $sheetInfo['price'];
                            $html .= '<span>'.$currency.'</span> ' . number_format($sheetPriceforticker, 2, $separator, '') . '<br/>';
                        }
                    } else {
                        foreach ($items['product_variant'] as $variants) {
                            $updatedPrice = (isset($variants['updated_price']) && $variants['updated_price'] != '') ? $variants['updated_price'] : $variants['unit_price'];
                            $html .= '<span>'.$currency.'</span> ' . number_format($updatedPrice, 2, $separator, '') . '<br/>';
                        }
                    }

                    $html .= '</td>
                      <td valign="top" width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">' . $items['quantity'] . '</td>
                      <td valign="top" width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"><span>'.$currency.'</span> ' . number_format($items['design_cost'], 2, $separator, '') . '</td>
                      <td valign="top" width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"><span>'.$currency.'</span> ' . number_format($items['unit_total'], 2, $separator, '') . '</td>
                    </tr>';
                } else {
                    $html .= '<tr>
                      <td valign="top" width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">' . $slNo . '</td>
                      <td valign="top" width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;" >No product availabe</td>
                      <td valign="top" width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">The product might be deleted or remove from store.</td>
                      <td valign="top" width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"></td>
                      <td valign="top" width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">' . $items['quantity'] . '</td>
                      <td valign="top" width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"><span>'.$currency.'</span> ' . number_format($items['design_cost'], 2, $separator, '') . '</td>
                      <td valign="top" width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"><span>'.$currency.'</span> ' . number_format($items['unit_total'], 2, $separator, '') . '</td>
                      </tr>';
                }
            }
            $display = ($quotationDetails['note'] == '') ? 'display: none;' : '';
            $html .= '</tbody>
            </table>
            <table width="100%" cellspacing="0" cellpadding="0" border="0" style="margin-top: 30px; line-height: 24px;">
              <tr>
                <td width="'.$leftTable.'"><br/>
                  <span style="font-size: 14px; ' . $display . '"><strong>'.$pdfLanguage['note'].'</strong></span>
                  <span style="font-size: 12px; line-height: 22px; ' . $display . '"><br/>
                    ' . $quotationDetails['note'] . '
                  </span>
                </td>
                <td width="'.$rightTable.'" align="'.$rtlLeftAlign.'">
                  <table width="100%" cellspacing="0" cellpadding="5" border="0" style="font-size: 12px; line-height: 20px;">
                    <tr>
                      <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><strong> '.$pdfLanguage['subtotal'].'</strong></td>
                      <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"> <span>'.$currency.'</span> ' . number_format($subtotal, 2, $separator, '') . '</td>
                    </tr>';
            if ($quotationDetails['discount_type'] == 'percentage') {
                $discountValue = $subtotal * ($quotationDetails['discount_amount'] / 100);
                $decCount = strlen(substr(strrchr($discountValue, "."), 1));
                if ($decCount <= 2) {
                    $finalDiscount = number_format($discountValue, 2, $separator, '');
                } else {
                    $finalDiscount = str_replace(".",$separator,floor($discountValue * 100) / 100);
                }
                $discountAmount = ' - <span>'.$currency.'</span>' . $finalDiscount;
                $showDisPercent = ' (' . $quotationDetails['discount_amount'] . '%)';
            } else {
                $discountValue = $quotationDetails['discount_amount'];
                $discountAmount = ' - <span>'.$currency.'</span> ' . number_format($discountValue, 2, $separator, '');
                $showDisPercent = '';
            }
            $taxAmount = ($subtotal - $discountValue) * ($quotationDetails['tax_amount'] / 100);
            $taxAmount = number_format($taxAmount, 2, '.', '');
            if ($quotationDetails['tax_amount'] > 0) { 
                $html .= '<tr>
                      <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><strong> '.$pdfLanguage['tax'].'(' . $quotationDetails['tax_amount'] . '%)</strong></td>
                      <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"> <span>'.$currency.'</span> ' . number_format($taxAmount, 2, $separator, '') . '</td>
                    </tr>';
            }
            if ($quotationDetails['shipping_amount'] > 0) {
                $html .= '<tr>
                      <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><strong> '.$pdfLanguage['shipping'].'</strong></td>
                      <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"> <span>'.$currency.'</span> '. number_format($quotationDetails['shipping_amount'], 2, $separator, '') . '</td>
                    </tr>';
            }
            if ($quotationDetails['discount_amount'] > 0) {
                if ($quotationDetails['discount_type'] == 'percentage') {
                $discountType = $pdfLanguage['percentage'];
              } else {
                $discountType = $pdfLanguage['flat'];
              }

                $html .= '<tr>
                      <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><strong>'.$pdfLanguage['discount'].'(' . $discountType . ')</strong></td>
                      <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;">' . $discountAmount . $showDisPercent . '</td>
                    </tr>';
            }
            
            if ($quotationDetails['is_rush'] == '1') {
                if ($quotationDetails['rush_type'] == 'percentage') {
                    $rush = $subtotal * ($quotationDetails['rush_amount'] / 100);
                    $rushAmount = number_format($rush, 2, $separator, '');
                    $showPercent = ' (' . $quotationDetails['rush_amount'] . '%)';
                } else {
                    $rushAmount = number_format($quotationDetails['rush_amount'], 2, $separator, '');
                    $showPercent = '';
                }
                $html .= '<tr>
                          <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><strong> '.$pdfLanguage['rush'].'(' . ucfirst($quotationDetails['rush_type']) . ')</strong></td>
                          <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"> <span>'.$currency.'</span>' . $rushAmount . $showPercent . '</td>
                        </tr>';
            }
            
            $html .= '<tr>
                      <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><strong> '.$pdfLanguage['total'].'</strong></td>
                      <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><span> '.$currency.'</span>' . number_format($quotationDetails['quote_total'], 2, $separator, '') . '
                      </td>
                    </tr>
                  </table>
                  <span style="font-size: 10px;"><br/>
                    ('.$pdfLanguage['all-prices'].' '.$currency.')
                  </small>
                </td>
              </tr>
            </table>';
            $html .= '<div style="page-break-before: always;"></div>';
            foreach ($itemList as $itemKey => $quoteItems) {
                $orderItemNo = $itemKey + 1;
                if ($quoteItems['product_availability']) {
                    $html .= '<table width="100%" cellspacing="0" cellpadding="0" border="0">
                  <tr>
                    <td colspan="2"><br/>
                      <span style="text-align: '.$rtlRightAlign.'; font-size: 14px;"><strong>'.$pdfLanguage['order-item'].' #' . $orderItemNo . '</strong></span>
                    </td>
                  </tr>
                  <tr>
                    <td style="vertical-align: top;" width="20%">
                      <table width="100%" cellspacing="0" cellpadding="0" border="0">
                        <tr>
                          <td style="padding: 5px;">
                            <span style="width: 170px; margin: 0;">
                              <img src="' . $quoteItems['product_store_image']['src'] . '" style="width : auto; hight: 150px;" alt=""/>
                            </span>
                          </td>
                        </tr>
                      </table>
                    </td>
                    <td style="vertical-align: top; padding-left: 40px;" width="80%"><br/>
                      <span style="font-size: 14px; margin-bottom: 20px;"> 
                        ' . $quoteItems['product_name'] . '
                      </span><br/>
                      <span style="font-size: 13px; margin-bottom: 20px;"> 
                        ' . $quoteItems['product_description'] . '
                      </span><br/><br/>';

                    if ($quoteItems['product_id'] == $quoteItems['variant_id']) {
                        $html .= '<table width="100%" cellspacing="0" cellpadding="5" border="0" style="border: 0px solid #e3e3e3; font-size: 14px;">
                        <tr>
                          <td bgcolor="#e3e4e6" style="text-align: center; border: 1px solid #d3d3d3;"><strong> '.$pdfLanguage['product-type'].'</strong></td>
                          <td style="text-align: center; padding: 6px 10px 10px 10px; border: 1px solid #e3e3e3;"> 
                            Simple Product
                          </td>
                        </tr>
                        <tr>
                          <td bgcolor="#e3e4e6" style="text-align: center; border: 1px solid #d3d3d3; background-color: #eee;"><strong> '.$pdfLanguage['quantity'].'</strong></td>
                          <td style="text-align: center; padding: 6px 10px 10px 10px; border: 1px solid #e3e3e3;"> 
                            ' . $quoteItems['product_variant'][0]['quantity'] . '
                          </td>
                        </tr>';
                        if (!empty($quoteItems['sticker_data']) && $quoteItems['sticker_data']['stickerOption'] == 'sheet' && !empty($quoteItems['sticker_data']['sheetInfo'])) {
                        } else {
                            $html .= '<tr>
                              <td bgcolor="#e3e4e6" style="text-align: center; border: 1px solid #d3d3d3;"><strong> '.$pdfLanguage['price'].'</strong></td>
                              <td style="text-align: center; padding: 6px 10px 10px 10px; border: 1px solid #e3e3e3;">
                                <span> '.$currency.'</span> ' . number_format($quoteItems['product_variant'][0]['unit_price'], 2, $separator, '') . '
                              </td>
                            </tr>';
                        }
                      $html .= '</table>';
                    } else {
                        $html .= '<table width="100%" cellspacing="0" cellpadding="5" border="0" style="border: 0px solid #e3e3e3; font-size: 14px;">';
                        foreach ($quoteItems['product_variant'] as $variantKey => $variantsData) {
                            $varSlNo = $variantKey + 1;
                            if ($variantKey == 0) {
                                $html .= '
                            <tr>
                              <td bgcolor="#e3e4e6" style="text-align: center; border: 1px solid #d3d3d3; "><strong> #</strong></td>';
                                foreach ($variantsData['attribute'] as $attKey => $attribute) {
                                    $html .= '<td bgcolor="#e3e4e6" style="text-align: center; border: 1px solid #d3d3d3;"><strong> ' . $attKey . '</strong></td>';
                                }
                                $html .= '
                              <td bgcolor="#e3e4e6" style="text-align: center; border: 1px solid #d3d3d3;"><strong> '.$pdfLanguage['quantity'].'</strong></td>
                              <td bgcolor="#e3e4e6" style="text-align: center; border: 1px solid #d3d3d3;"><strong> '.$pdfLanguage['price'].'</strong></td>
                            </tr>';
                            }
                            $html .= '<tr>
                          <td style="text-align: center; padding: 6px 10px 10px 10px; border: 1px solid #e3e3e3;"> 
                            ' . $varSlNo . '
                          </td>';
                            foreach ($variantsData['attribute'] as $attribute) {
                                $html .= '<td style="text-align: center; padding: 6px 10px 10px 10px; border: 1px solid #e3e3e3;"> ' . $attribute['name'] . '</td>';
                            }
                            $updatedPrices = (isset($variantsData['updated_price']) && $variantsData['updated_price'] != '') ? $variantsData['updated_price'] : $variantsData['unit_price'];
                            $html .= '<td style="text-align: center; padding: 6px 10px 10px 10px; border: 1px solid #e3e3e3;"> ' . $variantsData['quantity'] . '</td>
                          <td style="padding: 6px 10px 10px 10px; border: 1px solid #e3e3e3; text-align: center;"> <span>'.$currency.'</span>' . number_format($updatedPrices, 2, $separator, '') . '
                          </td>
                        </tr>';
                        }
                        $html .= '</table>';
                    }
                    if ($quoteItems['is_custom_size'] && $quoteItems['is_variable_decoration'] && $quoteItems['custom_size_dimension'] != '') {
                        $customSizeDimensionArr = explode(' x ', $quoteItems['custom_size_dimension']);
                        $html .= '<span style="text-align: center; font-size: 13px;">Dimension changed to: '.number_format($customSizeDimensionArr[0], 2, '.', '').'x'.number_format($customSizeDimensionArr[1], 2, '.', '').' '.$quoteItems['custom_size_dimension_unit'].'</span>';
                    }
                    $html .= '</td>
                  </tr>
                  <tr>
                    <td colspan="2">';
                    if (!empty($quoteItems['upload_designs'])) {
                      $html .= '<br/><br/><p style="text-align: '.$rtlRightAlign.'; font-size: 14px; margin-top: 20px;"><strong>'.$pdfLanguage['artwork-used'].'</strong></p><br/><br/>';
                    }
                    foreach ($quoteItems['upload_designs'] as $uploadDesigns) {
                        if (!empty($uploadDesigns['decoration_area'])) {
                            $html .= '<table width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 0px solid #e3e3e3; font-size: 12px;">
                        <tr>
                          <td style="padding: 12px; border: 1px solid #e3e3e3;">
                            ';
                            foreach ($uploadDesigns['decoration_area'] as $decorationArea) {
                                $html .= '<table width="100%" cellspacing="0" cellpadding="5" border="0">
                              <tr>
                                <td width="25%" style="vertical-align: top;">
                                <span style"text-align: center; font-size:12px"><strong>'.$pdfLanguage['preview'].'</strong></span><br/>
                                  <span style="margin: 0; width: 150px; height: 150px;" >
                                    <img src="' . $decorationArea['upload_preview_url'] . '" alt="" style="max-width: 100px; max-height:100px" />
                                  </span>
                                </td>
                                 <td width="25%" style="vertical-align: top;">
                                 <span style"text-align: center; font-size:12px"><strong>'.$pdfLanguage['design'].'</strong></span><br/>
                                  <span style="margin: 0; width: 100px; height: 100px;">';
                                $html .= '<img src="' . $decorationArea['upload_design_url'] . '" alt="" style="max-width: 150px; max-height:150px" />';
                                $html .= '</span>
                                </td>
                                <td width="50%" style="text-align: '.$rtlRightAlign.'; vertical-align: top;">
                                  <table width="100%" cellspacing="0" cellpadding="0" border="0">
                                    <tr>
                                      <td width="40%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.$pdfLanguage['product-side'].'</strong></td>
                                      <td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">' . $uploadDesigns['side_name'] . '</td>
                                    </tr>
                                    <tr>
                                      <td width="40%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.$pdfLanguage['print-method'].'</strong></td>
                                      <td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">' . $decorationArea['print_methods'] . '</td>
                                    </tr>
                                     <tr>
                                      <td width="40%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.$pdfLanguage['name'].'</strong></td>
                                      <td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">' . $decorationArea['decoration_area'] . '</td>
                                    </tr>';
                                    if ($decorationArea['print_area_name'] != '') {
                                        $html .='<tr>
                                          <td width="40%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.$pdfLanguage['area-name'].'</strong></td>
                                          <td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">' . $decorationArea['print_area_name'] . '</td>
                                        </tr>';
                                    }
                                    $html .='<tr>
                                      <td width="40%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.$pdfLanguage['height'].'</strong></td>
                                      <td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">' . $decorationArea['height'] . ' ' . $decorationArea['measurement_unit'] . '</td>
                                    </tr>
                                    <tr>
                                      <td width="40%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.$pdfLanguage['width'].'</strong></td>
                                      <td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">' . $decorationArea['width'] . ' ' . $decorationArea['measurement_unit'] . '</td>
                                    </tr>
                                  </table>
                                </td>
                              </tr>
                              </table>';
                            }
                            $html .= '</td></tr></table>';
                        }
                    }
                    if (isset($quoteItems['sticker_data']) && !empty($quoteItems['sticker_data'])) {
                        $stickerInfo = $quoteItems['sticker_data'];
                        $html .= '<span style="text-align: '.$rtlRightAlign.'; font-size: 14px; margin-top: 20px;">
                            '.$pdfLanguage['sticker-info'].'
                        </span>
                        <table width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 0px solid #e3e3e3; font-size: 12px;">
                            <tbody>
                            <td>
                                <table width="100%" cellspacing="0" cellpadding="0" border="0">
                                    <tr>
                                      <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">'.$pdfLanguage['size'].'</td>
                                      <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.$stickerInfo['width'].' x '. $stickerInfo['height'].' '.$quoteItems['upload_designs'][0]['decoration_area'][0]['measurement_unit'].'</strong></td>
                                    </tr>
                                    <tr>
                                      <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">'.$pdfLanguage['cut-type'].'</td>
                                      <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.ucfirst($stickerInfo['stickerType']).'</strong></td>
                                    </tr>
                                    <tr>
                                      <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">'.$pdfLanguage['sticker-option'].'</td>
                                      <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.ucfirst($stickerInfo['stickerOption']).'</strong></td>
                                    </tr>
                                </table>
                            </td>
                            <td>
                                <table width="100%" cellspacing="0" cellpadding="0" border="0">
                                    <tr>
                                      <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">'.$pdfLanguage['material'].'</td>
                                      <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.$stickerInfo['material'].'</strong></td>
                                    </tr>
                                    <tr>
                                      <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">'.$pdfLanguage['cutline'].'</td>
                                      <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.$stickerInfo['cutline'].'</strong></td>
                                    </tr>';
                                    if (!empty($stickerInfo['sheetInfo'])) {
                                        $sheetDetails = '<table width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 0px solid #e3e3e3; font-size: 12px; ">
                                      <tbody>
                                        <tr>
                                          <th style="border: 1px solid #d3d3d3; text-align: center; padding: 6px 10px;">'.$pdfLanguage['sheet'].'</th>
                                          <th style="border: 1px solid #d3d3d3; text-align: center; padding: 6px 10px;">'.$pdfLanguage['quantity'].'</th>
                                          <th style="border: 1px solid #d3d3d3; text-align: center; padding: 6px 10px;">'.$pdfLanguage['price'].'</th>
                                        </tr>';
                                        foreach ($stickerInfo['sheetInfo'] as $sheetInfo) {
                                            $sheetPrice = (isset($sheetInfo['updated_price'])) ? $sheetInfo['updated_price'] : $sheetInfo['price'];
                                                $sheetDetails .= '<tr>
                                              <td style="padding: 6px 10px; border: 1px solid #e3e3e3; text-align: center;">'.$sheetInfo['name'].'</td>
                                              <td style="padding: 6px 10px; border: 1px solid #e3e3e3; text-align: center;">'.$sheetInfo['quantity'].'</td>
                                              <td style="padding: 6px 10px; border: 1px solid #e3e3e3; text-align: center;"><span style="font-family: '.$fontFamily.';">'.$currency.'</span> ' . number_format($sheetPrice, 2, $separator, '') . '</td>
                                            </tr>';
                                        }
                                        $sheetDetails .='</tbody></table>';
                                        $html .= '<tr>
                                          <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">'.$pdfLanguage['sheet-info'].'</td>
                                          <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">'.$sheetDetails.'</td>
                                        </tr>';
                                    }
                                    if (!empty($stickerInfo['rollInfo'])) {
                                        $rollInfo = $stickerInfo['rollInfo'];
                                        $html .= '<tr>
                                          <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;">'.$pdfLanguage['roll-info'].'</td>
                                          <td style="text-align: '.$rtlRightAlign.'; padding: 0 0px 4px 20px;"><strong>'.$rollInfo['name'].'</strong></td> 
                                          <td><img src="'.$rollInfo['option']['file_name'].'" alt="" style="width: auto; height: 35px;"/>
                                          </td>
                                        </tr>';
                                    }
                                $html .= '</table>
                            </td>
                            </tbody>
                        </table>';
                    }
                    $html .= '</td>
                  </tr>
                </table>';
                } else {
                    $html .= '<table width="100%" cellspacing="0" cellpadding="0">
                  <tr>
                    <td colspan="2"><br/>
                      <p><strong>'.$pdfLanguage['order-item'].' #' . $orderItemNo . '</strong></p>
                    </td>
                  </tr>
                  <tr>
                    <td colspan="2">
                      <spn>'.$pdfLanguage['no-product'].'</span>
                    </td>
                  </tr>
                  </table>';
                }
            }
            $html .= '</table>
        </body></html>';
            $fileNames = create_tcpdf($html, $filePath, $quotationDetails['quote_id'], $toolLang);
            $dir = $filePath . $fileNames;
            if (file_exists($dir)) {
                if ($returnType == 1) {
                    return true;
                }
                $jsonResponse = [
                    'status' => 1,
                    'message' => message('Quotation Pdf', 'done'),
                ];
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET: Agent list with quotation count
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   13 May 2020
     * @return json response wheather data is added or any error occured
     */
    public function agentListWithQuote($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $getStoreDetails = get_store_details($request);
        $jsonResponse = [
            'status' => 0,
            'message' => message('Agent', 'error'),
        ];
        $userId = $request->getQueryParam('user_id');
        $view = $request->getQueryParam('view');
        $userInit = new User();
        $agentData = $userInit->select('xe_id as id', 'name', 'email');
        if (isset($view) && $view == 'list') {
            $agentData->whereNotIn('xe_id', [$userId]);
        }
        $agentData->where('store_id', $getStoreDetails['store_id']);
        
        $agentList = json_clean_decode($agentData->get(), true);
        $quotationInit = new Quotations();
        if (!empty($agentList)) {
            $agentResult = [];
            foreach ($agentList as $agents) {
                $newAgentList = $agents;
                //Get quotation count
                $quoteData = $quotationInit->where('agent_id', $agents['id']);
                $quoteCount = $quoteData->count();
                $newAgentList['quote_count'] = $quoteCount;
                array_push($agentResult, $newAgentList);
            }
            $jsonResponse = [
                'status' => 1,
                'data' => $agentResult,
            ];
        } else {
            $jsonResponse = [
                'status' => 1,
                'message' => message('Agent', 'not_found'),
                'data' => []
            ];
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET : Items w.r.t quotation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     * @param $returnType     Response return type
     *
     * @author debashrib@riaxe.com
     * @date   14 May 2020
     * @return json
     */
    public function getQuoteItems($request, $response, $args, $returnType = 0)
    {
        if (isset($_REQUEST['_token']) && !empty($_REQUEST['_token'])) {
             $getToken = $_REQUEST['_token'];
        } else {
            $getToken = '';
        }
        $getStoreDetails = get_store_details($request);
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Items', 'error'),
        ];
        if (!empty($args['id'])) {
            $quotationId = to_int($args['id']);
            $quoteItemsInit = new QuotationItems();
            $quoteItemFilesInit = new QuotationItemFiles();
            $variantsInit = new QuotationItemVariants();
            $getItems = $quoteItemsInit->where('quote_id', $quotationId);
            $itemDetails = [];
            $itemDataFilePath = path('abs', 'quotation').$quotationId.'/itemData.json';
            $itemDataJson = read_file($itemDataFilePath);
            $itemDataJsonArr = json_clean_decode($itemDataJson, true);
            //Get All Print Profile
            $printAreaInit = new PrintArea();
            $printArea = $printAreaInit->select('xe_id', 'name', 'width', 'height');
            $allPrintMethodesArr = $printArea->get();
            $allPrintMethodesArr = json_clean_decode($allPrintMethodesArr, true);
            $orderDwonloadObj = new OrderDownloadController();
            if ($getItems->count() > 0) {
                $getItemsData = $getItems->get()->toArray();
                foreach ($getItemsData as $itemsData) {
                    $newItemData = $itemsData;
                    $newItemData['type'] = $itemsData['product_type'];
                    unset($newItemData['product_type']);
                    if ($itemDataJsonArr[$itemsData['xe_id']] != '') {
                        $productDecorationArr = $itemDataJsonArr[$itemsData['xe_id']];
                    } else {
                        $productDecorationArr = $this->getItemProductData($request, $response, $itemsData['product_id'], $quotationId, $itemsData['xe_id'], 1);
                    }
                    unset($newItemData['product_deco_data']);
                    if (isset($productDecorationArr['price']) && ($productDecorationArr['price'] != '' || $productDecorationArr['price'] == 0)) {
                        $firstImageData = $productDecorationArr['store_images'];
                        //commented for some common store specific issue, it will be removed after all the store level testing

                        // if ($itemsData['is_decorated_product'] == 1) {
                        //     $productsControllerInit = new ProductsController();
                        //     $imageData = $productsControllerInit->getAssocProductImages($itemsData['product_id']);
                        //     if (!empty($imageData)) {
                        //         $firstImageData = [
                        //             'src' => $imageData[0],
                        //             'thumbnail' => $imageData[0]
                        //         ];
                        //     }
                        // }
                        $newItemData['product_store_image'] = $firstImageData;
                        $newItemData['product_name'] = $productDecorationArr['product_name'];
                        $newItemData['product_description'] = $productDecorationArr['product_description'];
                        $newItemData['product_sku'] = $productDecorationArr['sku'];
                        $newItemData['product_price'] = $productDecorationArr['price'];
                        $newItemData['is_configurator'] = isset($productDecorationArr['is_configurator']) ? $productDecorationArr['is_configurator'] : false;
                        //add custom product price for custom vda product
                        if ($itemsData['is_custom_size'] == 1) {
                            $newItemData['custom_product_price'] = $itemsData['unit_total'] - $itemsData['design_cost'];
                        }
                        $newItemData['variant_id'] = $productDecorationArr['variant_id'];
                        $newItemData['upload_designs'] = [];
                        if ($itemsData['artwork_type'] == 'uploaded_file') {
                            $getFiles = $quoteItemFilesInit->where('item_id', $itemsData['xe_id']);
                            //Get product side data
                            $allSideArr = $productDecorationArr['sides'];
                            $type =  gettype($allSideArr);
                            if ($type == 'object') {
                                $allSideArr = json_clean_decode($allSideArr, true);
                            }
                            $measurementUnitName = $productDecorationArr['measurement_unit'];

                            $uploadDesigns = [];
                            if ($getFiles->count() > 0) {
                                $getSideDataArr = $getFiles->select('side_id')->groupBy('side_id')->get()->toArray();
                                foreach ($getSideDataArr as $sideKey => $sideData) {
                                    $newSideKey = $sideKey+1;
                                    $tempSideData = $sideData;
                                    $sideId = $tempSideData['side_id'];
                                    if(!empty($allSideArr)) {
                                        $sideArr = array_filter($allSideArr, function ($item) use ($sideId) {
                                            return $item['xe_id'] == $sideId;
                                        });
                                        
                                        $sideArr = $sideArr[array_keys($sideArr)[0]];
                                    }
                                    $tempSideData['side_name'] = ($itemsData['is_variable_decoration'] == 0) ? $sideArr['side_name'] : 'Side '.$newSideKey;
                                    $tempSideData['thumbnail'] = ($itemsData['is_variable_decoration'] == 0) ? $sideArr['image']['thumbnail'] : $productDecorationArr['store_images']['thumbnail'];
                                    $decorationDataArr = $quoteItemFilesInit->where(['item_id' => $itemsData['xe_id'], 'side_id' => $sideData['side_id']])->get();
                                    $decorationArea = [];
                                    foreach ($decorationDataArr as $decorationData) {
                                        $tempDecorationArea = $decorationData;
                                        $allDecoArr = $sideArr['product_decoration_setting'];
                                        $decorationAreaId = $decorationData['decoration_area_id'];
                                        $decorationSettingId = $decorationData['decoration_settings_id'];
                                        $decoArr = [];
                                        if (!empty($allDecoArr)) {
                                            $decoArr = array_filter($allDecoArr, function ($item) use ($decorationSettingId) {
                                                return $item['xe_id'] == $decorationSettingId;
                                            });
                                            $decoArr = $decoArr[array_keys($decoArr)[0]];
                                        }
                                        $tempDecorationArea['decoration_settings_id'] = $decorationSettingId;
                                        $tempDecorationArea['decoration_area'] = ($itemsData['is_variable_decoration'] == 0) ? $decoArr['name'] : 'Side '.$newSideKey;
                                        $allPrintProfileArr = $decoArr['print_profile_decoration_settings'];
                                        //get print method
                                        $printMethodId = $decorationData['print_method_id'];
                                        $finalPrintMethod = [];
                                        foreach ($allPrintProfileArr as $printProfileArr) {
                                            $tempPrintMethods = $printProfileArr['print_profile'];
                                            $printProfileArr = array_filter($tempPrintMethods, function ($item) use ($printMethodId) {
                                                return $item['xe_id'] == $printMethodId;
                                            });
                                            $printProfileArr = $printProfileArr[array_keys($printProfileArr)[0]];
                                            if ($printProfileArr['xe_id'] == $printMethodId) {
                                                array_push($finalPrintMethod, $printProfileArr);
                                            }
                                        }
                                        if ($itemsData['is_variable_decoration'] == 1) {
                                            $getVdaPrintMethod =  DB::table("print_profiles")->select('name')->where('xe_id', '=', $printMethodId);
                                            $vdpPrintMethodData = $getVdaPrintMethod->first();
                                            $finalPrintMethod[0]['name'] = $vdpPrintMethodData->name;
                                        }
                                        $tempDecorationArea['print_methods'] = $finalPrintMethod[0]['name'];
                                        $printMethodsArr = array_filter($allPrintMethodesArr, function ($item) use ($decorationAreaId) {
                                            return $item['xe_id'] == $decorationAreaId;
                                        });
                                        $printMethodsArr = $printMethodsArr[array_keys($printMethodsArr)[0]];
                                        //Design hight and width
                                        $extraDataValue = $decorationData['extra_data'];
                                        $extraDataArr = json_clean_decode($extraDataValue, true);

                                        $tempDecorationArea['height'] = $printMethodsArr['height'];
                                        $tempDecorationArea['width'] = $printMethodsArr['width'];
                                        $tempDecorationArea['measurement_unit'] = $measurementUnitName;
                                        $tempDecorationArea['print_area_name'] = $printMethodsArr['name'];
                                        $tempDecorationArea['upload_design_url'] = path('read', 'quotation') . $quotationId . '/' . $itemsData['xe_id'] . '/' . $sideId . '/' . $decorationData['file'];
                                        $tempDecorationArea['upload_preview_url'] = path('read', 'quotation') . $quotationId . '/' . $itemsData['xe_id'] . '/' . $sideId . '/' . $decorationData['preview_file'];
                                        $tempDecorationArea['design_height'] = (!empty($extraDataArr) && isset($extraDataArr['design_height']) && $extraDataArr['design_height'] != '') ? $extraDataArr['design_height'] : '';
                                        $tempDecorationArea['design_width'] = (!empty($extraDataArr) && isset($extraDataArr['design_width']) && $extraDataArr['design_width'] != '') ? $extraDataArr['design_width'] : '';
                                        unset(
                                            $tempDecorationArea['xe_id'],
                                            $tempDecorationArea['item_id'],
                                            $tempDecorationArea['side_id'],
                                            $tempDecorationArea['extra_data']
                                        );
                                        array_push($decorationArea, $tempDecorationArea);
                                    }
                                    $tempSideData['decoration_area'] = $decorationArea;
                                    array_push($uploadDesigns, $tempSideData);
                                }
                                $newItemData['upload_designs'] = $uploadDesigns;
                            }
                        } else {
                            $uploadDesigns = [];
                            $customDesignId = $itemsData['custom_design_id'];
                            $deisgnStatePath = path('abs', 'design_state') . 'artworks';
                            $orderJsonPath = $deisgnStatePath . '/' . $customDesignId . ".json";
                            //Json file path of pre-deco product
                            if (!file_exists($orderJsonPath)) {
                                $orderJsonPath = path('abs', 'design_state') . 'predecorators' . '/' . $customDesignId . ".json";
                            }
                            if (file_exists($orderJsonPath)) {
                                $orderJson = read_file($orderJsonPath);
                                $jsonContent = json_clean_decode($orderJson, true);
                                $designProductDataArr = $jsonContent['design_product_data'][0]['design_urls'];
                                $getSideDataArr = $jsonContent['sides'];
                                foreach ($getSideDataArr as $sideKey => $sideData) {
                                    $tempSideData['side_id'] = 0;
                                    $tempSideData['side_name'] = $sideData['side_name'];
                                    $tempSideData['thumbnail'] = $sideData['url'];
                                    $decorationArea = [];
                                    $svgFileName = $customDesignId . '_' . $sideKey . ".svg";
                                    $pngFileName = $customDesignId . '_' . $sideKey . ".png";
                                    $path = path('abs', 'quotation') . $quotationId . '/' . $itemsData['xe_id'] . '/';
                                    $svgPath = $path . $svgFileName;
                                    $pngPath = $path . $pngFileName;
                                    if (!file_exists($path)) {
                                        create_directory($path);
                                    }
                                    if (!file_exists($svgPath)) {
                                        $parameter = array(
                                            'key' => $sideKey, 'ref_id' => $customDesignId,
                                            'item_path' => '',
                                            'svg_preview_path' => $svgPath,
                                            'value' => $sideData,
                                            'is_design' => 1,
                                        );
                                        $orderDwonloadObj->createSideSvgByOrderId($parameter);
                                        if (file_exists($svgPath)) {
                                            $orderDwonloadObj->svgConvertToPng($pngPath, $svgPath);
                                        }
                                    }
                                    foreach ($sideData['print_area'] as $pKey => $printArea) {
                                        if ($printArea['isDesigned'] == 1) {
                                            $fKeyArr = explode('bound_', $pKey);
                                            if (!empty($sideData['assets_doc_path'])) {
                                                $uploadDesign = $sideData['assets_doc_path'][$fKeyArr[1]];
                                                $uploadDesignArr = explode('/assets/', $uploadDesign);
                                                $file = ASSETS_PATH_R . $uploadDesignArr[1];
                                                if (file_exists(ASSETS_PATH_W . $uploadDesignArr[1])) {
                                                    $uploadDesignUrl = $file;
                                                } else {
                                                    $uploadDesignUrl =  $this->getS3URL($file, $getStoreDetails['store_id']);
                                                }
                                            } else {
                                                $uploadDesignUrl = path('read', 'quotation') . $quotationId . '/' . $itemsData['xe_id'] . '/side_'.$pKey.'/Layer_'.$fKeyArr[1].'_side_'.$pKey.'_'.$itemsData['xe_id'].'_'.$quotationId.'.png';
                                            }
                                            $newPrintAreaArr = [
                                                'decoration_area_id' => 0,
                                                'print_method_id' => $printArea['print_method_id'],
                                                'file' => $uploadDesignUrl,
                                                'preview_file' => '',
                                                'decoration_area' => $printArea['name'],
                                                'print_methods' => $printArea['print_method_name'],
                                                'height' => $printArea['print_area']['height'],
                                                'width' => $printArea['print_area']['width'],
                                                'measurement_unit' => $sideData['print_unit'],
                                                'print_area_name' => $printArea['print_area']['name'],
                                                'upload_design_url' => path('read', 'quotation') . $quotationId . '/' . $itemsData['xe_id'] . '/' . $pngFileName,
                                                'upload_preview_url' => $designProductDataArr[$sideKey],
                                                'custom_size_dimension' => ($itemsData['is_variable_decoration'] == 1 && $itemsData['is_custom_size'] == 1) ? $itemsData['custom_size_dimension'] : '',
                                            ];
                                            array_push($decorationArea, $newPrintAreaArr);
                                        }
                                    }
                                    $tempSideData['decoration_area'] = $decorationArea;
                                    array_push($uploadDesigns, $tempSideData);
                                }
                            }
                            $newItemData['upload_designs'] = $uploadDesigns;
                        }
                        //Get variants
                        $getVariants = $variantsInit->where('item_id', $itemsData['xe_id']);
                        $variants = [];
                        if ($getVariants->count() > 0) {
                            $getVariantData = $getVariants->get();
                            foreach ($getVariantData as $variantData) {
                                $newVariant = $variantData;
                                if (($variantData['attribute'] == '' || $variantData['attribute'] == 'null') && $variantData['variant_id'] != 0) {
                                    //get variant attribute
                                    if ($getToken != '') {
                                        $getAtt = call_curl(
                                            [],
                                            'product-details/' . $itemsData['product_id'] . '?variant_id=' . $variantData['variant_id'].'&_token='.$getToken, 'GET'
                                        );
                                    } else {
                                        $getAtt = call_curl(
                                            [],
                                            'product-details/' . $itemsData['product_id'] . '?variant_id=' . $variantData['variant_id'], 'GET'
                                        );
                                    }
                                    $getAtt = $getAtt['data'];
                                    $newVariant['attribute'] = !empty($getAtt['attributes']) ? $getAtt['attributes'] : [];
                                    //save attribute into database
                                    $updateAtt = [
                                        'attribute' => json_encode($getAtt['attributes'])
                                    ];
                                    $variantsInit = new QuotationItemVariants();
                                    $variantsInit->where('xe_id', $variantData['xe_id'])
                                        ->update($updateAtt);
                                } else {
                                    $newVariant['attribute'] = json_clean_decode($variantData['attribute'], true);
                                }
                                $newVariant['updated_price'] = ($variantData['updated_price'] != '' || $variantData['updated_price'] == 0) ? $variantData['updated_price'] : $variantData['unit_price'];
                                unset($newVariant['item_id']);
                                array_push($variants, $newVariant);
                            }
                        }
                        $newItemData['product_variant'] = $variants;
                        if ($itemsData['is_sticker'] == 1) {
                            $newItemData['custom_product_price'] = $variants[0]['unit_price'];
                        }
                        $newItemData['product_availability'] = true;
                    } else {
                        $newItemData['product_availability'] = false;
                    }
                    //Get team-jersey data
                    if (isset($itemsData['is_team_jersey']) && $itemsData['is_team_jersey'] == 1) {
                        $teamJerseyDataInit = new TeamJerseyData();
                        $getTeamJersey = $teamJerseyDataInit->where('quote_item_id', $itemsData['xe_id']);
                        if ($getTeamJersey->count() > 0) {
                            $getTeamJerseyData = $getTeamJersey->first();
                            $getTeamJerseyData = json_clean_decode($getTeamJerseyData, true);
                            $newItemData['team_jersey_data'] = json_clean_decode($getTeamJerseyData['data']);
                        }
                    }
                    //Get sticker data
                    if (isset($itemsData['is_sticker']) && $itemsData['is_sticker'] == 1) {
                        $stickerDataInit = new QuoteStickerData();
                        $getSticker = $stickerDataInit->where('quote_item_id', $itemsData['xe_id']);
                        if ($getSticker->count() > 0) {
                            $getStickerData = $getSticker->first();
                            $getStickerData = json_clean_decode($getStickerData, true);
                            $newItemData['sticker_data'] = json_clean_decode($getStickerData['data']);
                        }
                    }
                    array_push($itemDetails, $newItemData);
                }
                if (!empty($itemDetails)) {
                    if ($returnType == 1) {
                        return $itemDetails;
                    } else {
                        $jsonResponse = [
                            'status' => 1,
                            'data' => $itemDetails,
                        ];
                    }
                }
            } else {
                $jsonResponse = [
                    'status' => 1,
                    'data' => [],
                ];
            }
            
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: make quotation duplicate
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   14 May 2020
     * @return array
     */
    public function duplicateQuotation($request, $response)
    {
        $getStoreDetails = get_store_details($request);
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Duplicate', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        if ($allPostPutVars['quote_id'] != '' && $allPostPutVars['quote_id'] > 0) {
            $quotationId = $allPostPutVars['quote_id'];
            $isUserAccount = isset($allPostPutVars['is_user_account']) ? $allPostPutVars['is_user_account'] : 0;
            $quotationInit = new Quotations();
            $tagInit = new QuotationTagRelation();
            $itemsInit = new QuotationItems();
            $variantsInit = new QuotationItemVariants();
            $itemFilesInit = new QuotationItemFiles();
            $teamJerseyDataInit = new TeamJerseyData();
            $stickerDataInit = new QuoteStickerData();
            $quoteData = $quotationInit->where([
                'xe_id' => $quotationId,
                'store_id' => $getStoreDetails['store_id'],
            ]);
            if ($quoteData->count() > 0) {
                $quoteDetails = $quoteData->first();
                $quoteDetails = $oldQuotation = json_clean_decode($quoteDetails, true);
                $quoteSource = $quoteDetails['quote_source'];
                $quoteUId = $quoteDetails['quote_id'];
                unset(
                    $quoteDetails['xe_id'],
                    $quoteDetails['agent_id'],
                    $quoteDetails['created_at'],
                    $quoteDetails['updated_at']
                );
                $quoteDetails['quote_id'] = $this->generateQuoteId($request, $quoteDetails['quote_id']);
                //Get Open status id
                $statusInit = new ProductionStatus();
                $getStatusData = $statusInit->select('xe_id')->where([
                    'store_id' => $getStoreDetails['store_id'], 
                    'slug' => 'open',
                    'module_id' => 1
                ]);
                if ($getStatusData->count() > 0) {
                   $getStatusDataArr = $getStatusData->first(); 
                   $getStatusDataArr = json_clean_decode($getStatusDataArr, true);
                }
                $quoteDetails['status_id'] = $getStatusDataArr['xe_id'];
                $quoteDetails['draft_flag'] = '1';
                $quoteDetails['archive_status'] = '0';
                $quoteDetails['created_by'] = $allPostPutVars['user_type'];
                $quoteDetails['created_by_id'] = $allPostPutVars['user_id'];
                if ($allPostPutVars['user_type'] == 'agent') {
                    $quoteDetails['agent_id'] = $allPostPutVars['user_id'];
                }
                if ($isUserAccount == 1) {
                    $quoteDetails['quote_source'] = 'tool'; 
                }
                $quotation = new Quotations($quoteDetails);
                if ($quotation->save()) {
                    $quotationLastId = $quotation->xe_id;
                    $quotationLastUId = $quotation->quote_id;
                    //Get Tags
                    $tagData = $tagInit->select('tag_id')->where('quote_id', $quotationId);
                    if ($tagData->count()) {
                        $tagDetailsArr = $tagData->get()->toArray();
                        $tagDetailsArr = array_column($tagDetailsArr, 'tag_id');
                        //Save Tags
                        $this->saveQuoteTags($quotationLastId, $tagDetailsArr);
                    }
                    //get Items
                    $itemsData = $itemsInit->where('quote_id', $quotationId);
                    if ($itemsData->count() > 0) {
                        $itemsDetails = $itemsData->get()->toArray();
                        //Get the item decoration json file
                        $itemDecojsonContent = [];
                        $itemJsonFilePath = path('abs', 'quotation') . $quotationId . '/itemData.json';
                        if (file_exists($itemJsonFilePath)) {
                            $itemDecoJson = read_file($itemJsonFilePath);
                            $itemDecojsonContent = json_clean_decode($itemDecoJson, true);
                        }
                        $itemJsonArr = [];
                        foreach ($itemsDetails as $items) {
                            $saveItems = $items;
                            $tempItemId = $saveItems['xe_id'];
                            unset($saveItems['xe_id']);
                            $saveItems['quote_id'] = $quotationLastId;
                            $itemsObj = new QuotationItems($saveItems);
                            if ($itemsObj->save()) {
                                $lastItemId = $itemsObj->xe_id;
                                $itemJsonArr[$lastItemId] = $itemDecojsonContent[$tempItemId];
                                //Get Files
                                $itemFilesData = $itemFilesInit->where('item_id', $items['xe_id']);
                                if ($itemFilesData->count() > 0) {
                                    $itemsFilesDetails = $itemFilesData->get()->toArray();
                                    foreach ($itemsFilesDetails as $files) {
                                        $files['item_id'] = $lastItemId;
                                        $filesObj = new QuotationItemFiles($files);
                                        //Copy files to new quotation
                                        $souFileDir = path('abs', 'quotation') . $quotationId . '/' . $items['xe_id'] . '/' . $files['side_id'] . '/' . $files['file'];
                                        $souPreviewDir = path('abs', 'quotation') . $quotationId . '/' . $items['xe_id'] . '/' . $files['side_id'] . '/' . $files['preview_file'];
                                        $disFileDir = path('abs', 'quotation') . $quotationLastId . '/' . $lastItemId . '/' . $files['side_id'];
                                        if (!file_exists($disFileDir)) {
                                            create_directory($disFileDir);
                                        }
                                        if (copy($souFileDir, $disFileDir . '/' . $files['file'])) {
                                            copy($souPreviewDir, $disFileDir . '/' . $files['preview_file']);
                                            $filesObj->save();
                                        }
                                    }
                                }
                                //Get Variant
                                $variantData = $variantsInit->where('item_id', $items['xe_id']);
                                if ($variantData->count() > 0) {
                                    $variantArr = $variantData->get()->toArray();
                                    foreach ($variantArr as $variants) {
                                        $variants['item_id'] = $lastItemId;
                                        $variantObj = new QuotationItemVariants($variants);
                                        $variantObj->save();
                                    }
                                }
                                //Save team jersey data
                                $jerseyData = $teamJerseyDataInit->where('quote_item_id', $items['xe_id']);
                                if ($jerseyData->count() > 0) {
                                    $getJerseyData = $jerseyData->first()->toArray();
                                    $saveJerseyData = [
                                        'quote_item_id' => $lastItemId,
                                        'data' => $getJerseyData['data'],
                                    ]; 
                                    $saveJersey = new TeamJerseyData($saveJerseyData);
                                    $saveJersey->save();
                                }
                                //Save sticker data
                                $stickerData = $stickerDataInit->where('quote_item_id', $items['xe_id']);
                                if ($stickerData->count() > 0) {
                                    $getStickerData = $stickerData->first()->toArray();
                                    $saveStickerData = [
                                        'quote_item_id' => $lastItemId,
                                        'data' => $getStickerData['data'],
                                    ]; 
                                    $saveSticker = new QuoteStickerData($saveStickerData);
                                    $saveSticker->save();
                                }
                            }
                        }
                        //Save item data in json file
                        $filePath = path('abs', 'quotation') . $quotationLastId;
                        if (!file_exists($filePath)) {
                            create_directory($filePath);
                        }
                        if (is_dir($filePath)) {
                            write_file(
                                $filePath . '/itemData.json', json_clean_encode($itemJsonArr)
                            );
                        }
                    }
                    //Add requested quote data
                    $requestFormValueInit = new QuotationRequestFormValues();
                    if ($quoteSource == 'tool') {
                        $formValue = $requestFormValueInit->where('quote_id', $quoteUId);
                        if ($formValue->count() > 0) {
                            $formValueData = $formValue->get();
                            $formValueData = json_clean_decode($formValueData, true);
                            foreach ($formValueData as $value) {
                                $saveValue = [
                                    'quote_id' => $quotationLastUId,
                                    'form_key' => $value['form_key'],
                                    'form_value' => $value['form_value'],
                                    'form_type' => $value['form_type'],
                                ];
                                $saveFormData = new QuotationRequestFormValues($saveValue);
                                $saveFormData->save();
                            }
                        }
                        $requestDetailsInit = new QuotationRequestDetails();
                        $requestDetails = $requestDetailsInit->where('quote_id', $quoteUId);
                        if ($requestDetails->count() > 0) {
                            $requestDetailsData = $requestDetails->first();
                            $requestDetailsData = json_clean_decode($requestDetailsData, true);
                            $requestData = [
                                'quote_id' => $quotationLastUId,
                                'product_details' => $requestDetailsData['product_details'],
                                'design_details' => $requestDetailsData['design_details'],
                            ];
                            $saveRequestData = new QuotationRequestDetails($requestData);
                            $saveRequestData->save();
                        }
                    }
                    if ($isUserAccount == 1) {
                        //delete previous note
                        $checkNote = $requestFormValueInit->where([
                            'quote_id' => $quotationLastUId,
                            'form_key' => 'Note',
                        ])->where('form_value', 'LIKE', '%This quotation is created from #%');
                        if ($checkNote->count() > 0) {
                            $checkNote->delete();
                        }
                        $userAccountValue = [
                            'quote_id' => $quotationLastUId,
                            'form_key' => 'Note',
                            'form_value' => 'This quotation is created from #'.$oldQuotation['quote_id'],
                            'form_type' => '',
                        ];
                        $saveUserAccountData = new QuotationRequestFormValues($userAccountValue);
                        $saveUserAccountData->save();
                    }
                }
                //Added to quote log
                //Duplicate Log
                $logData = [
                    'quote_id' => $quotationId,
                    'title' => 'Quotation duplicated',
                    'description' => "Quote is duplicated to #" . $quoteDetails['quote_id'],
                    'user_type' => $allPostPutVars['user_type'],
                    'user_id' => $allPostPutVars['user_id'],
                    'created_date' => date_time(
                        'today', [], 'string'
                    )
                ];
                $this->addingQuotationLog($logData);
                //New quote log
                $logData = [
                    'quote_id' => $quotationLastId,
                    'title' => 'Quotation created',
                    'description' => "Quotation is created from #" . $oldQuotation['quote_id'],
                    'user_type' => $allPostPutVars['user_type'],
                    'user_id' => $allPostPutVars['user_id'],
                    'created_date' => date_time(
                        'today', [], 'string'
                    )
                ];
                $this->addingQuotationLog($logData);
                $jsonResponse = [
                    'status' => 1,
                    'message' => message('Quotation Duplicate', 'clone'),
                ];
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Reject Quotation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   18 May 2020
     * @return json response wheather data is updated or any error occured
     */
    public function rejectQuotation($request, $response)
    {
        $getStoreDetails = get_store_details($request);
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Reject', 'error'),
        ];
        $allPostPutVars = $updateData = $request->getParsedBody();
        if ($allPostPutVars['quote_id'] != '' && $allPostPutVars['quote_id'] > 0) {
            $quotationId = $allPostPutVars['quote_id'];
            $quotationInit = new Quotations();
            $quoteData = $quotationInit->where([
                'xe_id' => $quotationId,
                'store_id' => $getStoreDetails['store_id'],
            ]);
            if ($quoteData->count() > 0) {
                //Update status to reject
                //get rejected status id
                $rejectedStatusId = 0;
                if ($updateData['type'] == 'rejected') {
                    $statusInit = new ProductionStatus();
                    $getRejectedStatusData = $statusInit->select('xe_id')->where([
                        'store_id' => $getStoreDetails['store_id'], 
                        'slug' => 'rejected',
                        'module_id' => 1
                    ]);
                    if ($getRejectedStatusData->count() > 0) {
                       $getRejectedStatusDataArr = $getRejectedStatusData->first(); 
                       $getRejectedStatusDataArr = json_clean_decode($getRejectedStatusDataArr, true);
                       $rejectedStatusId = $getRejectedStatusDataArr['xe_id'];
                    }
                }
                
                unset(
                    $updateData['quote_id'],
                    $updateData['user_id'],
                    $updateData['user_type'],
                    $updateData['type']
                );
                $updateData['status_id'] = $rejectedStatusId;
                $quotationInit->where('xe_id', $quotationId)
                    ->update($updateData);
                //New quote log
                $logData = [
                    'quote_id' => $quotationId,
                    'title' => 'Quotation rejected',
                    'description' => "Quotation is rejected",
                    'user_type' => $allPostPutVars['user_type'],
                    'user_id' => $allPostPutVars['user_id'],
                    'created_date' => date_time(
                        'today', [], 'string'
                    )
                ];
                $this->addingQuotationLog($logData);
                //Get Quotation details
                $quotationDetails = $this->getQuotationDetails($request, $response, ['id' => $quotationId], 1);
                //Bind email template
                $templateData = $this->bindEmailTemplate('quote_reject', $quotationDetails, $getStoreDetails);
                $templateData = $templateData[0];
                //Send Email
                $this->sendQuotationEmail($templateData, $quotationDetails['customer'], $getStoreDetails, []);
                $jsonResponse = [
                    'status' => 1,
                    'message' => message('Quotation Reject', 'updated'),
                ];
            }

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

    /**
     * GET: Quotation items list
     *
     * @param $quotationId  Quotation id
     *
     * @author debashrib@riaxe.com
     * @date   19 May 2019
     * @return json response
     */
    public function itemsList($request, $response, $quotationId)
    {
        if ($quotationId != '') {
            $quotationInit = new Quotations();
            $quoteItemsInit = new QuotationItems();
            $variantsInit = new QuotationItemVariants();
            $itemFilesInit = new QuotationItemFiles();
            $decorationsInit = new ProductDecorationsController();
            $stickerInit = new QuoteStickerData();
            $getQuotations = $quotationInit->where(
                [
                    'xe_id' => $quotationId,
                ]);
            $totalCounts = $getQuotations->count();
            //Get all measurment units
            $appUnitInit = new AppUnit();
            $initAppUnit = $appUnitInit->select('xe_id', 'name');
            $measurementUnitArr = $initAppUnit->get();
            $measurementUnitArr = json_clean_decode($measurementUnitArr, true);
            //Get All Print Profile
            $printAreaInit = new PrintArea();
            $printArea = $printAreaInit->select('xe_id', 'name', 'width', 'height');
            $allPrintMethodesArr = $printArea->get();
            $allPrintMethodesArr = json_clean_decode($allPrintMethodesArr, true);
            if ($totalCounts > 0) {
                $getItemsData = $quoteItemsInit->where('quote_id', $quotationId);
                if ($getItemsData->count() > 0) {
                    $itemsDataArr = $getItemsData->get();
                    $itemListArr = [];
                    foreach ($itemsDataArr as $itemsData) {
                        $itemsArr = [];
                        $fileArr = [];
                        $stickerData = [];
                        // Sticker Product Implemented
                        if ($itemsData['is_sticker']) {
                            $getstickerItems = $stickerInit->where('quote_item_id', $itemsData['xe_id']);
                            if ($getstickerItems->count() > 0) {
                                $getstickerItemsData = $getstickerItems->first();
                                $stickerData = json_decode($getstickerItemsData->data,true)['sheetInfo'];
                            }
                        }
                        // End
                        $getVariants = $variantsInit->where('item_id', $itemsData['xe_id']);
                        $getFiles = $itemFilesInit->select('side_id')->groupBy('side_id')
                            ->where('item_id', $itemsData['xe_id']);
                        $productDecorationArr = $decorationsInit->getDecorationDetail($request, $response, ['product_id' => $itemsData['product_id']], 1); 
                        $productDecorationArr = $productDecorationArr['data'];
                        if ($getFiles->count() > 0) {
                            $getFileArr = $getFiles->get()->toArray();
                            //Get product side data
                            $allSideArr = $productDecorationArr['sides'];
                            $type =  gettype($allSideArr);
                            if ($type == 'object') {
                                $allSideArr = json_clean_decode($allSideArr);
                            }
                            //Get measurement unit name
                            $measurementUnitId = $productDecorationArr['scale_unit_id'];
                            $unitArr = array_filter($measurementUnitArr, function ($item) use ($measurementUnitId) {
                                return $item['xe_id'] == $measurementUnitId;
                            });
                            $unitArr = $unitArr[array_keys($unitArr)[0]];
                            $measurementUnitName = $unitArr['name'];

                            foreach ($getFileArr as $files) {
                                $tempFiles = [];
                                $tempFiles['side_id'] = $files['side_id'];
                                $sideId = $files['side_id'];
                                $sideArr = array_filter($allSideArr, function ($item) use ($sideId) {
                                    return $item['xe_id'] == $sideId;
                                });
                                $sideArr = $sideArr[array_keys($sideArr)[0]];
                                $tempFiles['side_name'] = ($itemsData['is_variable_decoration'] == 0) ? $sideArr['side_name'] : 'Side '. $sideId;
                                $decorationDataArr = $itemFilesInit->where(['item_id' => $itemsData['xe_id'], 'side_id' => $sideId])->get();
                                $decorationArea = [];
                                foreach ($decorationDataArr as $decorationData) {
                                    $tempDecorationArea = $decorationData;
                                    $allDecoArr = $sideArr['product_decoration_setting'];
                                    $decorationAreaId = $decorationData['decoration_area_id'];
                                    if (!empty($allDecoArr)) {
                                        $decoArr = array_filter($allDecoArr, function ($item) use ($decorationAreaId) {
                                            return $item['print_area_id'] == $decorationAreaId;
                                        });
                                        $decoArr = $decoArr[array_keys($decoArr)[0]];
                                    }
                                    $tempDecorationArea['decoration_area'] = ($itemsData['is_variable_decoration'] == 0) ? $decoArr['name'] : 'Side '.$sideId;
                                    $allPrintProfileArr = $decoArr['print_profile_decoration_settings'];
                                    $printMethodId = $decorationData['print_method_id'];
                                    $finalPrintMethod = [];
                                    foreach ($allPrintProfileArr as $printProfileArr) {
                                        $tempPrintMethods = $printProfileArr['print_profile'];
                                        $printProfileArr = array_filter($tempPrintMethods, function ($item) use ($printMethodId) {
                                            return $item['xe_id'] == $printMethodId;
                                        });
                                        $printProfileArr = $printProfileArr[array_keys($printProfileArr)[0]];
                                        if ($printProfileArr['xe_id'] == $printMethodId) {
                                            array_push($finalPrintMethod, $printProfileArr);
                                        }
                                    }
                                    if ($itemsData['is_variable_decoration'] == 1) {
                                        $getVdaPrintMethod =  DB::table("print_profiles")->select('name')->where('xe_id', '=', $printMethodId);
                                        $vdpPrintMethodData = $getVdaPrintMethod->first();
                                        $finalPrintMethod[0]['name'] = $vdpPrintMethodData->name;
                                    }
                                    $tempDecorationArea['print_methods'] = $finalPrintMethod[0]['name'];
                                    $printMethodsArr = array_filter($allPrintMethodesArr, function ($item) use ($decorationAreaId) {
                                        return $item['xe_id'] == $decorationAreaId;
                                    });
                                    $printMethodsArr = $printMethodsArr[array_keys($printMethodsArr)[0]];
                                    //Design hight and width
                                    $extraDataValue = $decorationData['extra_data'];
                                    $extraDataArr = json_clean_decode($extraDataValue, true);

                                    $tempDecorationArea['height'] = $printMethodsArr['height'];
                                    $tempDecorationArea['width'] = $printMethodsArr['width'];
                                    $tempDecorationArea['measurement_unit'] = $measurementUnitName;
                                    $tempDecorationArea['print_area_id'] = $decorationAreaId;
                                    $tempDecorationArea['print_area_name'] = $printMethodsArr['name'];
                                    $tempDecorationArea['upload_design_url'] = path('read', 'quotation') . $quotationId . '/' . $itemsData['xe_id'] . '/' . $sideId . '/' . $decorationData['file'];
                                    $tempDecorationArea['design_file_path'] = path('abs', 'quotation') . $quotationId . '/' . $itemsData['xe_id'] . '/' . $sideId . '/' . $decorationData['file'];
                                    $tempDecorationArea['upload_preview_url'] = path('read', 'quotation') . $quotationId . '/' . $itemsData['xe_id'] . '/' . $sideId . '/' . $decorationData['preview_file'];
                                    $tempDecorationArea['preview_file_path'] = path('abs', 'quotation') . $quotationId . '/' . $itemsData['xe_id'] . '/' . $sideId . '/' . $decorationData['preview_file'];
                                    $tempDecorationArea['design_height'] = (!empty($extraDataArr) && isset($extraDataArr['design_height']) && $extraDataArr['design_height'] != '') ?$extraDataArr['design_height'] : '';
                                    $tempDecorationArea['design_width'] = (!empty($extraDataArr) && isset($extraDataArr['design_width']) && $extraDataArr['design_width'] != '') ?$extraDataArr['design_width'] : '';
                                    unset(
                                        $tempDecorationArea['xe_id'],
                                        $tempDecorationArea['item_id'],
                                        $tempDecorationArea['side_id'],
                                        $tempDecorationArea['extra_data']
                                    );
                                    array_push($decorationArea, $tempDecorationArea->toArray());
                                }
                                $tempFiles['decoration_area'] = $decorationArea;
                                array_push($fileArr, $tempFiles);
                            }
                        }
                        if ($getVariants->count() > 0) {
                            $variantDataArr = $getVariants->select('variant_id', 'quantity', 'unit_price', 'attribute', 'updated_price')->get()->toArray();
                            foreach ($variantDataArr as $variantData) {
                                if (!empty($stickerData)) {
                                    // Sticker Product Implemented
                                    foreach ($stickerData as $stickerValue) {
                                        $itemsArr['variant_id'] = $variantData['variant_id'];
                                        $itemsArr['quantity'] = $stickerValue['quantity'];
                                        $itemsArr['overall_quantity'] = $stickerValue['quantity'];
                                        $itemsArr['unit_price'] = $stickerValue['price'];
                                        $itemsArr['updated_price'] = ($stickerValue['updated_price'] != '') ? $stickerValue['updated_price'] : $stickerValue['price'];
                                        $itemsArr['product_id'] = $itemsData['product_id'];
                                        $itemsArr['custom_design_id'] = $itemsData['custom_design_id'];
                                        $itemsArr['design_cost'] = $itemsData['design_cost'];
                                        $itemsArr['artwork_type'] = $itemsData['artwork_type'];
                                        $itemsArr['is_variable_decoration'] = $itemsData['is_variable_decoration'];
                                        $itemsArr['is_custom_size'] = $itemsData['is_custom_size'];
                                        $itemsArr['custom_size_dimension'] = $itemsData['custom_size_dimension'];
                                        $itemsArr['custom_size_dimension_unit'] = $itemsData['custom_size_dimension_unit'];
                                        $itemsArr['product_name'] = $productDecorationArr['product_name'];
                                        $itemsArr['product_attributes'] = json_clean_decode($variantData['attribute'], true);
                                        $itemsArr['files'] = !empty($fileArr) ? $fileArr : [];
                                        $itemsArr['is_sticker_product'] = 1;
                                        $itemsArr['sheet_name'] = $stickerValue['name'];
                                        array_push($itemListArr, $itemsArr);
                                    }
                                    // End
                                } else {
                                    $itemsArr['variant_id'] = $variantData['variant_id'];
                                    $itemsArr['quantity'] = $variantData['quantity'];
                                    $itemsArr['overall_quantity'] = $itemsData['quantity'];
                                    $itemsArr['unit_price'] = $variantData['unit_price'];
                                    $itemsArr['updated_price'] = ($variantData['updated_price'] != '') ? $variantData['updated_price'] : $variantData['unit_price'];
                                    $itemsArr['product_id'] = $itemsData['product_id'];
                                    $itemsArr['custom_design_id'] = $itemsData['custom_design_id'];//($itemsData['custom_design_id'] == 0 && $itemsData['artwork_type'] == 'uploaded_file') ? '-1' : $itemsData['custom_design_id'];
                                    $itemsArr['design_cost'] = $itemsData['design_cost'];
                                    $itemsArr['artwork_type'] = $itemsData['artwork_type'];
                                    $itemsArr['is_variable_decoration'] = $itemsData['is_variable_decoration'];
                                    $itemsArr['is_custom_size'] = $itemsData['is_custom_size'];
                                    $itemsArr['custom_size_dimension'] = $itemsData['custom_size_dimension'];
                                    $itemsArr['custom_size_dimension_unit'] = $itemsData['custom_size_dimension_unit'];
                                    $itemsArr['product_name'] = $productDecorationArr['product_name'];
                                    $itemsArr['product_attributes'] = json_clean_decode($variantData['attribute'], true);
                                    $itemsArr['files'] = !empty($fileArr) ? $fileArr : [];
                                    array_push($itemListArr, $itemsArr);
                                }
                            }
                        }

                    }
                }
            }
        }
        return $itemListArr;
    }


    /**
     * POST: Add internal note to quotation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   23 May 2020
     * @return json response wheather data is saved or any error occured
     */
    public function saveInternalNote($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Internal Note', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        $quotationId = to_int($allPostPutVars['quote_id']);
        if ($quotationId != '') {
            $quotationInit = new Quotations();
            $getOldQuotation = $quotationInit->where('xe_id', $quotationId);
            if ($getOldQuotation->count() > 0) {

                $allPostPutVars['created_date'] = date_time(
                    'today', [], 'string'
                );
                $quoteInternalNote = new QuotationInternalNote($allPostPutVars);
                if ($quoteInternalNote->save()) {
                    $noteInsertId = $quoteInternalNote->xe_id;
                    $allFileNames = do_upload(
                        'upload',
                        path('abs', 'quotation') . 'internal-note/', [150],
                        'array'
                    );
                    //Save file name w.r.t note
                    if (!empty($allFileNames)) {
                        foreach ($allFileNames as $eachFile) {
                            $fileData = [
                                'note_id' => $noteInsertId,
                                'file' => $eachFile,
                            ];
                            $saveNoteFile = new QuotationInternalNoteFiles($fileData);
                            $saveNoteFile->save();
                        }
                    }
                    $jsonResponse = [
                        'status' => 1,
                        'message' => message('Internal Note', 'saved'),
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Bulk actions for quotation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   23 May 2020
     * @return json response wheather data is saved or any error occured
     */
    public function bulkAction($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Bulk Action', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $quotationId = $allPostPutVars['quote_ids'];
        $eventType = $allPostPutVars['event_type'];
        $emailLogId = $allPostPutVars['email_log_id'];
        $totalEmailCount = $allPostPutVars['total_email_count'];
        if ($quotationId != '' && $quotationId > 0 && $eventType != '') {
            $quotationInit = new Quotations();
            $unsuccessEmails = '';
            $successEmails = '';
            $skippedEmails = '';
            $templateData = [];
            $quotation = $quotationInit->where('xe_id', $quotationId)->first();
            $quotationDetails = json_clean_decode($quotation, true);
            //Get Payments Details
            $paymentInit = new QuotationPayment();
            $paymentData =  $paymentInit->select('payment_amount')->where([
                'quote_id' => $quotationId,
                'payment_status' => 'paid'
            ])->sum('payment_amount');
            $comPaidAmount = ($paymentData > 0) ? $paymentData : 0;
            $comPaidAmount = number_format($comPaidAmount, 2, '.', '');
            $quotationDetails['due_amount'] = $quotationDetails['quote_total'] - $comPaidAmount;

            //check for customer
            if ($quotationDetails['customer_name'] == '' || $quotationDetails['customer_email'] == '') {
                $customersControllerInit = new CustomersController();
                $customerDetails = $customersControllerInit->getQuoteCustomerDetails($quotationDetails['customer_id'], $getStoreDetails['store_id'], '');
                $quotationDetails['customer_name'] = $customerDetails['customer']['name'];
                $quotationDetails['customer_email'] = $customerDetails['customer']['email'];
            }

            if ($quotationDetails['customer_email'] != '') {
                //Get Order status id
                $statusInit = new ProductionStatus();
                $orderStatusId = 0;
                $approvedStatusId = 0;
                $getOrderedStatusData = $statusInit->select('xe_id')->where([
                    'store_id' => $getStoreDetails['store_id'], 
                    'slug' => 'ordered',
                    'module_id' => 1
                ]);

                if ($getOrderedStatusData->count() > 0) {
                   $getOrderedStatusDataArr = $getOrderedStatusData->first(); 
                   $getOrderedStatusDataArr = json_clean_decode($getOrderedStatusDataArr, true);
                   $orderStatusId = $getOrderedStatusDataArr['xe_id'];
                }
                //Get Approved status id
                $getApprovedStatusData = $statusInit->select('xe_id')->where([
                    'store_id' => $getStoreDetails['store_id'], 
                    'slug' => 'approved',
                    'module_id' => 1
                ]);

                if ($getApprovedStatusData->count() > 0) {
                   $getApprovedStatusDataArr = $getApprovedStatusData->first(); 
                   $getApprovedStatusDataArr = json_clean_decode($getApprovedStatusDataArr, true);
                   $approvedStatusId = $getApprovedStatusDataArr['xe_id'];
                }
                if ($eventType == 'payment_reminder' && $quotationDetails['due_amount'] == 0) {
                    $skippedEmails = $quotationDetails['customer_email'];
                } elseif ($eventType == 'approval_reminder' && ($quotationDetails['status_id'] == $approvedStatusId  || $quotationDetails['status_id'] == $orderStatusId)) {
                    $skippedEmails = $quotationDetails['customer_email'];
                } else {
                    if ($eventType == 'resend_quotation_mail') {
                        //Bind email template for bulk resend quotation mail
                        $templateData = $this->bindEmailTemplate('bulk_resend_quotation', $quotationDetails, $getStoreDetails);
                    } elseif ($eventType == 'approval_reminder') {
                        //Bind email template for bulk quotation approval
                        $templateData = $this->bindEmailTemplate('bulk_quotation_approval', $quotationDetails, $getStoreDetails);
                    } else {
                        //Bind email template for bulk payment reminder
                        $templateData = $this->bindEmailTemplate('bulk_payment_reminder', $quotationDetails, $getStoreDetails);
                    }
                    $templateData = $templateData[0];
                    $mailResponse = $this->sendQuotationEmail(
                        $templateData, 
                        [
                            'name' => $quotationDetails['customer_name'], 
                            'email' => $quotationDetails['customer_email']
                        ], 
                        $getStoreDetails,
                        []
                    );
                    if (!empty($mailResponse['status']) && $mailResponse['status'] == 1) {
                        $successEmails = $quotationDetails['customer_email'];
                    } else {
                        $unsuccessEmails = $quotationDetails['customer_email'];
                    }
                }
            } else {
                $skippedEmails = 'No Customer';
            }

            //Save data for Email Log
            if ($emailLogId == 0) {
                $emailLogData = [
                    'store_id' => $getStoreDetails['store_id'],
                    'module' => 'quotation',
                    'type' => $eventType,
                    'subject' => (!empty($templateData)) ? $templateData['subject'] : '',
                    'message' => (!empty($templateData)) ? $templateData['message'] : '',
                    'total_email_count' => $totalEmailCount,
                    'success_email' => $successEmails,
                    'failure_email' => $unsuccessEmails,
                    'skipped_email' => $skippedEmails,
                    'created_date' => date_time(
                        'today', [], 'string'
                    )
                ];
                $emailLogId = $this->saveDataForEmailLog($emailLogData);
            } else {
                $updateEmailLogData = [
                    'email_log_id' => $emailLogId,
                    'subject' => (!empty($templateData)) ? $templateData['subject'] : '',
                    'message' => (!empty($templateData)) ? $templateData['message'] : '',
                    'success_email' => $successEmails,
                    'failure_email' => $unsuccessEmails,
                    'skipped_email' => $skippedEmails,
                ];
                $emailLogId = $this->updateDataForEmailLog($updateEmailLogData);
            }
        }

        $jsonResponse = [
            'status' => 1,
            'success_mails' => $successEmails,
            'unsuccess_emails' => $unsuccessEmails,
            'skipped_emails' => $skippedEmails,
            'email_log_id' => $emailLogId
        ];
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * Get: Get quotation items list
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   23 May 2020
     * @return json response
     */
    public function getQuotationItemsList($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Items', 'error'),
        ];
        $quotationIds = $args['id'];
        $quoteItemsArr = [];
        if (!empty($quotationIds)) {
            $getQuoteIdsToArray = json_clean_decode($quotationIds, true);
            if (count($getQuoteIdsToArray) > 0) {
                foreach ($getQuoteIdsToArray as $quotationId) {
                    $itemsArr = [];
                    $itemsArr[$quotationId] = $this->getQuoteItems($request, $response, ['id' => $quotationId], 1);
                    array_push($quoteItemsArr, $itemsArr);
                }
                $jsonResponse = [
                    'status' => 1,
                    'data' => $quoteItemsArr,
                ];
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Convert Quotation into Order
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   23 May 2020
     * @return json response
     */
    public function convertQuoteToOrder($request, $response, $otherParameter = [])
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Convert to order', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $quotationId = (isset($allPostPutVars['quote_id'])) ? $allPostPutVars['quote_id'] : $otherParameter['quote_id'];
        if ($quotationId != '') {
            //Check if order is created or not 
            $quotationInit = new Quotations();
            $quotationDetails = $quotationInit->where('xe_id', $quotationId)
                ->first();
            $quotationDetails = json_clean_decode($quotationDetails, true);
            if ($quotationDetails['order_id'] == '') {
                //Check all items were having variants or not
                $quoteItemsInit = new QuotationItems();
                $variantsInit = new QuotationItemVariants();
                $variantFlag = 1;
                $getItems = $quoteItemsInit->select('xe_id','is_sticker', 'quantity')->where('quote_id', $quotationId);
                if ($getItems->count() > 0) {
                    $getItemsData = $getItems->get()->toArray();
                    foreach ($getItemsData as $items) {
                        if ($items['quantity'] > 0) {
                            $variantData = $variantsInit->where('item_id', $items['xe_id']);
                            if ($variantData->count() == 0) {
                                $variantFlag = 0;
                            } else {
                                $variantDataArr = $variantData->get();
                                $variantDataArr = json_clean_decode($variantDataArr, true);
                                foreach ($variantDataArr as $dataArr) {
                                    $attributData = $dataArr['attribute'];
                                    $attributDataArr = json_clean_decode($attributData, true);
                                    foreach ($attributDataArr as $attKey => $attributes) {
                                        if ((isset($attributes['is_selected']) && $attributes['is_selected'] == 0) || ($attKey == $attributes['name'])) {
                                            $variantFlag = 0;
                                        }
                                    }
                                }
                            }
                        } else {
                            $variantFlag = 0;
                        }
                    }
                }
                if ($variantFlag == 1) {
                    $quotationDetails['product_data'] = $this->itemsList($request, $response, $quotationId);
                    $jsonData['data'] = json_encode($quotationDetails);
                    $jsonResponse = call_curl(
                        $jsonData, "convert-quote-to-order", "POST");
                    if (!empty($jsonResponse) && $jsonResponse['status'] == 1) {
                        $logData = [
                            'quote_id' => $quotationId,
                            'title' => 'Converted to order',
                            'description' => "Quote is coverted to order i.e #".$jsonResponse['data'],
                            'user_type' => (isset($allPostPutVars['user_type'])) ? $allPostPutVars['user_type'] : $otherParameter['user_type'],
                            'user_id' => (isset($allPostPutVars['user_id'])) ? $allPostPutVars['user_id'] : $otherParameter['user_id'],
                            'created_date' => date_time(
                                'today', [], 'string'
                            )
                        ];
                        $this->addingQuotationLog($logData);
                        //Change the quotation status to ordered
                        $orderId = $jsonResponse['data'];
                        $orderNumber = (isset($jsonResponse['order_number']) && $jsonResponse['order_number'] != '') ? $jsonResponse['order_number'] : '';
                        //Get Order status id
                        $statusInit = new ProductionStatus();
                        $orderStatusId = 0;
                        $getOrderedStatusData = $statusInit->select('xe_id')->where([
                            'store_id' => $getStoreDetails['store_id'], 
                            'slug' => 'ordered',
                            'module_id' => 1
                        ]);

                        if ($getOrderedStatusData->count() > 0) {
                           $getOrderedStatusDataArr = $getOrderedStatusData->first(); 
                           $getOrderedStatusDataArr = json_clean_decode($getOrderedStatusDataArr, true);
                           $orderStatusId = $getOrderedStatusDataArr['xe_id'];
                        }
                        $quotationInit->where('xe_id', $quotationId)
                            ->update(['status_id' => $orderStatusId, 'order_id' => $orderId]); // 5:Ordered
                        //Add data to Orders table
                        $ordersInit = new OrdersController();
                        $ordersInit->saveDataForOrder($orderId, $quotationDetails['store_id'], $quotationDetails['customer_id'], $orderNumber);
                    }
                } else {
                    $jsonResponse = [
                        'status' => 0,
                        'message' => message('Convert to order', 'insufficient'),
                    ];
                }
            } else {
                $jsonResponse = [
                    'status' => 0,
                    'message' => message('Convert to order', 'exist'),
                ];
            }
        }
        if (isset($otherParameter['return_type']) && $otherParameter['return_type'] == 1) {
            return $jsonResponse;
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * Get Email Template data
     *
     * @param $emailType  Email Template Type
     * @param $quotationDetails Quotation Details Array
     * @param $getStoreDetails Store Id
     *
     * @author debashrib@riaxe.com
     * @date   05 June 2020
     * @return array response
     */
    public function bindEmailTemplate($emailType, $quotationDetails, $getStoreDetails)
    {
        $resData = [];
        if ($emailType != '' && !empty($quotationDetails)) {
            //Bind email template
            $templateData = $this->getEmailTemplate(1, $getStoreDetails, $emailType);
            $abbrivationsInit = new ProductionAbbriviations();
            $getAbbrivations = $abbrivationsInit->where('module_id', 1);
            $getAbbrivations = $getAbbrivations->get();
            $abbriviationData = json_clean_decode($getAbbrivations, true);
            foreach ($abbriviationData as $abbrData) {
                $abbrName = $abbrData['abbr_name'];
                $abbrValue = $this->getAbbriviationValue($abbrName, $quotationDetails, $getStoreDetails['store_id']);
                if (strpos($templateData[0]['message'], $abbrName) !== false) {
                    $templateData[0]['message'] = str_replace($abbrName, $abbrValue, $templateData[0]['message']);
                }
                if (strpos($templateData[0]['subject'], $abbrName) !== false) {
                    $templateData[0]['subject'] = str_replace($abbrName, $abbrValue, $templateData[0]['subject']);
                }
            }
            $resData = $templateData;
        }
        return $resData;
    }

    /**
     * Get Email Template Abbriviation Value
     *
     * @param $abbrName  Abbriviation Name
     * @param $quotationDetails Quotation Details Drray
     *
     * @author debashrib@riaxe.com
     * @date   05 June 2020
     * @return array response
     */

    public function getAbbriviationValue($abbrName, $quotationDetails, $storeId)
    {
        $quotationId = $quotationDetails['xe_id'];
        //Get setting data for default currency
        $currency = $quotationDetails['currency']['value'];
        
        $abbrValue = '';
        //switch case
        switch ($abbrName) {
            case "{quote_id}":
                $abbrValue = $quotationDetails['quote_id'];
                break;
            case "{quote_date}":
                $abbrValue = date('m-d-Y', strtotime($quotationDetails['created_at']));
                break;
            case "{customer_name}":
                $abbrValue = ($quotationDetails['customer_name'] != '') ? $quotationDetails['customer_name'] : $quotationDetails['customer_email'];
                break;
            case "{payment_date}":
                $abbrValue = ($quotationDetails['request_date'] != '' && $quotationDetails['request_date'] != '0000-00-00 00:00:00') ? date('m-d-Y', strtotime($quotationDetails['request_date'])) : '';
                break;
            case "{shipping_date}":
                $abbrValue = date('m-d-Y', strtotime($quotationDetails['ship_by_date']));
                break;
            case "{delivery_date}":
                $abbrValue = date('m-d-Y', strtotime($quotationDetails['exp_delivery_date']));
                break;
            case "{payment_amount}":
                //Get latest payment amount
                $paymentInit = new QuotationPayment();
                $paymentData =  $paymentInit->where('quote_id', $quotationId);
                $quotePaymentLog = $paymentData->get()->toArray();
                $latestPayment = end($quotePaymentLog);
                $paymentAmount = !empty($latestPayment) ? $latestPayment['payment_amount'] : 0;
                $abbrValue = $currency.number_format($paymentAmount, 2, '.', '');
                break;
            case "{payment_due_amount}":
                //Get latest payment amount
                $dueAmount = $quotationDetails['due_amount'];
                $abbrValue = $currency.number_format($dueAmount, 2, '.', '');
                break;
            case "{public_url}":
                $token = 'quote_id=' . $quotationDetails['xe_id'].'&store_id='.$storeId;
                $token = base64_encode($token);
                $url = 'quotation/quotation-approval?token=' . $token;
                $abbrValue = API_URL.$url;
                break;
            case "{reject_note}":
                $abbrValue = $quotationDetails['reject_note'];
                break;
            case "{request_payment_amount}":
                $amount = (($quotationDetails['request_payment'] != '') && $quotationDetails['request_payment'] > 0) ? $quotationDetails['request_payment'] : $quotationDetails['due_amount'];
                $abbrValue = $currency.number_format($amount, 2, '.', '');
                break;
            case "{quote_total_amount}":
                $quoteTotalAmont = $quotationDetails['quote_total'];
                $abbrValue = $currency.number_format($quoteTotalAmont, 2, '.', '');
                break;
            case "{quote_pdf_download}":
                $strResult = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
                $token = substr(str_shuffle($strResult),  
                       0, 16);
                $abbrValue = BASE_URL . "quotation/download/" . $quotationId."?token=".$token;
                break;
            default:
                $abbrValue = $abbrName;
        }
        return $abbrValue;
    }

    /**
     * Send Email
     *
     * @param $emailType  Email Template Type
     * @param $quotationDetails Quotation Details Drray
     *
     * @author debashrib@riaxe.com
     * @date   05 June 2020
     * @return array response
     */
    public function sendQuotationEmail($templateData, $customerData, $getStoreDetails, $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;
    }

    /**
     * POST: Add Conversation to quotation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   08 June 2020
     * @return json response wheather data is saved or any error occured
     */
    public function saveConversations($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Conversation', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        $quotationId = to_int($allPostPutVars['quote_id']);
        if ($quotationId != '') {
            $quotationInit = new Quotations();
            $getOldQuotation = $quotationInit->where('xe_id', $quotationId);
            if ($getOldQuotation->count() > 0) {

                $allPostPutVars['created_date'] = date_time(
                    'today', [], 'string'
                );
                $QuoteConversations = new QuotationConversations($allPostPutVars);
                if ($QuoteConversations->save()) {
                    $convInsertId = $QuoteConversations->xe_id;
                    $allFileNames = do_upload(
                        'upload',
                        path('abs', 'quotation') . 'conversation/', [150],
                        'array'
                    );
                    //Save file name w.r.t note
                    if (!empty($allFileNames)) {
                        foreach ($allFileNames as $eachFile) {
                            $fileData = [
                                'conversation_id' => $convInsertId,
                                'file' => $eachFile,
                            ];
                            $saveConversationFile = new QuotationConversationFiles($fileData);
                            $saveConversationFile->save();
                        }
                    }
                    $jsonResponse = [
                        'status' => 1,
                        'message' => message('Conversation', 'saved'),
                        'conversation_id' => $convInsertId
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET: Get quotation conversation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   08 June 2020
     * @return json response
     */
    public function getConversations($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Conversation', 'not_found'),
        ];
        if (!empty($args['id'])) {
            $quotationId = to_int($args['id']);
            $quotationInit = new Quotations();
            $getOldQuotation = $quotationInit->where('xe_id', $quotationId);
            if ($getOldQuotation->count() > 0) {
                $conversationInit = new QuotationConversations();
                $conversations = $conversationInit->with('files')->where('quote_id', $quotationId);
                if ($conversations->count() > 0) {
                    $conversationArr = $conversations->get();
                    $jsonResponse = [
                        'status' => 1,
                        'data' => $conversationArr,
                    ];
                }
            }
        }
        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 debashrib@riaxe.com
     * @date   10 June 2020
     * @return json response
     */
    public function changeConversationSeenFlag($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Conversation Seen Flag', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        $quotationId = to_int($allPostPutVars['quote_id']);
        if ($quotationId != '') {
            $QuoteConversationInit = new QuotationConversations();
            $QuoteConversationInit->where('quote_id', $quotationId)
                ->update(['seen_flag' => '0']);

            $jsonResponse = [
                'status' => 1,
                'message' => message('Conversation Seen Flag', 'done'),
            ];

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

    /**
     * GET: Get quotation dynamic form attribute
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   17 June 2020
     * @return json response
     */
    public function getFormAttribute($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Form Attribute', 'not_found'),
        ];

        $formAttributeInit = new QuotationDynamicFormAttributes();
        if ($formAttributeInit->count() > 0) {
            $getFormAttribute = $formAttributeInit->get();
            $jsonResponse = [
                'status' => 1,
                'data' => $getFormAttribute,
            ];
        }

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

    /**
     * POST: Art Work Design
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author satyabratap@riaxe.com
     * @date   20 Jun 2020
     * @return json response wheather data is saved or any error occured
     */
    public function artWorkDesign($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Design Data', 'error'),
        ];
        // Get Store Specific Details from helper
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $productData = [];
        if (isset($allPostPutVars['product_data'])) {
            $productData = json_clean_decode($allPostPutVars['product_data'], true);
        }

        if (!empty($productData) && isset($allPostPutVars['design_data']) && $allPostPutVars['design_data'] != '') {
                $designData = json_clean_decode($allPostPutVars['design_data'], true);
                $productId = isset($designData['product_info']['product_id'])
                && $designData['product_info']['product_id'] != ''
                ? $designData['product_info']['product_id'] : null;
                $variantId = isset($productData[0]['variant_id'])
                && $productData[0]['variant_id'] != ''
                ? $productData[0]['variant_id'] : null;

                // Prepare array for saving design data
                $designDetails = [
                    'store_id' => $getStoreDetails['store_id'],
                    'product_setting_id' => (isset($allPostPutVars['product_setting_id'])
                        && $allPostPutVars['product_setting_id'] != "")
                    ? $allPostPutVars['product_setting_id'] : null,
                    'product_variant_id' => $variantId,
                    'product_id' => $productId,
                    'type' => (isset($allPostPutVars['template_type'])
                        && $allPostPutVars['template_type'] != "")
                    ? $allPostPutVars['template_type'] : "artwork",
                    'custom_price' => (isset($designData['custome_price'])
                        && $designData['custome_price'] > 0)
                    ? $designData['custome_price'] : 0.00,
                ];
                if (isset($designDetails) && !empty($designDetails != '')) {
                    $directory = (isset($allPostPutVars['template_type']) && $allPostPutVars['template_type'] == 'artwork_approval') ? 'artwork_approval' : 'artworks';
                    // save design data and get customDesignId
                    $customDesignId = $this->saveDesignData(
                        $designDetails, $allPostPutVars['design_data'], ['directory' => $directory]
                    );
                    if ($customDesignId > 0) {
                        $jsonResponse = [
                            'status' => 1,
                            'custom_design_id' => $customDesignId,
                            'message' => message('Design Data', 'saved'),
                        ];
                    }
                }
        }
        return response(
            $response, [
                'data' => $jsonResponse, 'status' => $serverStatusCode,
            ]
        );
    }

    /**
     * POST: Save Quotation Dynamic Form
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   17 June 2020
     * @return json response
     */
    public function saveDynamicForm($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Dynamic Form', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        if (isset($allPostPutVars['data']) && $allPostPutVars['data'] != "") {
            $dynamicForm = new QuotationDynamicForm($allPostPutVars['data']);
            if ($dynamicForm->save()) {
                $jsonResponse = [
                    'status' => 1,
                    'message' => message('Dynamic Form', 'saved'),
                ];
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Check setting for quotation creatation
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   22 June 2020
     * @return json response
     */
    public function checkSettingForQuote($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Setting Check', 'error'),
        ];

        //Get quotation setting data for sending email
        $settingData = $this->getProductionSetting($request, $response, ['module_id' => 1, 'return_type' => 1]);
        $settingData = $settingData['data'];
        $quotationSetting = [];
        if (!empty($settingData)) {
            $quotationSetting['is_quote_id_enable'] = $settingData['is_quote_id_enable'];
            $quotationSetting['quote_id'] = ($settingData['quote_id']['prefix'] != ''
                && $settingData['quote_id']['starting_number'] != ''
                && $settingData['quote_id']['postfix'] != '') ? true : false;
            $quotationSetting['invoice_setting'] = ($settingData['sender_email'] != '' && $settingData['company_name'] != '' && $settingData['city'] != '' && $settingData['country'] != '' && $settingData['zip_code'] != '' && $settingData['address'] != '' && $settingData['company_logo'] != '') ? true : false;
            //Email Template Data
            $templateData = $settingData['template_data'];
            $sendEmailTemp = array_filter($templateData, function ($item) {
                return $item['template_type_name'] == 'quote_sent';
            });
            $sendEmailTemp = $sendEmailTemp[array_keys($sendEmailTemp)[0]];
            $quotationSetting['quotation_sending_email'] = ($sendEmailTemp['is_configured'] == 1) ? true : false;
            //Get SMPT setup from general setting
            $storeArr = ["prestashop", "shopify"];
            if (in_array(strtolower(STORE_NAME), $storeArr)) {
                $globalSettingData = call_curl([], 'settings', 'GET', true);
            } else {
                $globalSettingData = call_api(
                    'settings', 'GET', []
                );
            }
            $emailData = $globalSettingData['general_settings']['email_address_details'];
            $smtpData = $globalSettingData['general_settings']['smtp_details'];
            $isEmailSettingsEnabled = $globalSettingData['general_settings']['is_email_settings_enabled'];

            $quotationSetting['smtp_data_setting'] = ($emailData !='' && $emailData['from_email'] != '' && $emailData['to_email'] != '' && $smtpData['smtp_host'] !='' && $smtpData['smtp_user'] != ''  && $smtpData['smtp_from'] != '' && $isEmailSettingsEnabled == 1) ? true : false;
        }
        if (!empty($quotationSetting)) {
            $jsonResponse = [
                'status' => 1,
                'data' => $quotationSetting,
            ];
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Send quotation request
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author satyabratap@riaxe.com
     * @date   04 July 2020
     * @return json response
     */
    public function sendQuotationRequest($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quatation Request Data', 'error'),
        ];

        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $storeArr = ["prestashop", "shopify"];
        if (in_array(strtolower(STORE_NAME), $storeArr)) {
            $globalSettingData = call_curl([], 'settings', 'GET', true);
        } else {
            $globalSettingData = call_api(
                'settings', 'GET', []
            );
        }
        //$quoteId = 'INQ' . getRandom();
        $fromEmail = '';
        $settingsEmail = '';
        // if(!empty($globalSettingData['general_settings']['email_address_details']['from_email'])) {
        //     $fromName = $globalSettingData['general_settings']['email_address_details']['from_email'];
        // }
        //Check tier price is enable or not in global setting
        $isTierPriceEnable = isset($globalSettingData['cart_setting']['tier_price']) ? $globalSettingData['cart_setting']['tier_price']['is_enabled'] : 0;
        if(!empty($globalSettingData['general_settings']['smtp_details']['smtp_from'])) {
            $fromEmail = $globalSettingData['general_settings']['smtp_details']['smtp_from'];
        }
        if(!empty($globalSettingData['general_settings']['email'])) {
            $settingsEmail = $globalSettingData['general_settings']['email'];
        }
        $productsControllerInit = new ProductsController();
        if (!empty($settingsEmail) && !empty($fromEmail)) {
            if (!empty($allPostPutVars['data'])) {
                $requestDetails = json_clean_decode($allPostPutVars['data']);
                $productDetails = $requestDetails['product_details'];
                if (!empty($productDetails)) {
                    $productData = $productsControllerInit->getProductDetails($request, $response, ['id' => $productDetails['product_id']], 1);
                    $productVariantData = $productsControllerInit->getProductVariants($request, $response, ['pid' => $productDetails['product_id']], 1);
                }
                if ($requestDetails['form_details']) {
                    $emailParam = [];
                    //Save uploaded data
                    $attachmentFiles = $requestDetails['form_details']['attachments'];
                    unset($requestDetails['form_details']['attachments']);
                    if (!empty($attachmentFiles)) {
                        //$attachmentFiles = $requestDetails['form_details']['attachments'];
                        //unset($requestDetails['form_details']['attachments']);
                        $attachmentKey = 1;
                        foreach ($attachmentFiles as $attachKey => $attachValue) {
                            $multipleFileArr = [];
                            $fileValueArr = explode(',', $attachValue);
                            if (count($fileValueArr) > 1) {
                                foreach ($fileValueArr as $multipleFiles) {
                                    $multipleFiles = trim($multipleFiles);
                                    $attachmentFileName = do_upload(
                                        $multipleFiles,
                                        path('abs', 'quotation_request'),
                                        'string'
                                    );
                                    $multipleFileArr[] = $attachmentFileName[0];
                                    $emailParam['attachments'][] = path('abs', 'quotation_request') . $attachmentFileName[0];
                                }
                            } else {
                                $attachmentFileName = do_upload(
                                    $fileValueArr[0],
                                    path('abs', 'quotation_request'),
                                    [],
                                    'string'
                                );
                                $emailParam['attachments'][] = path('abs', 'quotation_request') . $attachmentFileName;
                            }
                            
                            if (isset($multipleFileArr) && !empty($multipleFileArr)) {
                                $attachmentFileName = implode(', ', $multipleFileArr);
                            }
                            if ($attachmentFileName != '') {
                                $requestDetails['form_details'][$attachKey] = $attachmentFileName;
                                $requestDetails['form_details']['file_type'][] = $attachKey;
                                $attachmentKey = $attachmentKey + 1;
                            }
                        }
                    }
                    //Create quotation
                    if (isset($requestDetails['is_quotation_enable']) && $requestDetails['is_quotation_enable'] == 1) {
                        //Generate Quote Id
                        $quotationInit = new Quotations();
                        $lastQuotationRecord = $quotationInit->select('quote_id')->latest()->first();
                        if (!empty($lastQuotationRecord)) {
                            $quoteId = $this->generateQuoteId($request, $lastQuotationRecord->quote_id);
                        } else {
                            $quoteId = $this->generateQuoteId($request);
                        }
                        //Get Open status id
                        $statusInit = new ProductionStatus();
                        $getStatusData = $statusInit->select('xe_id')->where([
                            'store_id' => $getStoreDetails['store_id'], 
                            'slug' => 'open',
                            'module_id' => 1
                        ]);
                        if ($getStatusData->count() > 0) {
                           $getStatusDataArr = $getStatusData->first(); 
                           $getStatusDataArr = json_clean_decode($getStatusDataArr, true);
                        }
                        $currencyData = $this->getUsedCurrency('', $getStoreDetails['store_id']);
                        $quotationData = [
                            'store_id' => $getStoreDetails['store_id'],
                            'quote_id' => $quoteId,
                            'created_by' => 'customer',
                            'quote_source' => 'tool',
                            'design_total' => $requestDetails['total_price'],
                            'quote_total' => $requestDetails['total_price'],
                            'status_id' => $getStatusDataArr['xe_id'],
                            'draft_flag' => 1,
                            'discount_type' => 'flat',
                            'discount_amount' => 0,
                            'shipping_type' => 'express',
                            'shipping_amount' => 0,
                            'ship_by_date' => date_time(
                                            'today', [], 'string'
                                        ),
                            'exp_delivery_date' => date_time(
                                            'today', [], 'string'
                                        ),
                            'currency_id' => $currencyData['id'],
                        ];
                        $customerId = (isset($requestDetails['customer_id']) && $requestDetails['customer_id'] > 0) ? $requestDetails['customer_id'] : '';
                        $shippingId = '';
                        $customerName = '';
                        $customerEmail = '';
                        if ($customerId != '') {
                            $customersControllerInit = new CustomersController();
                            $customerDetails = $customersControllerInit->getQuoteCustomerDetails($customerId, $getStoreDetails['store_id'], '', true);
                            if (!empty($customerDetails)) {
                                $customerName = $customerDetails['customer']['name'];
                                $customerEmail = $customerDetails['customer']['email'];
                            }
                            $shippingId = $customerDetails['customer']['shipping_address'][0]['id'];
                            $quotationData += [
                                'customer_id' => $customerId,
                                'shipping_id' => $shippingId,
                                'created_by_id' => $customerId,
                                'customer_name' => $customerName,
                                'customer_email' => $customerEmail,
                            ];
                        }
                        
                        $quotation = new Quotations($quotationData);
                        if ($quotation->save()) {
                            $quotationLastId = $quotation->xe_id;
                            //Add quotation item data with its variants
                            if (!empty($productDetails)) {
                                $quantityArr = array_column($productDetails['variation'], 'qty');
                                $totalQuantity = array_sum($quantityArr);
                                $itemData = [
                                    'quote_id' => $quotationLastId,
                                    'product_id' => $productDetails['product_id'],
                                    'quantity' => $totalQuantity,
                                    'artwork_type' => 'design_tool',
                                    'custom_design_id' => $requestDetails['design_details']['custom_design_id'],
                                    'design_cost' => $requestDetails['decoration_price']/$totalQuantity,
                                    'unit_total' =>  0,
                                    'is_sticker' => (isset($productDetails['is_sticker']) && $productDetails['is_sticker'] == 1) ? 1 : 0,
                                    'is_team_jersey' => (isset($productDetails['is_team_jersey']) && $productDetails['is_team_jersey'] == 1) ? 1 : 0,
                                    'custom_size_dimension' => (isset($productDetails['variable_decoration_size']) && $productDetails['variable_decoration_size'] != '') ? $productDetails['variable_decoration_size'] : '',
                                    'custom_size_dimension_unit' =>  (isset($productDetails['variable_decoration_unit']) && $productDetails['variable_decoration_unit'] != '') ? $productDetails['variable_decoration_unit'] : '',
                                    'is_custom_size' => (isset($productDetails['variable_decoration_size']) && $productDetails['variable_decoration_size'] != '') ? 1: 0,
                                    'is_variable_decoration' => (isset($productDetails['variable_decoration_size']) && $productDetails['variable_decoration_size'] != '') ? 1: 0,
                                    'product_type' => (isset($productDetails['type']))? $productDetails['type'] : '',
                                ];
                                $quotationItems = new QuotationItems($itemData);
                                if ($quotationItems->save()) {
                                    $lastQuotationItemId = $quotationItems->xe_id;
                                    $totalUnitPrice = 0;
                                    foreach ($productDetails['variation'] as $variations) {
                                        $variantId = $variations['variant_id'];
                                        $unitPrice = 0;
                                        if (STORE_NAME == 'Opencart') {
                                            $storeCompoInit = new StoreComponent();
                                            $unitPrice = $storeCompoInit->getPriceByVariantId($variantId);
                                        } else {
                                            $unitPriceArr = array_filter($productVariantData, function ($item) use ($variantId) {
                                                return $item['id'] == $variantId;
                                            });
                                            $unitPriceArr = $unitPriceArr[array_keys($unitPriceArr)[0]];
                                            if (!empty($unitPriceArr)) {
                                                $unitPrice = $unitPriceArr['price'];
                                            } else {
                                                $unitPrice = $productData['data']['price'];
                                            }
                                        }
                                        if (isset($productDetails['variable_decoration_size']) && $productDetails['variable_decoration_size'] != '' && (!isset($productDetails['is_sticker']) || $productDetails['is_sticker'] == 0)) {
                                            $unitPrice = ($requestDetails['product_price']/$totalQuantity);
                                        }
                                        $totalUnitPrice = $totalUnitPrice + (($unitPrice * $variations['qty']) + $requestDetails['decoration_price']);
                                        if ($isTierPriceEnable == 1) {
                                            if ($productDetails['type'] != 'simple') {
                                                foreach ($variations['attribute'] as $attributeKey => $attribute) {
                                                    $attributeName = $attributeKey;
                                                    //Get the tier price
                                                    $getTierPriceData = $productsControllerInit->getStore()->storeMultiAttributeVariantDetails($request, $response, [
                                                            'pid' => to_int($productDetails['product_id']),
                                                            'vid' => to_int($variantId),'attribute' => $attributeName,
                                                            'price' => 1, 'isAttribute' => 0]);
                                                    $getTierPriceData = $getTierPriceData[$attributeName];
                                                    $variantTierPriceDataArr = array_filter($getTierPriceData, function ($item) use ($variantId) {
                                                        return $item['variant_id'] == $variantId;
                                                    });
                                                    $variantTierPriceDataArr = $variantTierPriceDataArr[array_keys($variantTierPriceDataArr)[0]];
                                                    if (!empty($variantTierPriceDataArr)) {
                                                        $variantTierPriceData = $variantTierPriceDataArr['tier_prices'];
                                                        $updatedPrice = $variantTierPriceDataArr['price'];
                                                        break;
                                                    }
                                                }
                                            } else {
                                                //Get the tier price for simple product 
                                                $getproductTierPrice = call_curl(
                                                    [],
                                                        'product-details/' . $productDetails['product_id'] . '?variant_id=' . $variantId, 'GET'
                                                    );
                                                $variantTierPriceData = $getproductTierPrice['data']['tier_prices'];
                                                $updatedPrice = $getproductTierPrice['data']['price'];
                                            }
                                            if (!empty($variantTierPriceData)) {
                                                $quantity = $variations['qty'];
                                                for ($i = 0; $i < count($variantTierPriceData); $i++) {
                                                    if($variantTierPriceData[$i+1]['quantity']) {
                                                        if($quantity >= $variantTierPriceData[$i]['quantity'] && $quantity < $variantTierPriceData[$i+1]['quantity']) {
                                                            $updatedPrice = $variantTierPriceData[$i]['price'];
                                                            break;
                                                        } else if ($quantity > $variantTierPriceData[$i]['quantity']) {
                                                            $updatedPrice = $variantTierPriceData[$i+1]['price'];
                                                        }
                                                    }
                                                }
                                            }
                                        } else {
                                            $updatedPrice = $unitPrice;
                                        }
                                        $variations = [
                                            'item_id' => $lastQuotationItemId,
                                            'variant_id' => $variantId,
                                            'quantity' => $variations['qty'],
                                            'unit_price' => $unitPrice,
                                            'updated_price' => $updatedPrice,
                                            'attribute' => !empty($variations['attribute']) ? json_encode($variations['attribute']) : ''
                                        ];
                                        $quotationItemVariants = new QuotationItemVariants($variations);
                                        $quotationItemVariants->save();
                                    }
                                    //Update total unit price in quotation items table
                                    $quotationItemsInit = new QuotationItems();
                                    $quotationItemsInit->where('xe_id', $lastQuotationItemId)
                                        ->update(['unit_total' => $totalUnitPrice]);
                                    //Save sticker data
                                    if (isset($productDetails['is_sticker']) && $productDetails['is_sticker'] == 1) {
                                        $teamJerseyData = [
                                            'quote_item_id' => $lastQuotationItemId,
                                            'data' => json_clean_encode($productDetails['sticker_data']),
                                        ];
                                        $stickerDataSave = new QuoteStickerData($teamJerseyData);
                                        $stickerDataSave->save();
                                    }
                                    //Save team jersey data
                                    if (isset($productDetails['is_team_jersey']) && $productDetails['is_team_jersey'] == 1) {
                                        $teamJerseyData = [
                                            'quote_item_id' => $lastQuotationItemId,
                                            'data' => json_clean_encode($productDetails['team_jersey_data']),
                                        ];
                                        $teamJerseyDataSave = new TeamJerseyData($teamJerseyData);
                                        $teamJerseyDataSave->save();
                                    }
                                    //Add data to quotation log
                                    $logData = [
                                        'quote_id' => $quotationLastId,
                                        'title' => 'Quotation created',
                                        'description' => 'Quotation is created from designer tool',
                                        'user_type' => 'customer',
                                        'created_date' => date_time(
                                            'today', [], 'string'
                                        )
                                    ];
                                    $this->addingQuotationLog($logData);
                                }
                            }
                        }
                    } else {
                        $quoteId = 'INQ' . getRandom();
                    }
                    
                    $fileTypeArr = isset($requestDetails['form_details']['file_type']) ? $requestDetails['form_details']['file_type'] : [];
                    $dynamicFormInit = new QuotationDynamicForm();
                    $formCustomerData = [];
                    foreach ($requestDetails['form_details'] as $formKey => $formValue) {
                        /*if (!in_array($formKey, $fileTypeArr)) {
                            $formValue = !is_array($formValue) ? $formValue : json_clean_encode($formValue);
                        }*/
                        if ($formKey != 'file_type') {
                            $fileType = '';
                            if (in_array($formKey, $fileTypeArr)) {
                                $fileType = 'file';
                            }
                            $checkForSlug = $dynamicFormInit->select('label_slug')->where('label', $formKey)->first()->toArray();
                            if ($checkForSlug['label_slug'] == 'customername') {
                                $formCustomerData['name'] = $formValue;
                            } else {
                                if ($checkForSlug['label_slug'] == 'customeremail') {
                                    $formCustomerData['email'] = $formValue;
                                }
                            }
                            
                                
                            $formData = [
                                'quote_id' => $quoteId,
                                'form_key' => $formKey,
                                'form_value' => is_array($formValue) ? implode(',', $formValue) : $formValue,
                                'form_type' => $fileType,
                            ];
                            $saveFormData = new QuotationRequestFormValues($formData);
                            $saveFormData->save();
                        }
                       
                    }
                    if (!empty($requestDetails['product_details'])) {
                        $customDesignId = $requestDetails['design_details']['custom_design_id'];
                        if (!empty($customDesignId)) {
                            $svgJsonPath = path('abs', 'design_state') . 'artworks/' . $customDesignId . '.json';
                            $isS3Enabled = $this->checkS3Settings($getStoreDetails['store_id']);
                            if (!$isS3Enabled && file_exists($svgJsonPath)) {
                                $svgData = read_file($svgJsonPath);
                                $svgData = json_clean_decode($svgData, true);
                                if (!empty($svgData['design_product_data'])) {
                                    foreach ($svgData['design_product_data'] as $variantsValue) {
                                        if (!empty($variantsValue['design_urls'])) {
                                            foreach ($variantsValue['design_urls'] as $designs) {
                                                $emailParam['attachments'][] = str_replace(API_URL, rtrim(RELATIVE_PATH, WORKING_DIR) . '/', $designs);
                                            }
                                        }
                                    }

                                    // Generate Artwork File
                                    //Initiate order download controller
                                    $orderDwonloadObj = new OrderDownloadController();
                                    $getSideDataArr = $svgData['sides'];
                                    foreach ($getSideDataArr as $sideKey => $sideData) {
                                        if ($sideData['is_designed'] == '1') {
                                            $svgFileName = $customDesignId . '_' . $sideKey . ".svg";
                                            $pngFileName = $customDesignId . '_' . $sideKey . ".png";
                                            $path = path('abs', 'quotation') . $quotationLastId . '/' . $lastQuotationItemId . '/';
                                            $svgPath = $path . $svgFileName;
                                            $pngPath = $path . $pngFileName;
                                            if (!file_exists($path)) {
                                                create_directory($path);
                                            }
                                            if (!file_exists($svgPath)) {
                                                $parameter = array(
                                                    'key' => $sideKey, 'ref_id' => $customDesignId,
                                                    'item_path' => '',
                                                    'svg_preview_path' => $svgPath,
                                                    'value' => $sideData,
                                                    'is_design' => 1,
                                                );
                                                $orderDwonloadObj->createSideSvgByOrderId($parameter);
                                                if (file_exists($svgPath)) {
                                                    $orderDwonloadObj->svgConvertToPng($pngPath, $svgPath);
                                                }
                                            }
                                            $emailParam['attachments'][] = $svgPath;
                                        }
                                    }
                                    /*End*/
                                }
                            }
                        }
                        $requestData = [
                            'quote_id' => $quoteId,
                            'product_details' => !is_array($requestDetails['product_details'])
                            ? $requestDetails['product_details']
                            : json_encode($requestDetails['product_details']),
                            'design_details' => !is_array($requestDetails['design_details'])
                            ? $requestDetails['design_details']
                            : json_encode($requestDetails['design_details']),
                        ];
                        $saveRequestData = new QuotationRequestDetails($requestData);
                        $saveRequestData->save();
                        $lastSaveRequestDataId = $saveRequestData->xe_id;
                        //Update last quotation request id in quotation tgable
                        if (isset($quotationLastId) && isset($requestDetails['is_quotation_enable']) && $requestDetails['is_quotation_enable'] == 1 && $lastSaveRequestDataId > 0) {
                             $quotationInit->where('xe_id', $quotationLastId)
                                ->update(['quotation_request_id' => $lastSaveRequestDataId]);
                        }
                        $requestEmailContent = $this->bindRequestQuoteTemplate($requestDetails, $productData, $getStoreDetails, $formCustomerData);
                        $requestEmailContent = $requestEmailContent[0];
                        $emailParam['message'] = (!empty($requestEmailContent)) ? $requestEmailContent['message'] : '';
                        $emailParam['subject'] = (!empty($requestEmailContent)) ? $requestEmailContent['subject'] : '';
                        $this->sendQuotationEmail($emailParam, [], $getStoreDetails, $emailParam['attachments']);
                        //if ($mailResponse['status'] == 1) {
                            $jsonResponse = [
                                'status' => 1,
                                'message' => message('Quatation Request Data', 'saved'),
                                'quote_id' => $quotationLastId,
                            ];
                        //}
                    }
                }
            }
        } else {
            $jsonResponse = [
                'status' => 0,
                'message' => "No email is set in the admin section",
            ];
        }
        return response(
            $response, [
                'data' => $jsonResponse, 'status' => $serverStatusCode,
            ]
        );
    }

    /**
     * Move Quotation uploaded files to Oreder Folder
     *
     * @param $quotationId  Quotation Id
     * @param $orderId      Order Id
     *
     * @author debashrib@riaxe.com
     * @date   25th June 2020
     * @return boolean
     */
    public function moveQuoteFileToOrder($request, $response, $args, $returnType = 0)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quatation File', 'error'),
            'data' => false
        ];
        $getStoreDetails = get_store_details($request);
        $quotationId = to_int($args['id']);
        $orderId = !empty($request->getQueryParam('order_id')) ? $request->getQueryParam('order_id') : $args['order_id'];
        $args = [
            'id' => $orderId,
            'store_id' => $getStoreDetails['store_id']
        ];

        if ($quotationId != '' && $quotationId > 0 && $orderId != '' && $orderId > 0) {
            $decorationsInit = new ProductDecorationsController();
            $ordersInit = new OrdersController();
            $orderItemsDetails = $ordersInit->getStoreItemsDetails($request, $response, $args, 1);
            $itemDataArr = $this->itemsList($request, $response, $quotationId);
            $orderListData = $ordersInit->getOrders($request, $response, ['id' => $orderId, 'store_id' => $getStoreDetails['store_id']], 1);
            //adding quotation in order details array
            $quotationInit = new Quotations();
            $getQuotation = $quotationInit->select('quote_id', 'quote_source')
                ->where('xe_id', $quotationId)
                ->get()->toArray();
            $quotationNumber = $getQuotation[0]['quote_id'];
            $orderItemsDetails['order_details']['quotation_id'] = $quotationNumber;
            $orderItemsDetails['order_details']['quote_id'] = $quotationId;
            $orderItemsDetails['order_details']['quote_source'] = $getQuotation[0]['quote_source'];
            
            $finalOrderItemsDetails = $orderItemsDetails;
            $orderItemsDetails = $orderItemsDetails['order_details']['order_items'];
            $finalOrderData = [];
            foreach ($orderItemsDetails as $itemsData) {
                $tempOrderData = $itemsData;
                $tempOrderData['is_quote_order'] = 1;
                $files = [];
                if ($itemsData['ref_id'] < 0) {
                    $variantId = ($itemsData['product_id'] == $itemsData['variant_id']) ? 0 : $itemsData['variant_id'];
                    $productId = $itemsData['product_id'];
                    $refId = $itemsData['ref_id'];
                    $decoArr = array_filter($itemDataArr, function ($item) use ($variantId, $productId, $refId) {
                        if (strtolower(STORE_NAME) == "shopify"){
                            return ($item['custom_design_id'] == $refId);
                        }else{
                            return ($item['product_id'] == $productId && $item['variant_id'] == $variantId && $item['custom_design_id'] == $refId);
                        }
                    });
                    $decoArr = $decoArr[array_keys($decoArr)[0]];
                    $files = $decoArr['files'];
                }
                $tempOrderData['file_data'] = $files;
                array_push($finalOrderData, $tempOrderData);
            }
            $itemsList = $orderListData['order_details']['orders'];
            foreach ($itemsList as $key => $items) {
                $itemsList[$key]['is_quote_order'] = 1;
            }
            $finalOrderItemsDetails['order_details']['order_items'] = $finalOrderData;
            $finalOrderItemsDetails['order_details']['orders'] = $itemsList;
            //Initiate order download controller
            $orderDwonloadObj = new OrderDownloadController();
            $quotationflag = true;
            $isS3Enabled = $this->checkS3Settings($getStoreDetails['store_id']);
            if ($isS3Enabled) {
                $s3Flag = true;
            } else {
                $s3Flag = false;
            }
            $finalOrderItemsDetails['order_details']['order_number'] = $finalOrderItemsDetails['order_details']['order_incremental_id'];
            $status = $orderDwonloadObj->createOrderAssetFile(['id' => $orderId], $finalOrderItemsDetails, $request, $response , $quotationflag,$s3Flag);
            if ($status) {
                //Move file which are uploaded
                $finalItemArr = [];
                foreach ($itemDataArr as $items) {
                    $tempFilsArr = $items;
                    $productData = $decorationsInit->getDecorationDetail($request, $response, ['product_id' => $items['product_id']], 1); 
                    $newFileArr = [];
                    if ($items['is_variable_decoration'] == 0) {
                        $sizeDataArr = $productData['data']['sides'];
                        foreach ($sizeDataArr as $sideValue) {
                            $sideId = $sideValue['xe_id'];
                            $tempArr = [
                                'side_id' => $sideId,
                                'side_wise_files' => [],
                            ];
                            $sideArr = array_filter($items['files'], function ($item) use ($sideId) {
                                return $item['side_id'] == $sideId;
                            });
                            if (!empty($sideArr)) {
                                foreach ($sideArr as $value) {
                                    $tempArr = [
                                        'side_id' => $sideId,
                                        'side_wise_files' => $value['decoration_area'],
                                    ];
                                }
                            }
                            array_push($newFileArr, $tempArr);
                        }
                    } else {
                        foreach ($items['files'] as $filesArr) {
                            $tempArr = [
                                'side_id' => $filesArr['side_id'],
                                'side_wise_files' => $filesArr['decoration_area'],
                            ];
                            array_push($newFileArr, $tempArr);
                        }
                    }
                    $tempFilsArr['files'] = $newFileArr;
                    array_push($finalItemArr, $tempFilsArr);
                }
                foreach ($finalItemArr as $itemsArr) {
                    if ($itemsArr['custom_design_id'] < 0) {
                        if ($itemsArr['variant_id'] == 0) {
                            $storeItemArr = array_filter($orderItemsDetails, function ($item) use ($itemsArr) {
                                return ($item['product_id'] == $itemsArr['product_id'] && $item['variant_id'] == $itemsArr['product_id'] && $item['ref_id'] == $itemsArr['custom_design_id']);
                            });
                        } else {
                            $storeItemArr = array_filter($orderItemsDetails, function ($item) use ($itemsArr) {
                                if (strtolower(STORE_NAME) == "shopify"){
                                    return ($item['ref_id'] == $itemsArr['custom_design_id']);
                                }else{
                                 return ($item['product_id'] == $itemsArr['product_id'] && $item['variant_id'] == $itemsArr['variant_id'] && $item['ref_id'] == $itemsArr['custom_design_id']);
                                }
                            });
                        }
                        //$storeItemArr = $storeItemArr[array_keys($storeItemArr)[0]];
                        foreach ($storeItemArr as $storeItemArrValue) {
                            $itemId = $storeItemArrValue['item_id'];
                            foreach ($itemsArr['files'] as $key => $filesArr) {
                                $sideKey = $key + 1;
                                $side = 'side_' . $sideKey;
                                if (!empty($filesArr['side_wise_files'])) {
                                    foreach ($filesArr['side_wise_files'] as $files) {
                                        if (strtolower(STORE_NAME) == "shopify"){
                                            $orderId = $orderListData['order_details']['order_number'];
                                        }
                                        $disFilePath = path('abs', 'order') . $orderId . "/" . $itemId . "/" . $side;
                                        //Create folder
                                        if (!is_dir($disFilePath) && !file_exists($disFilePath)) {
                                                mkdir($disFilePath, 0755, true);    
                                        }
                                        $disPreviewFilePath = $disFilePath . "/preview";
                                        if (!is_dir($disPreviewFilePath) && !file_exists($disPreviewFilePath)) {
                                                mkdir($disPreviewFilePath, 0755, true);
                                        }
                                        copy($files['preview_file_path'], $disPreviewFilePath . '/' . $files['preview_file']);
                                        copy($files['design_file_path'], $disFilePath . '/' . $files['file']);
                                    }
                                }
                            }
                        }
                    }
                }
                //Send Email
                //Get Quotation details
                $quotationData = $this->getQuotationDetails($request, $response, ['id' => $quotationId], 1);
                //Bind email template
                $templateData = $this->bindEmailTemplate('convert_to_order', $quotationData, $getStoreDetails);
                $templateData = $templateData[0];
                //Send Email
                $this->sendQuotationEmail($templateData, $quotationData['customer'], $getStoreDetails, []);
            }
            $jsonResponse = [
                'status' => 1,
                'data' => true,
            ];
            if ($returnType == 1) {
                return $jsonResponse;
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Email Template data
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   09 Sept 2020
     * @return json response
     */
    public function getEmailTemplateData($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Email Template', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $quotationId = $allPostPutVars['quote_id'];
        $templateType = $allPostPutVars['template_type'];
        if ($quotationId !=''  && $quotationId > 0 &&$templateType != '') {
            $quotationDetails = $this->getQuotationDetails($request, $response, ['id' => $quotationId], 1);
            //print_r($quotationDetails);exit;
            $templateData = $this->bindEmailTemplate($templateType, $quotationDetails, $getStoreDetails);
            $templateData = $templateData[0]; 
            $jsonResponse = [
                'status' => 1,
                'data' => $templateData,
            ];
        }
        
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET: All quotation Ids
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   15 dec 2020
     * @return json response
     */
    public function getAllQuotationIds($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Ids', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $quotationInit = new Quotations();
        $getIds = $quotationInit->select('xe_id')->where('store_id', $getStoreDetails['store_id']);
        if ($getIds->count() > 0) {
            $getIdData = $getIds->get();
            $jsonResponse = [
                'status' => 1,
                'data' => $getIdData,
            ];
        } else {
            $jsonResponse = [
                'status' => 1,
                'data' => []
            ];
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET : check if customer is existes or not in store
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $returnType Response return type
     *
     * @author debashrib@riaxe.com
     * @date   09 Sept 2020
     * @return json response
     */
    public function checkForCustomer($request, $response, $returnType = 0)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Customer Check', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $quotationId = $request->getQueryParam('quote_id');
        $customerId = $request->getQueryParam('customer_id');
        $shippingId = ($request->getQueryParam('shipping_id') != '') ? $request->getQueryParam('shipping_id') : '-1';
        $quotationInit = new Quotations();
        $customersControllerInit = new CustomersController();
        if ($quotationId != '' && $quotationId > 0 && $customerId != 'null') {
            $checkLineItem = $this->checkForLineItems($request, $response, ['id' => $quotationId], 1);
            if ($customerId != '' && $customerId > 0) {
                $customerDetails = $customersControllerInit->getQuoteCustomerDetails($customerId, $getStoreDetails['store_id'], $shippingId, true);
                if (!empty($customerDetails)) {
                    $getQuotations = $quotationInit->select('xe_id', 'customer_name', 'customer_email')
                        ->where('xe_id', $quotationId);
                    if ($getQuotations->count() > 0) {
                        $getQuotationData = json_clean_decode($getQuotations->first(), true);
                        if ($getQuotationData['customer_name'] == '' || ($getQuotationData['customer_name'] != $customerDetails['customer']['name']) || $getQuotationData['customer_email'] == '' || ($getQuotationData['customer_email'] != $customerDetails['customer']['email'])) {
                            $updateData = [
                                'customer_name' => $customerDetails['customer']['name'],
                                'customer_email' => $customerDetails['customer']['email'],
                                'customer_availability' => 0
                            ];
                            $quotationInit->where('xe_id', $quotationId)
                                ->update($updateData);
                        }
                    }
                    $jsonResponse = [
                        'status' => 1,
                        'data' => true,
                        'show_item_msg' => $checkLineItem['show_item_msg'],
                    ];

                } else {
                    $updateData = [
                        'customer_name' => '',
                        'customer_email' => '',
                        'customer_availability' => 1
                    ];
                    $quotationInit->where('xe_id', $quotationId)
                        ->update($updateData);
                    $jsonResponse = [
                        'status' => 1,
                        'data' => false,
                        'show_item_msg' => $checkLineItem['show_item_msg'],
                    ];
                }
            } else {
                $jsonResponse = [
                    'status' => 1,
                    'data' => true,
                    'show_item_msg' => $checkLineItem['show_item_msg'],
                ];
            }
            
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }


     /**
     * GET : Quotation Item decoration details
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   23 feb 2020
     * @return json
     */
    public function getUploadedDecorationDetails($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Decoration', 'error'),
        ];
        //Get all measurment units
        $appUnitInit = new AppUnit();
        $initAppUnit = $appUnitInit->select('xe_id', 'name');
        $measurementUnitArr = $initAppUnit->get();
        $measurementUnitArr = json_clean_decode($measurementUnitArr, true);
        if (!empty($args['id'])) {
            $quotationId = to_int($args['id']);
            $itemId = $request->getQueryParam('item_id');

            if ($quotationId != '' && $quotationId > 0 && $itemId != '' && $itemId > 0) {
                $quoteItemsInit = new QuotationItems();
                $quoteItemFilesInit = new QuotationItemFiles();
                $getItem = $quoteItemsInit->where(['quote_id' => $quotationId, 'xe_id' => $itemId]);
                if ($getItem->count() > 0) {
                    //Get quotation item details
                    $getItemData = $getItem->first();
                    $getItemData = json_clean_decode($getItemData, true);
                    $productId = $getItemData['product_id'];
                    //Get quotation item
                    $uploadedDataArr = [];
                    $uploadedData = $quoteItemFilesInit->where('item_id', $itemId);
                    if ($uploadedData->count() > 0) {
                        $uploadedDataArr = $uploadedData->get();
                        $uploadedDataArr = json_clean_decode($uploadedDataArr, true);
                    }
                    //Get Product decoration details
                    $decorationsInit = new ProductDecorationsController();
                    $productDecorationArr = $decorationsInit->getDecorationDetail($request, $response, ['product_id' => $productId], 1); 
                    $productDecorationArr = $productDecorationArr['data'];
                    //Get measurement unit name
                    $measurementUnitId = $productDecorationArr['scale_unit_id'];
                    $unitArr = array_filter($measurementUnitArr, function ($item) use ($measurementUnitId) {
                        return $item['xe_id'] == $measurementUnitId;
                    });
                    $unitArr = $unitArr[array_keys($unitArr)[0]];
                    $measurementUnitName = $unitArr['name'];
                    if ($productDecorationArr['is_variable_decoration'] == 1) {
                        //Design hight and width
                        $extraDataValue = $uploadedDataArr[0]['extra_data'];
                        $extraDataArr = json_clean_decode($extraDataValue, true);
                        $uploadedDecoratedData = [
                            'preview_file' => path('read', 'quotation') . $quotationId . '/' . $itemId . '/' . $uploadedDataArr[0]['side_id'] . '/' . $uploadedDataArr[0]['preview_file'],
                            'design_file' => path('read', 'quotation') . $quotationId . '/' . $itemId . '/' . $uploadedDataArr[0]['side_id'] . '/' . $uploadedDataArr[0]['file'],
                            'decoration_area_id' => $uploadedDataArr[0]['decoration_area_id'],
                            'print_method_id' => $uploadedDataArr[0]['print_method_id'],
                            'decoration_settings_id' => $uploadedDataArr[0]['decoration_settings_id'],
                            'design_height' => (!empty($extraDataArr) && isset($extraDataArr['design_height']) && $extraDataArr['design_height'] != '') ? $extraDataArr['design_height'] : '',
                            'design_width' => (!empty($extraDataArr) && isset($extraDataArr['design_width']) && $extraDataArr['design_width'] != '') ? $extraDataArr['design_width'] : '',
                            'measurement_unit' => $measurementUnitName,
                        ];
                        $productDecorationArr['product_decoration']['uploaded_decorated_data'] = $uploadedDecoratedData;
                    } else {
                        $allSideArr = $productDecorationArr['sides'];
                        $type =  gettype($allSideArr);
                        if ($type == 'object') {
                            $allSideArr = json_clean_decode($allSideArr, true);
                        }
                        $finalSideArr = [];
                        if (!empty($allSideArr)) {
                            foreach ($allSideArr as $sideArr) {
                                $sideId = $sideArr['xe_id'];
                                $tempSideArr = $sideArr;
                                $finalDecoData = [];
                                foreach ($sideArr['product_decoration_setting'] as $productDecorationSetting) {
                                    $tempDecoData = $productDecorationSetting;
                                    $decorationSettingsId = $productDecorationSetting['xe_id'];
                                    $uploadedDecoData = array_filter($uploadedDataArr, function ($item) use ($decorationSettingsId) {
                                        return $item['decoration_settings_id'] == $decorationSettingsId;
                                    });
                                    $uploadedDecoData = $uploadedDecoData[array_keys($uploadedDecoData)[0]];
                                    if (!empty($uploadedDecoData)) {
                                        //Design hight and width
                                        $extraDataValue = $uploadedDecoData['extra_data'];
                                        $extraDataArr = json_clean_decode($extraDataValue, true);
                                        $uploadedDecoratedData = [
                                            'preview_file' => path('read', 'quotation') . $quotationId . '/' . $itemId . '/' . $sideId . '/' . $uploadedDecoData['preview_file'],
                                            'design_file' => path('read', 'quotation') . $quotationId . '/' . $itemId . '/' . $sideId . '/' . $uploadedDecoData['file'],
                                            'decoration_area_id' => $uploadedDecoData['decoration_area_id'],
                                            'print_method_id' => $uploadedDecoData['print_method_id'],
                                            'decoration_settings_id' => $uploadedDecoData['decoration_settings_id'],
                                            'design_height' => (!empty($extraDataArr) && isset($extraDataArr['design_height']) && $extraDataArr['design_height'] != '') ? $extraDataArr['design_height'] : '',
                                            'design_width' => (!empty($extraDataArr) && isset($extraDataArr['design_width']) && $extraDataArr['design_width'] != '') ? $extraDataArr['design_width'] : '',
                                            'measurement_unit' => $measurementUnitName,
                                        ];
                                        $tempDecoData['uploaded_decorated_data'] = $uploadedDecoratedData;
                                        array_push($finalDecoData, $tempDecoData);
                                    }
                                }
                                
                                $tempSideArr['product_decoration_setting'] = (!empty($finalDecoData)) ? $finalDecoData : $sideArr['product_decoration_setting'];
                                array_push($finalSideArr, $tempSideArr);
                            }
                        }
                        $productDecorationArr['sides'] = $finalSideArr;
                    }
                }
                $jsonResponse = [
                    'status' => 1,
                    'data' => $productDecorationArr,
                ];
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }


    /**
     * Quotation Folder delete with its file
     *
     * @param $dir  folder path
     *
     * @author debashrib@riaxe.com
     * @date   23 feb 2020
     * @return json
     */
    private function deleteQuoteFolder($dir)
    {
        foreach(glob($dir . '/*') as $file) {
            if(is_dir($file)){
                $this->deleteQuoteFolder($file);
            }
            else{
                unlink($file);
            }
        }
        rmdir($dir);
    }

    /**
     * GET : Quotation data assigned to respective customer
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   24 feb 2020
     * @return json
     */
    public function quoteAssignedToCustomer($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Customer Quotation', 'not_found'),
        ];
        $getStoreDetails = get_store_details($request);
        $userType = $request->getQueryParam('user_type');
        $userId = $request->getQueryParam('user_id');
        
        if (!empty($args['customer_id'])) {
            $customerId = to_int($args['customer_id']);

            if ($customerId != '' && $customerId > 0) {
                $quotationInit = new Quotations();
                $quotationData = $quotationInit->join('production_status', 'quotations.status_id', '=', 'production_status.xe_id')
                ->select([
                    'quotations.xe_id', 'quotations.quote_id', 'quotations.quote_total',
                    'quotations.created_at', 'production_status.status_name as quote_status',
                    'production_status.color_code',
                    DB::raw("(SELECT SUM(`quantity`) as total_quantity FROM `quote_items` WHERE quote_id = quotations.xe_id) as total_quantity")
                ])->where([
                    'quotations.customer_id' => $customerId,
                    'quotations.store_id' => $getStoreDetails['store_id']
                ]);
                if ($userType == 'agent') {
                    $quotationData->where('agent_id', $userId);
                }
                $quotationData->orderBy('quotations.created_at', 'DESC');
                $totalCount = $quotationData->count();
                if ($totalCount > 0) {
                    $quotationDataArr = json_clean_decode($quotationData->get(), true);
                    $jsonResponse = [
                        'status' => 1,
                        'total' => $totalCount,
                        'data' => $quotationDataArr,
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

     /**
     * GET: Quotation request data from tool
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author diana@imprintnext.com
     * @date   06 July 2021
     * @return json response
     */
    public function getRequestQuotationData($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Request Data', 'not_found'),
        ];
        $getStoreDetails = get_store_details($request);
        if (!empty($args['id'])) {
            $quotationId = to_int($args['id']);
            $quotationInit = new Quotations();
            $getQuotations = $quotationInit
                ->select('quote_id', 'quote_source', 'quotation_request_id')
                ->where(
                [
                    'store_id' => $getStoreDetails['store_id'],
                    'xe_id' => $quotationId,
                ]);
            $totalCounts = $getQuotations->count();
            if ($totalCounts > 0) {
                $quotationData = $getQuotations->first();
                $quotationData = json_clean_decode($quotationData, true);
                //Get quotation request data
                $quotationRequestData = [];
                if ($quotationData['quote_source'] == 'tool' || ($quotationData['quotation_request_id'] != '' && $quotationData['quotation_request_id'] > 0)) {
                    $quotationRequestFormValuesInit = new QuotationRequestFormValues();
                    $requestFormData = $quotationRequestFormValuesInit->select('form_key', 'form_value', 'form_type')->where('quote_id', $quotationData['quote_id']);
                    if ($requestFormData->count() > 0) {
                        $quotationRequestData = json_clean_decode($requestFormData->get(), true);
                        $finalQuotationRequestData = [];
                        foreach ($quotationRequestData as $requestData) {
                            $tempQuotationRequestData = $requestData;
                            $tempQuotationRequestData['is_file_type'] = false;
                            if ($requestData['form_type'] == 'file') {
                                $fileArr = explode(', ', $requestData['form_value']);
                                if (count($fileArr) > 1) {
                                    foreach ($fileArr as $multipleFile) {
                                        $multipleFileArr[] = path('read', 'quotation_request') . $multipleFile;
                                    }
                                    $tempQuotationRequestData['form_value'] = $multipleFileArr;

                                } else {
                                    $tempQuotationRequestData['form_value'] = path('read', 'quotation_request') . $fileArr[0];
                                }
                                $tempQuotationRequestData['is_file_type'] = true;
                            }
                            unset($tempQuotationRequestData['form_type']);
                            array_push($finalQuotationRequestData, $tempQuotationRequestData);
                        }
                    }
                }
                $jsonResponse = [
                    'status' => 1,
                    'data' => $finalQuotationRequestData,
                ];
                    
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * Get: check product stock 
     *
     * @param $request slim request
     * @param $response slim request
     *
     * @author steve@imprintnext.com
     * @date   30 dec 2021
     * @return json
     */
    public function productStockCheck($request, $response, $args) {
        $serverStatusCode = OPERATION_OKAY; 
        $jsonResponse = [
            'status' => 0,
            'message' => 'Stock Not Available',
        ];        
        $quotationId = $request->getQueryParam('qid');
        $quoteItemsInit = new QuotationItems();
        $variantsInit = new QuotationItemVariants();
        $storeId = $request->getQueryParam('store_id') ? $request->getQueryParam('store_id') : 1;
        $getItems = $quoteItemsInit->select('xe_id','product_id','quantity')->where('quote_id', $quotationId); 
        $productsControllerInit = new ProductsController();
        $getItemsData = $getItems->get()->toArray();
        $convert_to_order = 1;
        foreach ($getItemsData as $key  => $itemsData ){
            $getVariants = $variantsInit->where('item_id', $itemsData['xe_id'])->get()->toArray();
            $productId = $itemsData['product_id'];
            $variantId = $getVariants[0]['variant_id'];
            $getProductResponse = $productsControllerInit->getStore()->checkProductStock($productId,$variantId,$storeId);
            if($getProductResponse['stock'] < $itemsData['quantity']){
                $convert_to_order = 0;
            }
            $data[$key] = [
                'product_id' => $productId,
                'variant_id' => $variantId,
                'product_name' => $getProductResponse['productname'],
                "sku" => $getProductResponse['productsku'],
                'product_stock' =>$getProductResponse['stock'],
                'quotation_qty' => $itemsData['quantity'],
            ];
        }
        $jsonResponse = [
            'status' => 1,
            'convert_to_order' => $convert_to_order,
            'data' => $data,
        ];
        return response(
            $response,[
                'data' => $jsonResponse,'message' => $serverStatusCode,
            ]
        );
    }

    /**
     * Bind request a quote email template data
     *
     * @param $emailType  Email Template Type
     * @param $quotationDetails Quotation Details Array
     * @param $getStoreDetails Store Id
     *
     * @author diana@imprintnext.com
     * @date   22 Feb 2022
     * @return array response
     */
    public function bindRequestQuoteTemplate($formDetails, $productDetails, $getStoreDetails, $cutomerData = [])
    {
        $resData = [];
        if (!empty($formDetails) && !empty($productDetails) && !empty($getStoreDetails)) {
            //Bind email template
            $templateData = $this->getEmailTemplate(7, $getStoreDetails, 'request_a_quote');
            $abbrivationsInit = new ProductionAbbriviations();
            $getAbbrivations = $abbrivationsInit->where('module_id', 7);
            $getAbbrivations = $getAbbrivations->get();
            $abbriviationData = json_clean_decode($getAbbrivations, true);
            $formDetails['customer_name'] = (!empty($cutomerData) && isset($cutomerData['name']) && $cutomerData['name'] != '') ? $cutomerData['name'] : '';
            $formDetails['customer_email'] = (!empty($cutomerData) && isset($cutomerData['email']) && $cutomerData['email'] != '') ? $cutomerData['email'] : '';
            foreach ($abbriviationData as $abbrData) {
                $abbrValue = $this->getRequestQuoteAbbrValue($abbrData['abbr_name'], $formDetails, $productDetails, $getStoreDetails['store_id']);
                if (strpos($templateData[0]['message'], $abbrData['abbr_name']) !== false) {
                    $templateData[0]['message'] = str_replace($abbrData['abbr_name'], $abbrValue, $templateData[0]['message']);
                }
                if (strpos($templateData[0]['subject'], $abbrData['abbr_name']) !== false) {
                    $templateData[0]['subject'] = str_replace($abbrData['abbr_name'], $abbrValue, $templateData[0]['subject']);
                }
            }
            $resData = $templateData;
        }
        return $resData;
    }

    public function getRequestQuoteAbbrValue($abbrName, $details, $productData, $storeId)
    {
        $abbrValue = '';
        $formDetails = $details['form_details'];
        
        $variantDetails = $details['product_details']['variation'];
        //switch case
        switch ($abbrName) {
            case "{form_data}":
                $abbrValue = '<br>';
                if (array_key_exists("file_type",$formDetails))
                {
                    foreach ($formDetails['file_type'] as $fileType) {
                        unset($formDetails[$fileType]);
                    }
                    unset($formDetails['file_type']);
                }
                foreach($formDetails as $key => $value) {
                    $keyValue = is_array($value) ? implode(',', $value) : $value;
                    $abbrValue .= '<span style="padding-left:2%">'.$key.': '.$keyValue.'</span><br>';
                }
                break;
            case "{product_data}":
                $langSettingData = $this->readSettingJsonFile($storeId);
                $langSettingData = $langSettingData['lanuage'];
                $toolLang = $langSettingData['default']['name'];  
                $ordersInit = new OrdersController($toolLang);
                $pdfLanguage = $ordersInit->languageContent['quotation-pdf-and-public-link'];
                $abbrValue = '<br>';
                $abbrValue .= '<span style="padding-left:2%">Product name:  ' . $productData['data']['name'];
                        if (!empty($productData['data']['sku'])) {
                            $abbrValue .= ' (SKU: ' . $productData['data']['sku'] . ')';
                        }
                $abbrValue .= '</span>';
                if (!empty($variantDetails)) {
                    $variantData = $extraData = "";
                    $variationText = count($variantDetails) == 1 ? 'Variation' : 'Variations';
                    $abbrValue .= '<br><span style="padding-left:2%">'.$variationText.':</span>';
                    foreach ($variantDetails as $variations) {
                        if (array_key_exists("attribute",$variations))
                        {
                            unset($variations['attribute']);
                        }
                        if ($productData['data']['type'] == 'variable') {
                            $variantData .= "<br><span style='padding-left:4%'>";
                            foreach ($variations as $ItemKey => $items) {
                                if ($ItemKey != 'variant_id' && $ItemKey != 'variantId') {
                                    if ($ItemKey == 'qty') {
                                        $variantData = rtrim($variantData, '/');
                                        $variantData .= " - Qty - " . $items;
                                    } else {
                                        $variantData .=  $items . "/";
                                    }
                                }
                            }
                            $variantData .= "</span>";
                        }
                        if ($productData['data']['type'] == 'simple') {
                            $variantData .= "<span>";
                            foreach ($variations as $ItemKey => $items) {
                                if ($ItemKey == 'qty') {
                                    $variantData .= " - Qty - " . $items;
                                }
                            }
                            $variantData .= "</span>";
                        }
                    }
                    if (isset($details['product_details']['is_team_jersey']) && $details['product_details']['is_team_jersey'] == 1 && !empty($details['product_details']['team_jersey_data'])) {
                        $teamJerseyData = $details['product_details']['team_jersey_data'];
                        $extraData = '<br><br><div><b>'.$pdfLanguage['team-details'].':</b>';
                        $extraData .= '<table width="100%" cellspacing="0" cellpadding="0" style="border: 0px solid #e3e3e3; font-size: 14px; "><tbody><tr>';
                        foreach ($teamJerseyData[0] as $heading) {
                            if (isset($heading['value'])) {
                               $extraData .= '<th style="border: 1px solid #d3d3d3; text-align: center; padding: 6px 10px;">'.$heading['name'].'</th>';
                           }
                        }
                        $extraData .= '</tr>';  
                        foreach ($teamJerseyData as $jersey) {
                            $extraData .='<tr>';
                            foreach ($jersey as $jerseyVal) {
                                if (isset($jerseyVal['value'])) {
                                    if ($jerseyVal['type'] == 'image') {
                                        $extraData .='<td style="padding: 6px 10px; border: 1px solid #e3e3e3; text-align: center;"><img _ngcontent-mve-c18="" alt="team-logo" height="20px" width="20px" src="'.$jerseyVal['value'].'"></td>';
                                    } else {
                                        $extraData .='<td style="padding: 6px 10px; border: 1px solid #e3e3e3; text-align: center;">'.$jerseyVal['value'].'</td>';
                                    }
                                
                                }
                            }
                            $extraData .='</tr>';
                        }        
                        $extraData .= '</tbody></table>';
                        
                    } elseif (isset($details['product_details']['is_sticker']) && $details['product_details']['is_sticker'] == 1 && !empty($details['product_details']['sticker_data'])) {
                        $stickerData = $details['product_details']['sticker_data'];
                        $extraData = '<br><br><div><b>'.$pdfLanguage['sticker-info'].':</b>';
                        $extraData .= '<table width="100%" cellspacing="0" cellpadding="0" style="border: 0px solid #e3e3e3; font-size: 14px;">
                            <tbody>
                            <td style="vertical-align: top;">
                                <table>
                                    <tr>
                                      <td class="" style="padding: 0 0px 4px 20px;">'.$pdfLanguage['size'].'</td>
                                      <td style="padding: 0 0px 4px 20px;"><strong>'.$stickerData['width'].' x '. $stickerData['height'].' '. $stickerData['measurementUnit'].'</strong></td>
                                    </tr>
                                    <tr>
                                      <td class="" style="padding: 0 0px 4px 20px;">'.$pdfLanguage['cut-type'].'</td>
                                      <td style="padding: 0 0px 4px 20px;"><strong>'.ucfirst($stickerData['stickerType']).'</strong></td>
                                    </tr>
                                    <tr>
                                      <td class="" style="padding: 0 0px 4px 20px;">'.$pdfLanguage['sticker-option'].'</td>
                                      <td style="padding: 0 0px 4px 20px;"><strong>'.ucfirst($stickerData['stickerOption']).'</strong></td>
                                    </tr>
                                    <tr>
                                      <td class="" style="padding: 0 0px 4px 20px;">'.$pdfLanguage['material'].'</td>
                                      <td style="padding: 0 0px 4px 20px;"><strong>'.$stickerData['material'].'</strong></td>
                                    </tr>
                                    <tr>
                                      <td class="" style="padding: 0 0px 4px 20px;">'.$pdfLanguage['cutline'].'</td>
                                      <td style="padding: 0 0px 4px 20px;"><strong>'.$stickerData['cutline'].'</strong></td>
                                    </tr>';
                                    if (!empty($stickerData['sheetInfo'])) {
                                        $sheetDetails = '<table width="100%" cellspacing="0" cellpadding="0" style="border: 0px solid #e3e3e3; font-size: 14px; ">
                                      <tbody>
                                        <tr>
                                          <th style="border: 1px solid #d3d3d3; text-align: center; padding: 6px 10px;">'.$pdfLanguage['sheet'].'</th>
                                          <th style="border: 1px solid #d3d3d3; text-align: center; padding: 6px 10px;">'.$pdfLanguage['quantity'].'</th>
                                          
                                        </tr>';
                                        foreach ($stickerData['sheetInfo'] as $sheetInfo) {
                                            //sheet price
                                            (isset($sheetInfo['updated_price'])) ? $sheetInfo['updated_price'] : $sheetInfo['price'];
                                                $sheetDetails .= '<tr>
                                              <td style="padding: 6px 10px; border: 1px solid #e3e3e3; text-align: center;">'.$sheetInfo['name'].'</td>
                                              <td style="padding: 6px 10px; border: 1px solid #e3e3e3; text-align: center;">'.$sheetInfo['quantity'].'</td>
                                              
                                            </tr>';
                                        }
                                        $sheetDetails .='</tbody></table>';
                                        $extraData .= '<tr>
                                          <td class="" style="padding: 0 0px 4px 20px;">'.$pdfLanguage['sheet-info'].'</td>
                                          <td style="padding: 0 0px 4px 20px;">'.$sheetDetails.'</td>
                                        </tr>';
                                    }
                                    if (!empty($stickerData['rollInfo'])) {
                                        $rollInfo = $stickerData['rollInfo'];
                                        $extraData .= '<tr>
                                          <td class="" style="padding: 0 0px 4px 20px;">'.$pdfLanguage['roll-info'].'</td>
                                          <td style="padding: 0 0px 4px 20px;"><strong>'.$rollInfo['name'].'</strong></td> 
                                          <td><img src="'.$rollInfo['option']['file_name'].'" alt="" style="width: auto; height: 35px;"/>
                                          </td>
                                        </tr>';
                                    }
                                $extraData .= '</table>
                            </td>
                            </tbody>
                        </table>';

                    } elseif ($details['product_details']['variable_decoration_size'] != '' && $details['product_details']['variable_decoration_unit'] != '') {
                        $extraData = '<br><br><b>Dimension changed to: </b>'. $details['product_details']['variable_decoration_size'].' '.$details['product_details']['variable_decoration_unit'];
                    }
                    $customDesignId = $details['design_details']['custom_design_id'];
                    $previewLink = '';
                    if (!empty($customDesignId)) {
                        $svgJsonPath = path('abs', 'design_state') . 'artworks/' . $customDesignId . '.json';
                        $isS3Enabled = $this->checkS3Settings($storeId);
                        if ($isS3Enabled) {
                            $previewLink .= '<br><br><b>Artwork preview links:</b><br>';
                            $svgData = read_file($svgJsonPath);
                            $svgData = json_clean_decode($svgData, true);
                            if (!empty($svgData['design_product_data'])) {
                                foreach ($svgData['design_product_data'] as $variantsValue) {
                                    if (!empty($variantsValue['design_urls'])) {
                                        foreach ($variantsValue['design_urls'] as $designs) {
                                            $previewLink .= $designs.'<br>';
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $abbrValue .= $variantData . $extraData . $previewLink. "<br>";
                }
                break;
            case "{customer_name}":
                $abbrValue = $details['customer_name'];
                break;
            case "{customer_email}":
                $abbrValue = $details['customer_email'];
                break;
            case "{requested_date}":
                $date = date_time(
                        'today', [], 'string'
                    );
                $abbrValue = date('m-d-Y', strtotime($date));
                break;
            default:
                $abbrValue = $abbrName;
        }
        return $abbrValue;
    }

    /**
     * POST: move quotation to archive
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author diana@imprintnext.com
     * @date   09 Mar 2022
     * @return json response wheather data is updated or any error occured
     */
    public function moveToArchive($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Move to archive', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $quoteIds = $allPostPutVars['quote_ids'];
        $quoteIdArr = json_clean_decode($quoteIds, true);
        $quotationInit = new Quotations();
        $paymentInit = new QuotationPayment();
        $finalQuoteIdArr = [];
        if ($quoteIds == '') {
            //Get Order status id
            $statusInit = new ProductionStatus();
            $orderStatusId = 0;
            $getOrderedStatusData = $statusInit->select('xe_id')->where([
                'store_id' => $getStoreDetails['store_id'], 
                'slug' => 'ordered',
                'module_id' => 1
            ]);
            if ($getOrderedStatusData->count() > 0) {
               $getOrderedStatusDataArr = $getOrderedStatusData->first(); 
               $getOrderedStatusDataArr = json_clean_decode($getOrderedStatusDataArr, true);
               $orderStatusId = $getOrderedStatusDataArr['xe_id'];
            }
            //Get quotation ids from list  
            $getQuotation = $quotationInit
                ->join('quote_log', 'quotations.xe_id', '=', 'quote_log.quote_id')
                ->select('quotations.xe_id', 'quotations.quote_id', 'quotations.quote_total as total_amount', 'quote_log.created_date as order_date')
                ->where('quotations.status_id', $orderStatusId)
                ->where('quote_log.title', 'Converted to order');
            if ($getQuotation->count() > 0) {
                $getQuotationIds = $getQuotation->get();
                $getQuotationIdsArr = json_clean_decode($getQuotationIds, true);
                $currentDate = date('Y-m-d');
                $currentDate = strtotime($currentDate);
                $tempQuoteArr = [];
                foreach ($getQuotationIdsArr as $quoteData) {
                    //For due date
                    $paymentData = $paymentInit->select('xe_id', 'payment_amount', 'payment_status')
                        ->where([
                            'quote_id' => $quoteData['xe_id'],
                            'payment_status' => 'paid'
                        ])->sum('payment_amount');
                    $comPaidAmount = ($paymentData > 0) ? $paymentData : 0;
                    $comPaidAmount = number_format($comPaidAmount, 2, '.', '');
                    $dueAmount = $quoteData['total_amount'] - $comPaidAmount;
                    $orderDate = date('Y-m-d', strtotime($quoteData['order_date']));
                    $orderDate = strtotime($orderDate);
                    $dateDiff = ($currentDate - $orderDate)/60/60/24;
                    if ($dueAmount == 0 && $dateDiff > 15) {
                        array_push($tempQuoteArr, $quoteData['xe_id']);
                    }
                }
            }
            $finalQuoteIdArr = $tempQuoteArr;
        } else {
            $quotationList = $quotationInit->select('quotations.xe_id', 'quotations.quote_id', 'quotations.quote_total as total_amount')->whereIn('xe_id', $quoteIdArr);
            $quotationListData = $quotationList->get();
            $quotationListData = json_clean_decode($quotationListData, true);
            $tempQuoteArr = [];
            foreach ($quotationListData as $quoteList) {
                //For due date
                $paymentData = $paymentInit->select('xe_id', 'payment_amount', 'payment_status')
                    ->where([
                        'quote_id' => $quoteList['xe_id'],
                        'payment_status' => 'paid'
                    ])->sum('payment_amount');
                $comPaidAmount = ($paymentData > 0) ? $paymentData : 0;
                $comPaidAmount = number_format($comPaidAmount, 2, '.', '');
                $dueAmount = $quoteList['total_amount'] - $comPaidAmount;
                if ($dueAmount == 0) {
                    array_push($tempQuoteArr, $quoteList['xe_id']);
                }
            }
            $finalQuoteIdArr = $tempQuoteArr;
        }
        if (!empty($finalQuoteIdArr)) {
            foreach ($finalQuoteIdArr as $id) {
                $quotationInit->where('xe_id', $id)->update(['archive_status' => 1]);
                //Adding to quote log
                $logData = [
                    'quote_id' => $id,
                    'title' => 'Archive',
                    'description' => 'Quotation is moved to archive.',
                    'user_type' => $allPostPutVars['user_type'],
                    'user_id' => $allPostPutVars['user_id'],
                    'created_date' => date_time(
                        'today', [], 'string'
                    )
                ];
                $this->addingQuotationLog($logData);
            }
            $jsonResponse = [
                'status' => 1,
                'success_count' => count($finalQuoteIdArr),
                'message' => message('Move to archive', 'done'),
            ];
        } else {
            $jsonResponse = [
                'status' => 0,
                'message' => 'Payment is pending for this quotation.',
            ];
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: make quotation unarchive
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author diana@imprintnext.com
     * @date   28 Mar 2022
     * @return json response wheather data is updated or any error occured
     */
    public function unarchiveQuote($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('unarchive', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        $quoteIds = $allPostPutVars['quote_ids'];
        $quoteIdArr = json_clean_decode($quoteIds, true);
        $quotationInit = new Quotations();
        if (!empty($quoteIdArr)) {
            $checkData = $quotationInit->whereIn('xe_id', $quoteIdArr);
            if ($checkData->count() > 0) {
                foreach ($quoteIdArr as $id) {
                    //Change quotation archive status to 0
                    $quotationInit->where('xe_id', $id)
                        ->update(['archive_status' => 0]);
                    //Adding to quote log
                    $logData = [
                        'quote_id' => $id,
                        'title' => 'Unarchive',
                        'description' => 'Quotation has been unarchive.',
                        'user_type' => $allPostPutVars['user_type'],
                        'user_id' => $allPostPutVars['user_id'],
                        'created_date' => date_time(
                            'today', [], 'string'
                        )
                    ];
                    $this->addingQuotationLog($logData);
                }
                
                $jsonResponse = [
                    'status' => 1,
                    'message' => message('unarchive', 'done'),
                ];
            }
        }
        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 QuotationConversations();
            $conversations = $conversationsInit->where('xe_id', $conversationId);
            $conversationData = $conversations->first();
            if (!empty($conversationData)) {
                $conversationData = $conversationData->toArray();
                $quotationId = $conversationData['quote_id'];
                $senderType = $conversationData['user_type'];
                // $senderId = $conversationData['user_id'];
                $quotationInit = new Quotations();
                $quotation = $quotationInit->select('quote_id as quote_number','agent_id','customer_id')->where('xe_id', $quotationId);
                $quotationData = $quotation->first()->toArray();
                $customerId = $quotationData['customer_id'];
                //Get customer details
                $customersControllerInit = new CustomersController();
                $customerDetails = $customersControllerInit->getQuoteCustomerDetails($customerId, $getStoreDetails['store_id'], '');
                if (!empty($customerDetails)) {
                    $customerName = ($customerDetails['customer']['name'] != '') ? $customerDetails['customer']['name'] : $customerDetails['customer']['email'];
                    $customerEmail = $customerDetails['customer']['email'];
                }
                $agentId = $quotationData['agent_id'];
                $customerData = [];
                if ($agentId != '') {
                    //Send mail to Agent
                    $userInit = new User();
                    $agent = $userInit->select('xe_id', 'name', 'email')->where('xe_id', $agentId);
                    $agentDetails = $agent->first();
                    if (!empty($agentDetails)) {
                        $agentDetails = json_clean_decode($agentDetails, true);
                        $agentName = $agentDetails['name'];
                        $agentEmail = $agentDetails['email'];
                        $customerData = [
                            'name' => $agentName,
                            'email' => $agentEmail,
                        ];
                    }
                } else {
                    //Send Email to Superadmin
                    $userInit = new User();
                    $superAdmin = $userInit->select('xe_id', 'name', 'email')->where('xe_id', 1);
                    $superAdminDetails = $superAdmin->first();
                    $agentName = $superAdminDetails['name'];
                }
                //Get company name
                $settingInit = new ProductionHubSetting();
                $setting = $settingInit->select('setting_value')
                    ->where([
                        'module_id' => 1,
                        'setting_key' => 'company_name',
                        'store_id' => $getStoreDetails['store_id'],
                    ]);
                $settingData = $setting->first();
                $companyName = '';
                if (!empty($settingData)) {
                    $settingData = $settingData->toArray();
                    $companyName = $settingData['setting_value'];
                    $companyName = ltrim(rtrim($companyName, '"'), '"');
                    //$companyName = ltrim($companyName, '"');
                }
                if ($senderType == 'customer') {
                    //Send mail to Agent/Superadmin
                    $subject = 'A new message sent by '. $customerName . ' - Quotation #'.$quotationData['quote_number'];
                    $message = '<div>Hello '.$agentName.',</div><div><br></div><div>A new message is sent by customer '.$customerName.' for quotation #'.$quotationData['quote_number'].'.</div><div><br></div><div><b>Message:</b> '.$conversationData['message'].'</div><div><br></div><div>From,</div><div>'.$companyName.'</div>';
                } else {
                    //Send Mail to Customer
                    $token = 'quote_id=' . $quotationId.'&store_id='.$getStoreDetails['store_id'];
                    $token = base64_encode($token);
                    $url = 'quotation/quotation-approval?token=' . $token;
                    $publicUrl = API_URL.$url;
                    $subject = 'A new message sent by '. $agentName . ' - Quotation #'.$quotationData['quote_number'];
                    $message = '<div>Hello '.$customerName.',</div><div><br></div><div>A new message is sent by agent '.$agentName.' for quotation #'.$quotationData['quote_number'].'.</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><div>From,</div><div>'.$companyName.'</div>';

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

    /**
     * GET : check if quoation item's product decoration data is present or not
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $returnType Response return type
     *
     * @author diana@imprintnext.com
     * @date   11 Oct 2022
     * @return json response
     */
    public function checkForLineItems($request, $response, $args, $returnType = 0)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Customer items', 'error'),
        ];
       
        if (!empty($args['id'])) {
            $quotationId = $args['id'];
            $quotationItemsInit = new QuotationItems();
            $lineItems = $quotationItemsInit->where('quote_id', $quotationId);
            $lineItemsData = $lineItems->get();
            if (!empty($lineItemsData)) {
                $quotationItemFilesInit = new QuotationItemFiles();
                $productSideInit = new ProductSide();
                $productSettingInit = new ProductSetting();
                $checkFlag = 0;
                foreach ($lineItemsData as $items) {
                    if ($items['artwork_type'] == 'uploaded_file' && $items['is_variable_decoration'] == 0) {
                        //Check in product setting table
                        $checkSetting = $productSettingInit->where('product_id', $items['product_id']);
                        if ($checkSetting->count() > 0) {
                            $getProductSettingData = $checkSetting->first()->toArray();
                            $productSettingId = $getProductSettingData['xe_id'];
                            //Get files 
                            $fileData = $quotationItemFilesInit->where('item_id', $items['xe_id']);
                            $fileDataArr = $fileData->get();
                            foreach ($fileDataArr as $files) {
                                $productSide = $productSideInit->where([
                                    'product_setting_id' => $productSettingId,
                                    'xe_id' => $files['side_id']
                                ]);
                                if ($productSide->count() == 0) {
                                    $checkFlag = 1;
                                }
                            }
                        }
                    }
                }
                $jsonResponse = [
                    'status' => 1,
                    'show_item_msg' => ($checkFlag == 1) ? true : false,
                ];
                if ($returnType == 1) {
                    return $jsonResponse;
                }
            }
        }
        
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    public function getUsedCurrency($curencyId, $storeId) {
        $currencyArr = [];
        $currencyInit = new Currency();
        if ($curencyId != '' && $curencyId > 0) {
            $getCurrencyData = $currencyInit->where('xe_id', $curencyId)->first()->toArray();
            $currencyValue = utf8_decode($getCurrencyData['symbol']);
            if (strpos($currencyValue, '?') !== false) {
                $currencyVal = $getCurrencyData['symbol'];
            } else {
                $currencyVal = $currencyValue;
            }
            $currencyArr = [
                'id' => $getCurrencyData['xe_id'],
                'value' => $currencyVal,
                'unicode_character' => $getCurrencyData['unicode_character'],
                'code' => $getCurrencyData['code'],
            ];
        } else {
            $globalSettingData = $this->readSettingJsonFile($storeId);
            $getCurrencyId = $currencyInit->where('code', $globalSettingData['currency']['code'])
                ->first()->toArray();
            $currencyArr = [
                'id' => $getCurrencyId['xe_id'],
                'value' => $globalSettingData['currency']['value'],
                'unicode_character' => $globalSettingData['currency']['unicode_character'],
                'code' => $globalSettingData['currency']['code'],
            ];
        }
        return $currencyArr;

    }

    /**
     * GET: Get quotation default language
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     * @param $returnType     retun type
     *
     * @author diana@imprintnext.com
     * @date   06 Mar 2023
     * @return json response
     */
    public function getQuotationDefaultLang($request, $response, $returnType = 0)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Lang', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $langSettingData = $this->readSettingJsonFile($getStoreDetails['store_id']);
        $langSettingData = $langSettingData['lanuage'];
        $settingInit = new ProductionHubSetting();
        $settingData = $settingInit->select('setting_value', 'flag')
            ->where([
                'module_id' => 1,
                'setting_key' => 'quotation_default_lang',
                'store_id' => $getStoreDetails['store_id'],
            ]);
        if ($settingData->count() > 0) {
            $settingDataArr = $settingData->first()->toArray();
            $settingValue = json_clean_decode($settingDataArr['setting_value'], true);
            $languageInit = new Language();
            $defaultLang = $languageInit->select('name', 'flag', 'type')->where('name', $settingValue)->where('type', 'tool')->first()->toArray();
        } else {
            $defaultLang = $langSettingData['default'];
        }
        //Check for the language in list
        $defaultLangName = $defaultLang['name'];
        $checkLang = array_filter($langSettingData['lang_list'], function ($item) use ($defaultLangName) {
            return $item['name'] == $defaultLangName;
        });
        if (empty($checkLang)) {
            $defaultLang = $langSettingData['default'];
            //Update in quotation setting
            $settingInit->where([
                'module_id' => 1,
                'setting_key' => 'quotation_default_lang',
                'store_id' => $getStoreDetails['store_id'],
            ])->update(['setting_value' => json_clean_encode($defaultLang['name'])]);
        }
        $langauageData = [
            'default' => $defaultLang,
            'lang_list' => $langSettingData['lang_list']
        ];
        if ($returnType == 1) {
            return $langauageData;
        }
        $jsonResponse = [
            'status' => 1,
            'data' => $langauageData,
        ];
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    private function getItemProductData($request, $response, $productId, $quotationId, $itemId='', $flag = 0, $productSideImages = [])
    {
        $productsControllerInit = new ProductsController();
        $productDecorationArr = $productsControllerInit->getProductDetails($request, $response, ['id' => $productId], 1);
        $productDecorationArr = $productDecorationArr['data'];

        $decorationsInit = new ProductDecorationsController();
        $getSettingsAssociatedRecords = $decorationsInit->productSettingDetails(
            $request, $response,
            [
                'product_id' => $productId,
                'return_type' => 'array',
            ]
        );
        if (empty($getSettingsAssociatedRecords)) {
            $getSettingsAssociatedRecords = $decorationsInit->getDecorationDetail($request, $response,['product_id' => $productId], 1);
            $getSettingsAssociatedRecords = $getSettingsAssociatedRecords['data'];
            $productSideImages = $getSettingsAssociatedRecords['store_images'];
        }
        $productImgId = 0;
        $prodImgSettRelObj = new ProductImageSettingsRel();
        $checkForProductImageData = $prodImgSettRelObj->where('product_setting_id', $getSettingsAssociatedRecords['xe_id']);
        $doExistProdImgSetts = $checkForProductImageData->count();
        $checkForProductImage = $checkForProductImageData->first();
        $productImgId = to_int($checkForProductImage['product_image_id']);

        $prodImageSideObj = new ProductImageSides();
        $getProductImageSides = $prodImageSideObj->where('product_image_id', $productImgId)->orderBy('sort_order', 'ASC')->get();

        $allSideArr = $getSettingsAssociatedRecords['sides'];
        $type =  gettype($allSideArr);
        if ($type == 'object') {
            $allSideArr = json_clean_decode($allSideArr, true);
        }
        
        foreach ($allSideArr as $sideKey => $side) {
            if ($doExistProdImgSetts == 0) {
                    // Get Product Image Sides from Respective Stores
                    if (!empty($productSideImages[$sideKey])) {
                        $productSideImage = $productSideImages[$sideKey];
                    }
                } else {
                    $productImageObj = new ProductImage();
                    $imageDetails = $productImageObj->where('xe_id', $productImgId)->select('cloud_storage')->first()->toArray();
                    // Get Product Image Sides from DB
                    if (!empty($getProductImageSides[$sideKey])) {
                        $getProductImageSideData = $getProductImageSides[$sideKey];
                        if (!empty($getProductImageSideData)) {
                            $productSideImage = [
                                'id' => $getProductImageSideData->xe_id,
                                'src' => ($imageDetails['cloud_storage'] == 1) ? $this->getS3URL($getProductImageSideData->file_name, $storeId) : $getProductImageSideData->file_name,
                                'thumbnail' => ($imageDetails['cloud_storage'] == 1) ? $this->getS3URL($getProductImageSideData->thumbnail, $storeId) : $getProductImageSideData->thumbnail,
                            ];
                        }
                    }
                }
                $allSideArr[$sideKey]['image'] = $productSideImage;
        }
        $measurementUnitId = $getSettingsAssociatedRecords['scale_unit_id'];
        $measurementUnitArr = [];
        if ($measurementUnitId != '') {
            $appUnitInit = new AppUnit();
            $initAppUnit = $appUnitInit->select('xe_id', 'name')->where('xe_id', $measurementUnitId);
            $measurementUnitArr = $initAppUnit->first()->toArray();
        }

        $decoData = [
            'product_name' => $productDecorationArr['name'],
            'product_description' => $productDecorationArr['description'],
            'sku' => $productDecorationArr['sku'],
            'price' => $productDecorationArr['price'],
            'store_images' => $productDecorationArr['images'][0],
            'variant_id' => ($productDecorationArr['type'] == 'simple') ? $productId : $productDecorationArr['variant_id'],
            'measurement_unit' => $measurementUnitArr['name'],
            'sides' => $allSideArr,
        ];
        if ($flag == 1 && $itemId != '') {
            //Save item data in json file
            $filePath = path('abs', 'quotation') . $quotationId;
            if (!file_exists($filePath)) {
                create_directory($filePath);
            }
            $itemDataFilePath = $filePath.'/itemData.json';
            $itemDataJsonArr = [];
            if (file_exists($itemDataFilePath)) {
                $itemDataJson = read_file($itemDataFilePath);
                $itemDataJsonArr = json_clean_decode($itemDataJson, true);
            }
            $itemDataJsonArr[$itemId] = $decoData;
            write_file(
                $itemDataFilePath, json_clean_encode($itemDataJsonArr)
            );
            
        }
        return $decoData;
    }

    /**
     * GET: Check and update product data if it changed from store
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     * @param $returnType     retun type
     *
     * @author diana@imprintnext.com
     * @date   23 Jan 2024
     * @return json response
     */
    public function checkAndUpdateProductData($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Product data', 'error'),
        ];
        $quotationId = $args['id'];

        $quoteItemsInit = new QuotationItems();
        $getItems = $quoteItemsInit->select('xe_id', 'product_id')->where('quote_id', $quotationId);
        $getItemData = $getItems->get()->toArray();
        $productsControllerInit = new ProductsController();
        
        $itemDataFilePath = path('abs', 'quotation').$quotationId.'/itemData.json';
        $itemDataJson = read_file($itemDataFilePath);
        $itemDataJsonArr = json_clean_decode($itemDataJson, true);
        if (!empty($itemDataJsonArr)) {
            foreach ($getItemData as $item) {
                $quoteProductData = $itemDataJsonArr[$item['xe_id']];
                //Get the product data
                $productDetailsArr = $productsControllerInit->getProductDetails($request, $response, ['id' => $item['product_id']], 1);
                $productDetailsArr = $productDetailsArr['data'];
                if ($quoteProductData['product_name'] != $productDetailsArr['name'] || $quoteProductData['product_description'] != $productDetailsArr['description']) {
                    $itemDataJsonArr[$item['xe_id']]['product_name'] = $productDetailsArr['name'];
                    $itemDataJsonArr[$item['xe_id']]['product_description'] = $productDetailsArr['description'];
                    
                }
            }
            //Save item data in json file
            $filePath = path('abs', 'quotation') . $quotationId;
            if (is_dir($filePath)) {
                write_file($itemDataFilePath, json_clean_encode($itemDataJsonArr)
                );
            }
        }
        $jsonResponse = [
            'status' => 1,
            'message' => message('Product data', 'done'),
        ];
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }


    /**
     * GET: Check and update product data if it changed from store
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     * @param $returnType     retun type
     *
     * @author diana@imprintnext.com
     * @date   23 Jan 2024
     * @return json response
     */
    public function getProductDeco($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Product data', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $productId = $args['id'];

        $decorationsInit = new ProductDecorationsController();
        $getSettingsAssociatedRecords = $decorationsInit->productSettingDetails($request, $response, [
            'product_id' => $productId,
            'return_type' => 'array'
        ]);
        $productImgId = 0;
        $prodImgSettRelObj = new ProductImageSettingsRel();
        $checkForProductImageData = $prodImgSettRelObj->where('product_setting_id', $getSettingsAssociatedRecords['xe_id']);
        $doExistProdImgSetts = $checkForProductImageData->count();
        $checkForProductImage = $checkForProductImageData->first();
        $productImgId = to_int($checkForProductImage['product_image_id']);

        $prodImageSideObj = new ProductImageSides();
        $getProductImageSides = $prodImageSideObj->where('product_image_id', $productImgId)->orderBy('sort_order', 'ASC')->get();
        $resData['is_decoration'] = true;
        $productsControllerInit = new ProductsController();
        $getStoreProduct = $productsControllerInit->getStore()->getProducts($request, $response, [
            'id' => $productId, 'store_id' => $getStoreDetails['store_id']
        ]);
        $productSideImages = $getStoreProduct['products']['images'];
        if (empty($getSettingsAssociatedRecords)) {
            
            $defaultDecoData = $decorationsInit->getDefaultDecoData($productSideImages, $getStoreDetails['store_id']);
            $getSettingsAssociatedRecords = $defaultDecoData;
            $resData['product_description'] = $getStoreProduct['products']['description'];
            $resData['is_decoration'] = false;
        }
        $finalSideData = $getSettingsAssociatedRecords['sides'];
        foreach ($finalSideData as $sideKey => $side) {
            if ($doExistProdImgSetts == 0) {
                    // Get Product Image Sides from Respective Stores
                    if (!empty($productSideImages[$sideKey])) {
                        $productSideImage = $productSideImages[$sideKey];
                    }
                } else {
                    $productImageObj = new ProductImage();
                    $imageDetails = $productImageObj->where('xe_id', $productImgId)->select('cloud_storage')->first()->toArray();
                    // Get Product Image Sides from DB
                    if (!empty($getProductImageSides[$sideKey])) {
                        $getProductImageSideData = $getProductImageSides[$sideKey];
                        if (!empty($getProductImageSideData)) {
                            $productSideImage = [
                                'id' => $getProductImageSideData->xe_id,
                                'src' => ($imageDetails['cloud_storage'] == 1) ? $this->getS3URL($getProductImageSideData->file_name, $storeId) : $getProductImageSideData->file_name,
                                'thumbnail' => ($imageDetails['cloud_storage'] == 1) ? $this->getS3URL($getProductImageSideData->thumbnail, $storeId) : $getProductImageSideData->thumbnail,
                            ];
                        }
                    }
                }
                $finalSideData[$sideKey]['image'] = $productSideImage;
        }
        $scaleUnitId = $getSettingsAssociatedRecords['scale_unit_id'];
        $appUnitInit = new AppUnit();
        $initAppUnit = $appUnitInit->select('xe_id', 'name')->where('xe_id', $scaleUnitId);
        $measurementUnitArr = $initAppUnit->first()->toArray();
        $resData += [
            'sides' => $finalSideData,
            'measurement_unit' => $measurementUnitArr['name'],
        ];
        $jsonResponse = [
            'status' => 1,
            'data' => $resData,
        ];
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }
}