<?php

namespace Modules\PrintSuppliers\Controllers;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Modules\PrintSuppliers\Models\PrintLogisticSku;
use Illuminate\Support\Facades\Config;
use Modules\PrintSuppliers\Models\Order;
use Modules\PrintSuppliers\Models\Shipper;
use Modules\PrintSuppliers\Models\OrderMeta;
use Carbon\Carbon;
use Modules\PrintSuppliers\Models\OrderItem;
// use GuzzleHttp\Client;

class PrintLogisticController extends Controller
{
    private $printingName = 'printLogistic';
    private $apiUrl;
    private $credential;

    const PRINT_LOGISTIC_COUNTRY_IDS = [225, 73, 80, 105, 172, 199, 150, 205];


    public function __construct()
    {
        $this->credential = $this->getCredential('printerval', 'printlogistic');
        $this->apiUrl = Config::get('print-suppliers::connection.printlogistic.api_url', 'https://panel.smartfactore.eu:7443/api');
    }

    public function internalCallApi(Request $request)
    {
        $endPoint = $request->input('end_point');
        $method = $request->input('method', 'GET');
        $params = $request->input('params', []);
        
        return $this->triggerSyncRequest($this->apiUrl . '/' . $endPoint, $method, $params, [
            'merch-key: ' . $this->credential[1],
            'Content-Type: application/json'
        ]);
    }

    public function getProductTypes () {

        $dataCacheKey = 'PRINT_LOGISTIC_PRODUCT_TYPE_' . config('app.version');
        if (Cache::has($dataCacheKey)) {

            $productTypes = Cache::get($dataCacheKey, []);

        } else {

            $productTypes = PrintLogisticSku::query()
                ->select(['product_type'])
                ->groupBy('product_type')
                ->pluck('product_type');

            Cache::put($dataCacheKey, $productTypes, 3600); // cache

        }

        return $productTypes;
    }

    public function getProductSkus (Request $request)
    {
        $productType = $request->input('product_type');
        $productColor = $request->input('product_color');
        $productSize = $request->input('product_size');
        $productBrand = $request->input('product_brand');
        $groupBy = $request->input('group');

        $productSkuQuery = PrintLogisticSku::query();
        $productSkuQuery->where('product_type', $productType);

        if ($productColor) {
            $productSkuQuery->where('color', $productColor);
        }
        if ($productSize) {
            $productSkuQuery->where('size', $productSize);
        }
        if ($productBrand) {
            $productSkuQuery->where('brand', $productBrand);
        }
        if ($groupBy) {
            $groupBy = explode(',', $groupBy);
            $productSkuQuery->groupBy($groupBy);
        }

        return $productSkuQuery->get();
    }

    public function cronJobGetOrderStatus(Request $request)
    {
        set_time_limit(3600);

        $this->setupJobs();

        $debug = $request->input('debug', 0);

        $date = new Carbon();
        $yesterday = $date->now()->subDays(7);

        $jobs = DB::table('print_logistic_job')
            ->where(function($q) use($yesterday) {
                $q->whereNull('updated_at');
                $q->orWhere('updated_at', '>=', $yesterday->format('Y-m-d 00:00:00'));
            })
            ->orderBy('updated_at', 'asc')
            ->whereNull('finished_at')
            ->limit(500)
            ->get();

        if ($debug == 1) {
            var_dump($jobs);
            die;
        }

        foreach ($jobs as $job) 
        {
            DB::table('print_logistic_job')->where('id', $job->id)->update(['updated_at' => date('Y-m-d H:i:s')]);
            $this->changeOrderStatus($job->job_id, $job->order_code);
        }

        return [
            'jobs' => $jobs
        ];
    }

    private function getJobCode($jobLog)
    {
        try {
            $data = json_decode($jobLog->data, true);
            $jobId = $data['job_id'];
            $orderCode = explode('_', $jobId)[1]; 

            return [$jobId, $orderCode];

        } catch (\Exception $ex) {
            return [null, null];
        }
    }

    protected function setupJobs()
    {
        $date = new Carbon();
        $timeAgo = $date->now()->subDays(30)->format('Y-m-d H:i:s');

        $logId = 0;
        $lastestJob = DB::table('print_logistic_job')->orderBy('id', 'desc')->first();
        if ($lastestJob) {
            $logId = $lastestJob->log_id;
        }
        
        if (isset($_GET['rebuild']) && $_GET['rebuild'] == 1) {
            $logId = 20373240;
        }
        
        $jobLogs = DB::table('log')
            ->whereIn('event_type', ['PRINTLOGISTIC-FULFILLMENT', 'PRINTLOGISTIC_AUTO_FULFILL'])
            ->where('id', '>', $logId)
            ->where('created_at', '>=', $timeAgo)
            ->select(['id', 'target_id', 'data', 'created_at'])
            ->get();

        $jobs = [];
        for ($i = 0; $i < count($jobLogs); $i++) {
            list($jobId, $orderCode) = $this->getJobCode($jobLogs[$i]);
            $jobs[] = [
                'job_id' => $jobId,
                'log_id' => $jobLogs[$i]->id,
                'order_code' => $orderCode,
                'created_at' => $jobLogs[$i]->created_at,
                // 'updated_at' => date('Y-m-d H:i:s'),
            ];
        }

        DB::table('print_logistic_job')->insert($jobs);
    }

