<?php

namespace Modules\PrintSuppliers\Controllers;

use Illuminate\Http\Request;
use DB;

class GelatoTemplate extends Controller
{

    public function template (Request $request) {

        $validator = \Validator::make($request->all(), [
            'category_id' => 'required',
            'color' => 'required',
            'size' => 'required',
            // 'type' => 'required',
            // 'style' => 'required',
            'position' => 'required',
        ]);

        if ($validator->fails())
        {
            return $validator->messages();
        }

        $input = [
            $request->input('category_id'),
            $request->input('color'),
            $request->input('size'),
            $request->input('type'),
            $request->input('style'),
            $request->input('position'),
        ];

        $template = $this->getTemplate($input);
        if ($template) {
            return [
                'status' => 'success',
                'template' => $template
            ];
        } else {
            return [
                'status' => 'fail'
            ];
        }
    }

    public function index () {
        $this->offset = 0;
        $this->limit = 200;
        return $this->getNextPage();
    }

    public function getNextPage () {
        \Log::info($this->offset);
        $url = "https://product.gelatoapis.com/v3/catalogs/apparel/products:search";
        $body = json_encode([
            'limit' => $this->limit,
            'offset' => $this->offset,
        ]);
        $response =  $this->sendRequest("https://product.gelatoapis.com/v3/catalogs/apparel/products:search", $body);
        if (count($response->products)) {
            foreach ($response->products as $key => $product) {
                if (count(DB::table('print_suppliers_geleto_products')->where('productUid', $product->productUid)->get())) {
                    DB::table('print_suppliers_geleto_products')
                        ->where('productUid', $product->productUid)
                        ->update([
                        'productUid' => $product->productUid,
                        'GarmentCategory' => $product->attributes->GarmentCategory,
                        'GarmentColor' => $product->attributes->GarmentColor,
                        'GarmentCut' => $product->attributes->GarmentCut,
                        'GarmentPrint' => $product->attributes->GarmentPrint,
                        'GarmentQuality' => $product->attributes->GarmentQuality,
                        'GarmentSize' => $product->attributes->GarmentSize,
                        'GarmentSubcategory' => $product->attributes->GarmentSubcategory,
                        'ProductStatus' => $product->attributes->ProductStatus,
                        'State' => $product->attributes->State,
                    ]);
                } else {
                    DB::table('print_suppliers_geleto_products')->insert([
                        'productUid' => $product->productUid,
                        'GarmentCategory' => $product->attributes->GarmentCategory,
                        'GarmentColor' => $product->attributes->GarmentColor,
                        'GarmentCut' => $product->attributes->GarmentCut,
                        'GarmentPrint' => $product->attributes->GarmentPrint,
                        'GarmentQuality' => $product->attributes->GarmentQuality,
                        'GarmentSize' => $product->attributes->GarmentSize,
                        'GarmentSubcategory' => $product->attributes->GarmentSubcategory,
                        'ProductStatus' => $product->attributes->ProductStatus,
                        'State' => $product->attributes->State,
                    ]);
                }

            }


            $this->offset = $this->offset + $this->limit;
            $this->getNextPage();
        }
        // return response()->json($response->products[0]);
    }