    public function webhook(Request $request)
    {
        $input = $request->all();

        $retVal['status'] = 'fail';
        $retVal['message'] = 'Empty resource ID & DATA.';

        if (!empty($input['job_id'])) {
            
            // example jobId API_DE0682359_4218 API_DE0682359
            $orderCode = explode('_', $input['job_id'])[1]; 
            $result = $this->changeOrderStatus($input['job_id'], $orderCode);

            if ($result > 0) {
                $retVal['status'] = 'successful';
                unset($retVal['message']);
            } else if ($result === 0) {
                $retVal['message'] = 'Status not match from Config.';
            } else { // $result = -1
                $retVal['message'] = 'Order Not Found.';
            }
            
        }

        return response()->json($retVal, 200, [], JSON_NUMERIC_CHECK);
    }

    private function changeOrderStatus($jobId, $orderCode)
    {
        $mapStatus = Config::get('print-suppliers::statuses.print_logistic');
        $printLogisticOrder = $this->getPrintLogisticJob($jobId);

        if (isset($printLogisticOrder['status']) && !empty($mapStatus[$printLogisticOrder['status']])) {
            
            $originOrder = Order::query()
                ->where('code', '=', $orderCode)
                ->whereNotIn('status', ['CANCELED', 'REQUEST_RETURN', 'RETURNED', 'PROCESSING', 'FINISHED'])
                ->where('payment_status', '=', 'PAID')
                ->orderBy('id', 'DESC')
                ->first();

            $job = DB::table('print_logistic_job')->where('job_id', $jobId)->first();

            if (!$job) return -1;

            if (!$job->status || $job->status != $printLogisticOrder['status']) {
                DB::table('print_logistic_job')->where('job_id', $jobId)
                    ->update(['status' => $printLogisticOrder['status']]);
            }

            // update finish job
            if (!$originOrder || $printLogisticOrder['status'] == 'Sent' || $printLogisticOrder['status'] == 'shipped') {
                DB::table('print_logistic_job')->where('job_id', $jobId)->update(['finished_at' => date('Y-m-d H:i:s')]);
            }

            if ($job->status == $printLogisticOrder['status']) {
                return 0;
            }

            if (!$originOrder || empty($originOrder->id)) {
                return -1; // order not found
            }

            $this->updateOrder($originOrder, $printLogisticOrder, 'Webhook');
            
            return $originOrder->id; // ok
            
        } else {
            return 0; // not match order statuses
        }
    }

    public function updateOrder($originOrder, $printLogisticOrder, $refer = 'Printerval')
    {
        $dataUpdate = [];
        $mapStatus = Config::get('print-suppliers::statuses.print_logistic');

        if (isset($mapStatus[$printLogisticOrder['status']])) {
            $dataUpdate['status'] = $mapStatus[$printLogisticOrder['status']];
        }

        if (isset($mapStatus[$printLogisticOrder['status']])) {
            $dataUpdate['status'] = $mapStatus[$printLogisticOrder['status']];
        }

        if (!empty($printLogisticOrder['tracking_number'])) {
            $this->updateTracking($originOrder, $printLogisticOrder);
        }
        
        $this->sendUpdateOrder($originOrder->id, $dataUpdate, ["Referal: $refer"]);
    }

    private function sendUpdateOrder($orderId, $dataUpdate, $headers = []) 
    {
        $updateUrl = Config::get('sa.api_url') . '/api/update-order/' . $orderId;
        array_push($headers, 'Content-Type:application/json');

        return $this->triggerSyncRequest($updateUrl, 'POST', $dataUpdate, $headers);
    }

    private function updateTracking($order, $printLogisticOrder)
    {
        $shipments = [];
        $shipmentKey = 'shipment';

        $shipper = null;
        if (!empty($printLogisticOrder['carrier'])) {
            $shipper = Shipper::firstOrCreate(['name' => $printLogisticOrder['carrier']], ['name' => $printLogisticOrder['carrier'], 'meta_data' => 'Created by Webhook']);
        }

        if($shipper) 
        {
            OrderMeta::updateOrCreate([ 'order_id' => $order->id, 'key' => $shipmentKey ], [ 'value' => $shipper->id ]);

            $shipment['id'] = $shipper->id;

            if (!empty($printLogisticOrder['tracking_number'])) {
                $shipment['code'] = $printLogisticOrder['tracking_number'];
            } 

            if (!empty($printLogisticOrder['tracking_url'])) {
                if (str_contains($printLogisticOrder['tracking_url'], 'https://tracking.asendia.com/tracking/')){
                    $printLogisticOrder['tracking_url'] = 
                            str_replace('https://tracking.asendia.com/tracking/', 
                                'https://a-track.asendia.com/customer-tracking/self?tracking_id=', 
                                $printLogisticOrder['tracking_url']
                            );
                }
                $shipment['url'] = $printLogisticOrder['tracking_url'];
            }
            
            if (isset($shipment) && !empty($shipment)) {
                $shipments[] = $shipment;

                OrderMeta::updateOrCreate([ 'order_id' => $order->id, 'key' => 'shipment_data' ], [ 'value' => json_encode($shipments) ]);
            }
        }

        return $shipments;
    }

    public function getPrintLogisticJob($jobId)
    {
        $headers = [
            'merch-key: ' . $this->credential[1],
            'Content-Type: application/json'
        ];

        return $this->triggerSyncRequest($this->apiUrl . '/order/status/' . $jobId, 'GET', [], $headers);
    }

     /**
     * Request send order Printify to production
     * */
    public function submitProduction(Request $request)
    {
        $responseData = [
            'status' => self::STATUS_FAIL
        ];

        $orderId = $request->input('order_id');

        if ($orderId) {
            // https://panel.smartfactore.eu:7443/api/order/update/:id/accept
            $response = $this->triggerSyncRequest($this->apiUrl . "/order/update/{$orderId}/accept", 'GET', [], [
                'merch-key: ' . $this->credential[1],
                'Content-Type: application/json'
            ]);

            if (isset($response['job_id'])) {

                $systemOrderId = $request->input('id');
                if ($systemOrderId) {
                    DB::table('order_meta')->insert([
                        'key' => 'in_production_time',
                        'order_id' => $systemOrderId,
                        'value' => date('Y-m-d H:i:s')
                    ]);
                }

                $responseData['status'] = self::STATUS_SUCCESSFUL;
            }
            $responseData['result'] = $response;
        }

        return $responseData;
    }

    /* public function updateJobStatus()
    {
        set_time_limit(3000);

        $jobids = file_get_contents(public_path('jobids.txt'));
        $jobids = explode("\r\n", $jobids);

        $client = new Client([
            'headers' => [
                'Content-Type' => 'application/json'
            ]
        ]);

        foreach($jobids as $id) {
            if ($id) {
                $locale = strtolower(substr($id,  0, 2));
                $httpResponse = $client->post("https://printerval.com/$locale/print-suppliers/print-logistic/webhook", [
                    'body' => json_encode([
                        'job_id' => $id 
                    ], JSON_UNESCAPED_UNICODE)
                ]);
                \Log::info("UPDATE_JOB", [$id, json_decode($httpResponse->getBody(), true)]);
            }
        }

    } */

    public function getTemplates($orderId) {

        $retval = [
            'status' => 'successful',
            'msg' => ''
        ];

        try {
            $routeParameters = Route::current()->parameters();
            $orderId = $routeParameters['orderId'];
            $order = (object) $this->findOrderDetail($orderId);
            $retval['order'] = $order;
            if ($order) {
                $retval['order'] = $order;
            } else {
                throw new \Exception("Order not found", 1);
            }
            if (!in_array($order->country_id, self::PRINT_LOGISTIC_COUNTRY_IDS)) {
                throw new \Exception("PRINT_LOGISTIC_COUNTRY_IDS Only", $order->country_id);
            }
            $order->printing_service = 'print_logistic';
            $items = $order->items;
            foreach ($items as $key => $item) {
                $itemId = $item['id'];
                $input = $this->getTemplateInput($item['product_sku_id']);
                if ($input[0] == null) {
                    throw new \Exception("Can not get item input, item id : $itemId", 3);
                }
                $template = $this->getTemplate($input, $item['product_id']);
                if (!$template) {
                    throw new \Exception("Not found template, item id : $itemId", 404);
                }
                $items[$key]['template'] = $template;
            }
            if (count($items)) {
                $retval['items'] = $items;
            } else {
                throw new \Exception("Items not found", 2);
            }
        } catch (\Exception $e) {
            $retval['status'] = 'fail';
            $retval['msg'] = $e->getMessage() . '. Line: ' . $e->getLine() . '. File: ' . $e->getFile();
        }

        return $retval;
    }