    public function getTemplate ($input) {
        $this->category_id = $input[0];
        $this->color = $input[1];
        $this->size = $this->parseSize($input[2]);
        $this->type = $input[3];
        $this->style = $input[4];
        $position = $input[5] == 'back' ? 'back' : 'front';
        $this->printArea = ($input[5] == 'back') ? '0-4' : '4-0';
        $this->GarmentCut = null;
        $this->GarmentQuality = ['prm', 'classic', 'triblend', 'heavy-weight'];
        if(in_array($this->type, [
            'Unisex', 'Unisexxo',
            'Men', 'Herren', 'Hommes', 'Uomini', 'Hombre', 'Homem'
        ])) $this->GarmentCut = 'unisex';
        if (in_array($this->type, [
            'Donne', 'Damen', 'Femmes', 'Women', 'Mujer', 'Mulher'
        ]))  $this->GarmentCut = 'womens';
        if (in_array($this->type, [
            'Kinder', 'Kids', 'Youth', 'Jeunes', 'Niño', 'Criança'
        ]))  $this->GarmentCut = 'kids';
        if (!$this->GarmentCut) return;

        $this->resolution = '3600x4800';
        switch ($this->category_id) {
            case 7:
                $this->GarmentCategory = 't-shirt';
                $this->GarmentSubcategory = 'crewneck';
                break;
            case 33:
                $this->GarmentCategory = 't-shirt';
                $this->GarmentSubcategory = 'crewneck';
                break;
            case 8:
                if ($this->printArea == '4-0') {
                    $this->resolution = '3600x3600';
                }
                $this->GarmentCategory = 'hoodie';
                $this->GarmentSubcategory = 'pullover';
                break;
            case 54:
                $this->GarmentCategory = 'sweatshirt';
                $this->GarmentSubcategory = 'crewneck';
                break;
            case 63:
                $this->GarmentCategory = 't-shirt';
                $this->GarmentSubcategory = 'longsleeve-crew';
                break;
            case 35:
                $this->GarmentCategory = 't-shirt';
                $this->GarmentSubcategory = 'longsleeve-crew';
                break;
            case 75:
                if ($this->printArea == '4-0') {
                    $this->resolution = '3600x3600';
                }
                $this->GarmentCategory = 'hoodie';
                $this->GarmentSubcategory = 'zip';
                break;
            case 48:
                $this->resolution = '3000x3600';
                $this->GarmentCategory = 't-shirt';
                $this->GarmentSubcategory = 'tank-top';
                break;
            case 65:
                $this->GarmentCategory = 't-shirt';
                $this->GarmentSubcategory = 'longsleeve-crew';
                break;

            default:
                $this->GarmentCategory = 'Unknown GarmentCategory';
                $this->GarmentSubcategory = 'Unknown GarmentSubcategory';
                break;
        }

        if ($this->GarmentCategory == 't-shirt' && $this->GarmentCut == 'womens') {
            $this->resolution = '3000x3600';
        }

        $this->queryColor = $this->parseColor($input[1]);

        if ($this->style == 'T-shirt premium à col en V unisexe') {
            $this->GarmentCategory = 't-shirt';
            $this->GarmentSubcategory = 'v-neck';
            $this->GarmentQuality = ['prm'];
        }

        if ($this->style == 'V-neck T-shirt') {
            $this->GarmentCategory = 't-shirt';
            $this->GarmentSubcategory = 'v-neck';
        }

        if ($this->style == 'Heavyweight T-shirt') {
            $this->GarmentQuality = ['heavy-weight', 'prm'];
        }

        if ($this->style == 'Heavyweight T-shirt' && $this->GarmentCut == 'kids') {
            $this->GarmentQuality = ['heavy-weight', 'classic'];
        }

        $query = DB::table('print_suppliers_gelato_products')
            ->where('GarmentSize', $this->size)
            ->where('GarmentColor', $this->queryColor)
            ->where('GarmentPrint', $this->printArea)
            ->where('GarmentSubcategory', $this->GarmentSubcategory)
            ->where('GarmentCategory', $this->GarmentCategory)
            ->where('GarmentCut', $this->GarmentCut)
            ->whereIn('GarmentQuality', $this->GarmentQuality)
            ->where('State', 'published')
            ->where('ProductStatus', 'activated')
            ->orderBy('GarmentQuality');

        $variant = $query->first();

        if ($variant) {
            return [
                $variant->productUid,
                $variant->$position ? $variant->$position : $this->resolution

            ];
        }

    }

    public function parseSize ($size) {
        switch ($size) {

            case 'Large':
                $size = 'L';
                break;
            case 'Unisex Large':
                $size = 'L';
                break;
            case 'Unisex 2XL':
                $size = '2XL';
                break;
            case 'Unisex XL':
                $size = 'XL';
                break;
            case 'Unisex Medium':
                $size = 'M';
                break;
            case 'Unisex Small':
                $size = 'S';
                break;
            case 'Medium':
                $size = 'M';
                break;
            case 'Small':
                $size = 'S';
                break;
            case 'XXL':
                $size = '2XL';
                break;
            case 'Newborn':
                $size = '6m';
                $this->GarmentCut = 'baby';
                break;

            default:
                $size = $size;
                break;
        }
        return $size;
    }