    public function autoFulfill(Request $request)
    {
        $responseData = [
            'status' => self::STATUS_FAIL,
            'msg' => 'order_id is required!'
        ];

        $orderId = $request->input('order_id');

        if ($orderId) {

            try {

                $order = $this->findOrderDetail($orderId);

                $order['resource_id'] = null;

                if ($order && (!isset($order['resource_id']) || !$order['resource_id'])) {

                    $inventoryItems = $this->buildInventoryItems($order);

                    if (isset($inventoryItems['items']) && count($inventoryItems['items']) == count($order['items'])) {

                        $orderSchema = $this->getFulfillOrderSchema($order, $inventoryItems);

                        if (isset($_GET['debug'])) {
                            dd($orderSchema);
                        }

                        $fulfillResponse = $this->fulfill($order, $orderSchema);

                        $responseData = [
                            'result' => $fulfillResponse
                        ];

                        if ($fulfillResponse !== false) {

                            $condition = isset($fulfillResponse['status']) && $fulfillResponse['status'] == 'Success';
                            $condition_2 = isset($fulfillResponse['order_id']);

                            if ($condition || $condition_2) {

                                $responseData['status'] = self::STATUS_SUCCESSFUL;

                                OrderItem::query()->whereIn('id', $inventoryItems['orderItemIds'])
                                    ->update([
                                        'printing_code' => 'print-logistic',
                                        'print_provider' => 'PRINTLOGISTIC'
                                    ]);

                                // update resource_id
                                $objectOrder = Order::query()->find($order['id']);
                                $objectOrder->resource_id = $orderSchema['job_id'];
                                $objectOrder->save();

                            }
                        }

                    }  else {
                        $responseData = [
                            'status' => self::STATUS_FAIL,
                            'msg' => 'Không build được đủ line items'
                        ];
                    }

                } else {
                    $msg = 'Không tìm thấy chi tiết đơn Printerval hoặc đơn đã được fulfill, kiểm tra resource_id trong đơn hàng!';
                    if (isset($order['resource_id']) && $order['resource_id']) {
                        $msg = 'Đơn fullfill trùng lặp!';
                    } elseif (!$order) {
                        $msg = 'Không tìm thấy chi tiết đơn Printerval';
                    }

                    $responseData = [
                        'status' => self::STATUS_FAIL,
                        'msg' => $msg
                    ];
                }

            } catch (Exception $ex) {
                $errorMsg = 'Error on line '. $ex->getLine().' in '.$ex->getFile() .': '.$ex->getMessage();
                $responseData = [
                    'status' => self::STATUS_FAIL,
                    'msg' => $errorMsg
                ];
            }
        }

        return $responseData;
    }

    protected function getFulfillOrderSchema($orderDetail, $inventoryItems)
    {
        $fullname = $orderDetail['customer']['full_name'];
        $phone = $orderDetail['customer']['phone'];

        if (isset($orderDetail['attributes']['customer_info'])) {
            $fullname = $orderDetail['attributes']['customer_info']['full_name'];
            $phone = $orderDetail['attributes']['customer_info']['phone'];
        }

        if (isset($orderDetail['attributes']['gift_info']['name']) && $orderDetail['attributes']['gift_info']['name']) {
            $fullname = $orderDetail['attributes']['gift_info']['name'];
            $phone = $orderDetail['attributes']['gift_info']['phone'];
        }

        $customerName = getCustomerName($fullname);
        
        $lastName = $customerName['last_name'];
        $firstName = $customerName['first_name'];

        $orderReferenceId = "AUTO_" . $orderDetail['code'];

        return [
            "job_id" => $orderReferenceId,
            "job_provider" => "Printerval",
            "special_handling" => "",
            "cancelled" => "false",
            "inventory_items" => $inventoryItems["items"],
            "placements" => $inventoryItems["placementTokens"],
            "mockups" => $inventoryItems["mockupTokens"],
            "artworks" => $inventoryItems["artworkTokens"],
            "shipments" => [
                [
                    "type" => ($orderDetail["shipping_type"] === 'standard' ? 'Standard' : 'Express'),
                    "transport_data" => [
                        [
                            "company" => "",
                            "name" => $firstName,
                            "surname" => $lastName,
                            "address_1" => $orderDetail["delivery_address"],
                            "address_2" => (isset($orderDetail['optional_address']) && $orderDetail['optional_address']) ? $orderDetail['optional_address'] : ' ',
                            "city" => $orderDetail['city_name'],
                            "post-code" => $orderDetail["zip_code"],
                            "country" => $orderDetail["country"]["iso"],
                            "phone" => $phone,
                            "email" => 'info@megaads.vn'
                        ]
                    ]
                ]
            ]
        ];
    }

    protected function buildInventoryItems($order)
    {
        $items = [];
        $artworkTokens = [];
        $mockupTokens = [];
        $placementTokens = [];
        $orderItemIds = [];
    
        for ($i = 0; $i < count($order['items']); $i++)
        {
            $item = $order['items'][$i];

            $input = $this->getTemplateInput($item['product_sku_id']);
            if ($input[0] == null) {
                throw new \Exception("Can not get item input, item id: " . $item['id'], 3);
            }

            $printSku = $this->getTemplate($input, $item['product_id']);

            if (!$printSku) {
                throw new \Exception("Cannot find template, item id: " . $item['id'], 3);
            }
    
            $layouts = [];

            $printableAreas = ['front', 'back'];
            $printAreas = $this->getPrintLocations($item);
            
            if (!count(array_diff($printAreas, $printableAreas))) 
            {
                $designs = [];
                $getDesignParams = [];

                $resolution = '4500x5100';
                foreach ($printAreas as $area)
                {
                    $design = $this->getFulfillDesign($item['product_sku_id'], $resolution, $item['product_id'], null, $area);
                    $getDesignParams[] = [
                        'prams' => [$item['product_sku_id'], $resolution, $item['product_id'], null, $area],
                        'result' => $design
                    ];

                    if ($design) {
                        $designs[$area] = $design;
                    }
                }

                if (!count($designs) || count($designs) != count($printAreas)) {
                    throw new \Exception("Cannot find design, item id: " . $item['id'] . ' | ' . json_encode([$printAreas, $resolution]), 3);
                }

                foreach ($designs as $key => $artwork)
                {
                    $layoutKey = $item['id'] . '_' . $key;
        
                    $layouts[] = [
                        "artwork_token" => $layoutKey . "_art",
                        "mockup_token" => $layoutKey . "_mck",
                        "placement_token" => $layoutKey . "_plc",
                        "location" => $key
                    ];
    
                    $artworkTokens[] = [
                        "token" => $layoutKey . "_art",
                        "url" => $artwork->image_url
                    ];
    
                    $mockupTokens[] = [
                        "token" => $layoutKey . "_mck",
                        "url" => $item['image_url']
                    ];
    
                    $placementTokens[] = [
                        "token" => $layoutKey . "_plc",
                        "x_offset" => 0,
                        "y_offset" => 0
                    ];
                }

                $orderItemIds[] = $item['id'];
        
                $items[] = [
                    "sku" => $printSku->sku,
                    "quantity" => $item['quantity'],
                    "description" => $printSku->color . ' ' . $printSku->product_type . ' ' . $printSku->size . ' ' . $printSku->brand,
                    "layouts" => $layouts
                ];
            }
        }
    
        return [
            "items" => $items,
            "artworkTokens" => $artworkTokens,
            "mockupTokens" => $mockupTokens,
            "placementTokens" => $placementTokens,
            "orderItemIds" => $orderItemIds
        ];
    }

    protected function fulfill($order, $orderSchema)
    {
        list($shopId, $apiToken) = $this->getCredential();

        if ($shopId && $apiToken) {

            $response = $this->triggerSyncRequest($this->apiUrl . '/order/add', 'POST', $orderSchema, [
                'merch-key: ' . $this->credential[1],
                'Content-Type: application/json'
            ]);

            $this->logFulfill([
                'order_id' => $order['id'],
                'data' => $orderSchema
            ]);

            if ($response) {
                return [
                    'order_id' => $orderSchema['job_id'],
                    'data' => $orderSchema
                ];
            }
        }

        return false;
    }

    protected function logFulfill($logData)
    {
        DB::table('log')->insert([
            'actor_email' => 'system',
            'target_id' => $logData['order_id'],
            'target_type' => 'ORDER',
            'event_type' => 'PRINTLOGISTIC_AUTO_FULFILL',
            'data' => json_encode($logData['data']),
            'created_at' => date('Y-m-d H:i:s')
        ]);
    }

    public function getTemplate($input, $productId) {
        $categories = DB::table('product_n_category')
            ->select([
                'category.id', 'category.name',
                'category._lft', 'category._rgt'
            ])
            ->where('product_id', $productId)
            ->join('category', 'category.id', 'product_n_category.category_id')
            ->get();
        $categoriesName = [];
        foreach ($categories as $category) {
            $categoriesName[] = mb_strtolower($category->name);
        }
        return $this->getPrintLogisticSkuInfo($categoriesName, $input[3], $input[4], $input[1], $input[2]);
    }