    public function parseColor($color) {
        // $color = str_slug($color);
        $retval = 'Unknown color';
        switch ($color) {
            case 'Schwarz':
                $retval = 'black';
                break;
            case 'Königsblau':
                $retval = 'royal';
                break;
            case 'Militärgrün':
                $retval = 'military-green';
                break;
            case 'Marineblau':
                $retval = 'navy';
                break;
            case 'Weiß':
                $retval = 'white';
                break;
            case 'Sport Grau':
                $retval = 'sports-grey';
                break;
            case 'Grey':
                $retval = 'sports-grey';
                break;
            case 'Dark Heather':
                $retval = 'dark-heather';
                break;
            case 'Türkis':
                $retval = 'turquoise';
                break;
            case 'Rot':
                $retval = 'red';
                break;
            case 'Anthrazit Meliert':
                $retval = 'dark-heather';
                break;
            case 'Hell Pink':
                $retval = 'light-pink';
                break;
            case 'Natürlich':
                $retval = 'natural';
                break;
            case 'Irisch Grün':
                $retval = 'irish-green';
                break;
            case 'Gris Sport':
                $retval = 'sports-grey';
                break;
            case 'Gris':
                $retval = 'charcoal';
                break;
            case 'Rouge':
                $retval = 'red';
                break;
            case 'Noir':
                $retval = 'black';
                break;
            case 'Bleu Marine':
                $retval = 'navy';
                break;
            case 'Marron':
                $retval = 'dark-chocolate';
                break;
            case 'Brown':
                $retval = 'dark-chocolate';
                break;
            case 'Vert Militaire':
                $retval = 'military-green';
                break;
            case 'Naturel':
                $retval = 'natural';
                break;
            case 'Blanc':
                $retval = 'white';
                break;
            case 'Noir Chiné Triblend ':
                $retval = 'triblend-black-heather';
                break;
            case 'Bleu Marine Triblend':
                $retval = 'triblend-navy';
                break;
            case 'Royal blue':
                $retval = 'royal';
                break;
            case 'Olive':
                $retval = 'military-green';
                break;
            case 'Triblend Cardinal Red':
                $retval = 'triblend-red';
                break;
            case 'Bleu Royal':
                $retval = 'royal';
                break;
            case 'Asphalte':
                $retval = 'asphalt';
                break;
            case 'Gris Athlétique Triblend':
                $retval = 'triblend-athletic-gray';
                break;
            case 'Military green':
                $retval = 'military-green';
                break;
            case 'Baby Blue':
                $retval = 'light-blue';
                break;
            case 'Sport grey':
                $retval = 'sports-grey';
                if ($this->type == 'Youth') {
                    // if ($this->style == 'Heavyweight T-shirt') {
                        $retval = 'heather-gray';
                    // }
                }
                break;
            case 'Blue Navy':
                $retval = 'navy';
                break;
            case 'Heather Grey':
                $retval = 'sports-grey';
                if ($this->type == 'Youth') {
                    // if ($this->style == 'Heavyweight T-shirt') {
                        $retval = 'heather-gray';
                    // }
                }
                break;

            case 'Pink':
                $retval = 'pink';
                $this->GarmentQuality[] = 'organic';
                break;
            case 'Dark Heather Grey':
                $retval = 'dark-heather';
                break;
            case 'Heather Blue':
                $retval = 'blue';
                break;
            case 'Blue sky':
                $retval = 'light-blue';
                break;
            case 'Military Grey':
                $retval = 'heather-gray';
                break;


            default:
                $retval = $color;
                break;
        }
        return $retval;
    }

    public function sendRequest ($url, $body = '') {
        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => $url,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => $body,
          CURLOPT_HTTPHEADER => array(
            'X-API-KEY: e9d5c1d3-d77b-4c2f-938a-edea0b9573f2-698611a6-66c3-4bd5-bfd4-f91b436c38c3:6d36fec9-26a5-40b9-aaea-ee6bc9cbbffb',
            'Content-Type: application/json'
          ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        return json_decode($response);
    }
}