    public function getPrintLogisticSkuInfo ($categoriesName, $type, $style, $color, $size) {
        $productInfo = [];
        $type = mb_strtolower($type);
        $style = mb_strtolower($style);
        $style = trim(mb_strtolower($style));
        if (in_array('hoodies', $categoriesName) && $type == 'unisex' && $style == 'premium hoodie') {
            $productInfo = [
                'product_type' => 'Hoodie',
                'style' => 'JH001'
            ];
        } else if (in_array('hoodies', $categoriesName) && in_array($type, ['youth', 'kids']) && $style == 'classic hoodie') {
            $productInfo = [
                'product_type' => 'Hoodie',
                'style' => '18500B'
            ];
        } else if (in_array('hoodies', $categoriesName) && $type == 'unisex' && $style == 'classic hoodie') {
            $productInfo = [
                'product_type' => 'Hoodie',
                'product_name' => 'Men Hoodie'
            ];
        } else if (in_array('hoodies', $categoriesName) && $type == 'unisex' && in_array($style, ['classic zip hoodie', 'zip hoodie'])) {
            $productInfo = [
                'product_type' => 'Hoodie',
                'product_name' => 'ZIP Hoodie'
            ];
        } else if (in_array('long sleeves', $categoriesName) && $type == 'unisex') {
            $productInfo = [
                'product_type' => 'Longsleeve',
                'product_name' => 'Longsleeve t-shirt'
            ];
        } else if (in_array('sweatshirts', $categoriesName) && $type == 'unisex' && $style == 'classic sweatshirt') {
            $productInfo = [
                'product_type' => 'Sweatshirt',
                'product_name' => 'Men Sweatshirt'
            ];
            if (strtolower($color) == 'black') {
                $productInfo['product_name'] = 'Standard Crew Neck Sweatshirt';
            }
        }  else if (in_array('sweatshirts', $categoriesName) && $type == 'unisex' && $style == 'premium sweatshirt') {
            $productInfo = [
                'product_type' => 'Sweatshirt',
                'product_name' => 'AWDIS Sweatshirt'
            ];
        } else if (in_array('sweatshirts', $categoriesName) && $type == 'kids' && $style == 'classic sweatshirt') {
            $productInfo = [
                'product_type' => 'Sweatshirt',
                'product_name' => 'Kids Sweatshirt'
            ];
        } else if (in_array('t-shirts', $categoriesName) && $type == 'men' && $style == 'heavyweight t-shirt') {
            $productInfo = [
                'product_type' => 'T-shirt',
                'style' => '5000'
            ];
        } else if (in_array('t-shirts', $categoriesName) && $type == 'kids' && $style == 'heavyweight t-shirt') {
            $productInfo = [
                'product_type' => 'T-shirt',
                'style' => '5000B'
            ];
        } else if (in_array('t-shirts', $categoriesName) && $type == 'men' && $style == 'classic t-shirt') {
            $productInfo = [
                'product_type' => 'T-shirt',
                'style' => '64000'
            ];
        } else if (in_array('t-shirts', $categoriesName) && in_array($type, ['unisex', 'women']) && $style == 'v-neck t-shirt') {
            $productInfo = [
                'product_type' => 'T-shirt',
                'style' => '3005'
            ];
        } else if (in_array('t-shirts', $categoriesName) && $type == 'unisex') {
            $productInfo = [
                'product_type' => 'T-shirt',
                'style' => '3200'
            ];
        } else if (in_array('t-shirts', $categoriesName) && $type == 'women' && $style == 'classic t-shirt') {
            $productInfo = [
                'product_type' => 'T-shirt',
                'style' => '5000L'
            ];
        } else if (in_array('tank tops', $categoriesName) && $type == 'unisex' && $style == 'premium tank') {
            $productInfo = [
                'product_type' => 'Tank Top',
                'style' => '3480'
            ];
        } else if (in_array('tank tops', $categoriesName) && $type == 'unisex' && $style == 'classic tank') {
            $productInfo = [
                'product_type' => 'Tank Top',
                'style' => '64200'
            ];
        }
        $locale = env('APP_LOCALE', 'us') ? env('APP_LOCALE', 'us') : 'us';
        if (in_array($locale, ['fr', 'de'])) {
            $productInfo = $this->getProductInfoByLocale($locale, $categoriesName, $type, $style);
        }
        $retVal = null;
        if ($productInfo) {
            if (in_array('t-shirts', $categoriesName) && $type == 'men' && $style == 'heavyweight t-shirt' && strtolower($color) == 'carolina blue') {
                $color = 'Car Blue';
            }
            $color = $this->getMapColors($color);
            if ($style == 'öko-t-shirt' && $locale == 'de') {
                $mapColor = [
                    "Sand" => "Desert Dust",
                    "Burgundy" => "Burgundy",
                    "Schwarz" => "Black",
                    "Anthrazit" => "Anthracite",
                    "Königsblau" => "Royal Blue",
                    "Plum" => "Plum",
                    "Rot" => "Red",
                    "Weiß" => "White",
                    "Sapphire Blue" => "Azur",
                    "Light Blue" => "Sky Blue",
                    "French Navy" => "French Navy",
                    "Sport Grey" => "Heather Grey",
                    "Military Green" => "Khaki",
                    "Opal" => "Opal",
                    "Bottle Green" => "Bottle Green",
                    "Dark Chocolate" => "Deep Chocolate",
                    "Irish Green" => "Fresh Green",
                    "Vintage Weiß" => "Vintage White",
                    "Light Pink" => "Cotton Pink",
                    "Daisy" => "Spectra Yellow",
                ];
                if (isset($mapColor[$color])) {
                    $color = $mapColor[$color];
                }
            }
            $colors = [$color];
            if (strtolower($color) == 'sport grey' || strtolower($color) == 'sport gray') {
                $colors = ['Sport Gray', 'Sport Grey'];
            }
            if (strtolower($color) == 'hether navy' || strtolower($color) == 'heather navy') {
                $colors = ['Hether Navy', 'Heather Navy'];
            }
            if (strtolower($color) == 'saphire' || strtolower($color) == 'saphire blue') {
                $colors = ['Saphire', 'Saphire Blue'];
            }
            if (strtolower($color) == 'bottle green' || strtolower($color) == 'forest green') {
                $colors = ['Bottle Green', 'Forest Green'];
            }

            $query = DB::table('print_logistic_sku')
                ->whereIn('color', $colors)
                ->where('size', '=', $size);
            foreach ($productInfo as $key => $value) {
                $query->where($key, '=', $value);
            }
            $retVal = $query->first();
        }
        return $retVal;
    }

    private function getMapColors ($color) {
        $retVal = $color;
        $locale = env('APP_LOCALE', 'us') ? env('APP_LOCALE', 'us') : 'us';
        $mapColors = Config::get("print-suppliers::print_logistic_sku.map_colors.$locale");
        if ($mapColors && isset($mapColors[$color]))  {
            $retVal = $mapColors[$color];
        }
        return $retVal;
    }


    private function getProductInfoByLocale ($locale, $categoriesName, $type, $style) {
        $productInfo = [];
        if ($locale == 'fr') {
            if ((in_array('sweats à capuche, hoodies', $categoriesName) || in_array('sweats à capuche, hoodies deux côtés', $categoriesName)) && $type == 'unisex' && $style == 'sweat à capuche premium') {
                $productInfo = [
                    'product_type' => 'Hoodie',
                    'style' => 'JH001'
                ];
            } else if ((in_array('sweats à capuche, hoodies', $categoriesName) || in_array('sweats à capuche, hoodies deux côtés', $categoriesName)) && $type == 'enfant' && $style == 'sweat à capuche classique') {
                $productInfo = [
                    'product_type' => 'Hoodie',
                    'style' => '18500B'
                ];
            } else if ((in_array('sweats à capuche, hoodies', $categoriesName) || in_array('sweats à capuche, hoodies deux côtés', $categoriesName)) && $type == 'unisex' && $style == 'sweat à capuche classique') {
                $productInfo = [
                    'product_type' => 'Hoodie',
                    'product_name' => 'Men Hoodie'
                ];
            } else if (in_array('sweats à capuche, hoodies zippé', $categoriesName) && $type == 'unisex') {
                $productInfo = [
                    'product_type' => 'Hoodie',
                    'product_name' => 'ZIP Hoodie'
                ];
            } else if ((in_array('sweatshirts', $categoriesName) || in_array('sweatshirts deux côtés', $categoriesName)) && $type == 'unisex' && $style == 'sweatshirt premium') {
                $productInfo = [
                    'product_type' => 'Sweatshirt',
                    'product_name' => 'AWDIS Sweatshirt'
                ];
            } else if ((in_array('sweatshirts', $categoriesName) || in_array('sweatshirts deux côtés', $categoriesName)) && $type == 'unisex' && $style == 'sweatshirt classique') {
                $productInfo = [
                    'product_type' => 'Sweatshirt',
                    'product_name' => 'Men Sweatshirt'
                ];
            } else if ((in_array('t-shirts', $categoriesName) || in_array('t-shirts deux côtés', $categoriesName)) && $type == 'hommes' && $style == 't-shirt épais') {
                $productInfo = [
                    'product_type' => 'T-shirt',
                    'style' => '5000'
                ];
            } else if ((in_array('t-shirts', $categoriesName) || in_array('t-shirts deux côtés', $categoriesName)) && $type == 'enfant' && $style == 't-shirt classique') {
                $productInfo = [
                    'product_type' => 'T-shirt',
                    'style' => '5000B'
                ];
            } else if ((in_array('t-shirts', $categoriesName) || in_array('t-shirts deux côtés', $categoriesName)) && $type == 'hommes' && $style == 't-shirt classique') {
                $productInfo = [
                    'product_type' => 'T-shirt',
                    'style' => '64000'
                ];
            } else if ((in_array('t-shirts', $categoriesName) || in_array('t-shirts deux côtés', $categoriesName)) && in_array($type, ['hommes', 'femmes']) && $style == 't-shirt premium à col en v unisexe') {
                $productInfo = [
                    'product_type' => 'T-shirt',
                    'style' => '3005'
                ];
            } else if ((in_array('t-shirts', $categoriesName) || in_array('t-shirts deux côtés', $categoriesName)) && in_array($type, ['femmes']) && $style == 't-shirt classique') {
                $productInfo = [
                    'product_type' => 'T-shirt',
                    'style' => '5000L'
                ];
            } else if (in_array('Débardeurs', $categoriesName) && in_array($type, ['unisex'])) {
                $productInfo = [
                    'product_type' => 'Tank Top',
                    'style' => '64200'
                ];
            }
        } else if ($locale == 'de') {
            if ((in_array('hoodies', $categoriesName) || in_array('zweiseitige hoodies', $categoriesName)) && $type == 'unisex' && $style == 'premium hoodie') {
                $productInfo = [
                    'product_type' => 'Hoodie',
                    'style' => 'JH001'
                ];
            } else if ((in_array('hoodies', $categoriesName) || in_array('zweiseitige hoodies', $categoriesName)) && $type == 'kinder' && $style == 'classic hoodie') {
                $productInfo = [
                    'product_type' => 'Hoodie',
                    'style' => '18500B'
                ];
            } else if ((in_array('hoodies', $categoriesName) || in_array('zweiseitige hoodies', $categoriesName)) && $type == 'unisex' && $style == 'classic hoodie') {
                $productInfo = [
                    'product_type' => 'Hoodie',
                    'style' => '18500'
                ];
            } else if (in_array('kapuzenjacke', $categoriesName) && $type == 'unisex') {
                $productInfo = [
                    'product_type' => 'Hoodie',
                    'product_name' => 'ZIP Hoodie'
                ];
            } else if ((in_array('pullover', $categoriesName) || in_array('zweiseitige pullovers', $categoriesName)) && $type == 'unisex' && $style == 'premium pullover ') {
                $productInfo = [
                    'product_type' => 'Sweatshirt',
                    'product_name' => 'AWDIS Sweatshirt'
                ];
            } else if ((in_array('pullover', $categoriesName) || in_array('zweiseitige pullovers', $categoriesName)) && $type == 'unisex' && $style == 'classic pullover') {
                $productInfo = [
                    'product_type' => 'Sweatshirt',
                    'product_name' => 'Men Sweatshirt'
                ];
            } else if ((in_array('t-shirts', $categoriesName) || in_array('zweiseitige t-shirts', $categoriesName)) && $type == 'herren' && $style == 'schweres t-shirt') {
                $productInfo = [
                    'product_type' => 'T-shirt',
                    'style' => '5000'
                ];
            } else if ((in_array('t-shirts', $categoriesName) || in_array('zweiseitige t-shirts', $categoriesName)) && $type == 'kinder' && $style == 'classic t-shirt') {
                $productInfo = [
                    'product_type' => 'T-shirt',
                    'style' => '5000B'
                ];
            } else if ((in_array('t-shirts', $categoriesName) || in_array('zweiseitige t-shirts', $categoriesName)) && $type == 'herren' && $style == 'classic t-shirt') {
                $productInfo = [
                    'product_type' => 'T-shirt',
                    'style' => '64000'
                ];
            } else if ((in_array('t-shirts', $categoriesName) || in_array('zweiseitige t-shirts', $categoriesName)) && in_array($type, ['herren', 'damen']) && $style == 'v-auschnitt t-shirt') {
                $productInfo = [
                    'product_type' => 'T-shirt',
                    'style' => '3005'
                ];
            } else if ((in_array('t-shirts', $categoriesName) || in_array('zweiseitige t-shirts', $categoriesName)) && in_array($type, ['damen']) && $style == 'classic t-shirt') {
                $productInfo = [
                    'product_type' => 'T-shirt',
                    'style' => '5000L'
                ];
            } else if (in_array('tank tops', $categoriesName) && in_array($type, ['unisex'])) {
                $productInfo = [
                    'product_type' => 'Tank Top',
                    'style' => '64200'
                ];
            }
        }

        return $productInfo;
    }

    /**
     * [getTemplateInput Lay ra cac input de lay ra template]
     * @param  [int] $productSkuId               [ma bien the]
     * @return [array] $retval                   [$category_id, $color, $size, $type, $style]
     */
    public function getTemplateInput($productSkuId) {
        return $this->getFulfillSkuAttrs($productSkuId);
    }
}
