<?php

namespace Modules\PrintSuppliers\Controllers;

use Illuminate\Http\Request;
use Modules\PrintSuppliers\Models\PrintProvider;
use Modules\PrintSuppliers\Models\Blueprint;
use Illuminate\Support\Facades\DB;

class PrintifyTemplate extends Controller
{

    public function blueprints()
    {

        // return;

        // $response = $this->sendRequest("https://api.printify.com/v1/catalog/blueprints.json");
        // foreach ($response as $key => $value) {
        //     $blueprintId = $value['id'];
        //     $this->blueprint($blueprintId);
        // }
        set_time_limit(0);
        // $this->blueprint(6);
        $this->blueprint(36);
        // $this->blueprint(139);
    }

    public function blueprint($blueprintId)
    {
        $time = date('Y-m-d H:i:s', strtotime('-1 minute'));
        $response = $this->sendRequest("https://api.printify.com/v1/catalog/blueprints/$blueprintId/print_providers.json");
        foreach ($response as $key => $value) {
            $printProviderId = $value['id'];
            $this->fetchPrintProviderVariant($printProviderId, $blueprintId);
        }
        
        $response = $this->sendRequest("https://printify.com/product-catalog-service/api/v1/blueprints/$blueprintId");
        foreach($response['printProviders'] as $printProvider) {
            $printProviderId = $printProvider['id'];
            foreach ($printProvider['variants'] as $variant) {
                $variantId = $variant['id'];
                DB::table('print_suppliers_variant')->where([
                    'blueprint_id' => $blueprintId,
                    'print_provider_id' => $printProviderId,
                    'variant_id' => $variantId,
                ])->update([
                    'cost' => $variant['costs'][0]['resultSubscription']
                ]);
            }
        }
        DB::table('print_suppliers_variant')->where([
            'blueprint_id' => $blueprintId,
        ])->whereNull('cost')->delete();
        DB::table('print_suppliers_variant')->where([
            'blueprint_id' => $blueprintId,
        ])->where('updated_at', '<', $time)->delete();
        echo $time;die;
 

    }

    public function print_providers()
    {
        $response = $this->sendRequest("https://api.printify.com/v1/catalog/print_providers.json");
        foreach ($response as $key => $value) {
            $printProviderId = $value['id'];
            $this->index($printProviderId);
        }
    }

    public function shipping($blueprintId, $printProviderId)
    {
        \Log::info("autoff: shipping $blueprintId, $printProviderId");
        $response = $this->sendRequest("https://api.printify.com/v1/catalog/blueprints/$blueprintId/print_providers/$printProviderId/shipping.json");
        if (!isset($response['profiles'])) return;
        foreach ($response['profiles'] as $profile) {
            if (in_array("US", $profile['countries'])) {
                $first_item = $profile['first_item']['cost'];
                $additional_items = $profile['additional_items']['cost'];
                $row = DB::table('print_suppliers_printify_shipping')->where([
                    'blueprint' => $blueprintId,
                    'print_provider' => $printProviderId
                ])->first();

                if (!$row) {
                    DB::table('print_suppliers_printify_shipping')->insert([
                        'blueprint' => $blueprintId,
                        'print_provider' => $printProviderId,
                        'first_item' => $first_item,
                        'additional_items' => $additional_items
                    ]);
                } else {
                    DB::table('print_suppliers_printify_shipping')->where([
                        'blueprint' => $blueprintId,
                        'print_provider' => $printProviderId
                    ])->update([
                        'first_item' => $first_item,
                        'additional_items' => $additional_items
                    ]);
                }
                return $profile;
            }
        }
        return;
    }

    public function index($printProviderId)
    {
        // dd($printProviderId);
        \Log::info("autoff: Starting get print provider " .  $printProviderId);
        $printProvider = $this->fetchPrintProvider($printProviderId);
        \Log::info("autoff: DONE get print provider  " .  $printProviderId);
        return $printProvider;
    }

    public function printProvidersWithVariants($printProviderId)
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        \Log::info("autoff: Starting get print provider with variants " .  $printProviderId);
        $printProvider = $this->fetchPrintProvider($printProviderId, true);
        \Log::info("autoff: DONE get print provider with variants " .  $printProviderId);
        return $printProvider;
    }

    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();
        }



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

    public function fetchPrintProvider($printProviderId, $getVariants = false)
    {
        $printProvider = PrintProvider::firstOrNew(['id' => $printProviderId]);
        $token = config('print-suppliers::token.printify');
        $response = $this->sendRequest("https://api.printify.com/v1/catalog/print_providers/$printProviderId.json", $token);
        $printProvider->update($response);
        $printProvider->save();
        foreach ($response['blueprints'] as $key => $value) {

            $blueprint = Blueprint::firstOrNew(['id' => $value['id']]);
            $blueprint->fill($value);
            $blueprint->save();
            if ($getVariants) {
                $this->fetchPrintProviderVariant($printProviderId, $value['id']);
            }
        }

        return $printProvider;
    }

    public function fetchPrintProviderVariant($printProviderId, $blueprintId)
    {
        $this->shipping($blueprintId, $printProviderId);
        \Log::info("autoff: printProviderId $printProviderId, blueprintId $blueprintId");
        $response = $this->sendRequest("https://api.printify.com/v1/catalog/blueprints/$blueprintId/print_providers/$printProviderId/variants.json");
        $variants  = [];
        if ($response && isset($response['variants'])) {
            foreach ($response['variants'] as $variant) {
                $variantId = $variant['id'];
                $variants[$variantId] = $variant;
            }
        }



        $token = config('print-suppliers::token.printify');
        $response = $this->sendRequest("https://printify.com/api/v1/blueprints/$blueprintId/$printProviderId", $token);

        if ($response && isset($response['print_provider']) && isset($response['print_provider']['variants'])) {
            foreach ($response['print_provider']['variants'] as $variant) {
                $variantId = $variant['id'];
                $variants[$variantId]['status'] = $variant['status'] && $variant['status'] ? $variant['status'] : 'out-of-stock';
                $variants[$variantId]['costs'] = $variant['costs'];
                 $costArrray = $variant['costs'][0];
                // dd($costArrray);
                 $variants[$variantId]['cost'] = $costArrray['result'];
            }
        } else {
            return;
        }

        foreach ($variants as $key => $variant) {
            if (!isset($variant['id'])) {
                continue;
            }

            if (isset($variant['options']['color'])) {
                $color = $variant['options']['color'];
            } else {
                $color = "";
            }

            if (isset($variant['options']['size'])) {
                $size = $variant['options']['size'];
            } else {
                $size = "";
            }

            $row = DB::table('print_suppliers_variant')->where([
                'blueprint_id' => $blueprintId,
                'variant_id' => $variant['id'],
                'print_provider_id' => $printProviderId,
            ])->first();
            if (!$row) {
                DB::table('print_suppliers_variant')->insert([
                    'variant_id' => $variant['id'],
                    'blueprint_id' => $blueprintId,
                    'print_provider_id' => $printProviderId,
                    'color' => $color,
                    'size' => $size,
                    'status' => $variant['status'],
                    'costs' => json_encode($variant['costs']),
                    'cost' => $variant['cost'],
                    'placeholders' => json_encode($variant['placeholders']),
                    'update' => true,
                    'created_at' => date('Y-m-d H:i:s', time()),
                    'updated_at' => date('Y-m-d H:i:s', time()),
                ]);
            } else {
                $item = DB::table('print_suppliers_variant')->where([
                    'blueprint_id' => $blueprintId,
                    'variant_id' => $variant['id'],
                    'print_provider_id' => $printProviderId,
                ])->first();
                $item = (array) $item;
                $fields = ['color', 'size', 'status', 'costs', 'cost', 'placeholders', 'update'];
                $updateData = [
                    'color' => $color,
                    'size' => $size,
                    'status' => $variant['status'],
                    'costs' => json_encode($variant['costs']),
                    'cost' => $variant['cost'],
                    'placeholders' => json_encode($variant['placeholders']),
                    'update' => true,
                    'updated_at' => date('Y-m-d H:i:s', time()),
                ];
                $isUpdate = true;
                // foreach ($fields as $field) {
                //     if ($item[$field] != $updateData[$field]) {
                //         $isUpdate = true;
                //     }
                // }
                if ($isUpdate) {
                    DB::table('print_suppliers_variant')->where([
                        'blueprint_id' => $blueprintId,
                        'variant_id' => $variant['id'],
                        'print_provider_id' => $printProviderId,
                    ])->update($updateData);
                }
            }


            // die;
        }


        DB::table('print_suppliers_variant')->where([
            'blueprint_id' => $blueprintId,
            'print_provider_id' => $printProviderId,
            'update' => false
        ])->delete();
        DB::table('print_suppliers_variant')->where([
            'blueprint_id' => $blueprintId,
            'print_provider_id' => $printProviderId,
        ])->update([
            'update' => false,
            'updated_at' => date('Y-m-d H:i:s', time()),
        ]);
    }


    public function getTemplate($input)
    {


        $retval = [
            null, null, null, null
        ];
        $this->blueprint_id = null;
        $print_provider_id = null;
        $variant_id = null;
        $this->category_id = $input[0];
        $this->color = $input[1];
        $this->queryColor = $this->parseColor($input[1]);
        $this->size = $this->parseSize($input[2]);
        $this->type = $input[3];
        $this->style = $input[4];
        $this->position = $input[5];
        $this->blueprint_id = $this->getBluePrint();
        $this->addTriBlendColor();
        $variant = null;

        // 29 Monster
        // 61 Dimona Tee
        // 45 Awkward
        // 3 Dream Junction
        // 39 Swift pod
        // 16 MyLocker
        // 52 Stakes Manufacturing

        $providerIds = [29, 61, 45, 3, 39, 16, 52];
        if (in_array($this->size, ['2XL', '3XL', '4XL', '5XL'])) {
            switch ($this->style) {
                case 'Classic T-shirt':
                    $providerIds = [39, 29, 61, 45, 3, 39, 16, 52];
                    break;
                case 'Heavyweight T-shirt':
                    $providerIds = [43, 39, 29, 61, 45, 3, 39, 16, 52];
                    break;
                default:
                    $providerIds = [29, 61, 45, 3, 39, 16, 52];
                    break;
            }
        }

        foreach ($providerIds as  $print_provider_id) {
            if ($this->blueprint_id == 157 && $print_provider_id == 29) {
                continue;
            }
            if (!$variant) {
                $row = DB::table('print_suppliers_variant')->first();
                $query = DB::table('print_suppliers_variant')
                    ->where('size', $this->size)
                    ->whereIn('color', $this->queryColor)
                    ->where('blueprint_id', $this->blueprint_id)
                    ->where('print_provider_id', $print_provider_id);
                if (isset($row->status)) {
                    $query->where('status', 'in-stock');
                }
                $variant = $query->first();
            }
        }

        $resolution = null;

        if ($variant) {
            $variant_id = $variant->variant_id;
            $print_provider_id = $variant->print_provider_id;
            $placeholders = json_decode($variant->placeholders);
            $resolution = $placeholders[0]->width . 'x' . $placeholders[0]->height;
            foreach ($placeholders as $key => $placeholder) {
                if ($this->position == $placeholder->position) {
                    $resolution = $placeholder->width . 'x' . $placeholder->height;
                }
            }
        } else {
            $print_provider_id = null;
        }

        return [
            "$this->blueprint_id",
            "$print_provider_id",
            "$variant_id",
            "$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;

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

    public function getBluePrintByStyle()
    {
        switch ($this->type) {
            case 'Women':
                if ($this->style == 'V-neck T-shirt') {
                    $this->blueprint_id = 48;
                }
                if ($this->style == 'Ringer T-shirt') {
                    $this->blueprint_id = 412;
                }
                if ($this->style == 'Crewneck Sweatshirt') {
                    $this->blueprint_id = 49;
                }
                if ($this->style == 'Premium Sweatshirt') {
                    $this->blueprint_id = 446;
                }
                if ($this->style == 'Premium Hoodie') {
                    $this->blueprint_id = 439;
                }
                if ($this->style == 'Tri-blend T-shirt') {
                    $this->blueprint_id = 460;
                }
                if ($this->style == 'Tri-Blend T-Shirt (Extra Soft)') {
                    $this->blueprint_id = 460;
                }
                if ($this->style == 'Classic Hoodie') {
                    $this->blueprint_id = 77;
                }
                if ($this->style == 'Classic Long Sleeves') {
                    $this->blueprint_id = 80;
                }
                if ($this->style == 'Premium Long Sleeves') {
                    $this->blueprint_id = 41;
                }
                if ($this->style == 'Classic RacerBack') {
                    $this->blueprint_id = 18;
                }
                if ($this->style == 'Tri-Blend Racerback (Extra Soft)') {
                    $this->blueprint_id = 141;
                }
                break;
            case 'Men':
            case 'Unisex':

                if ($this->style == 'Heavyweight T-shirt') {
                    $this->blueprint_id = 6;
                }
                if ($this->style == 'V-neck T-shirt') {
                    $this->blueprint_id = 48;
                }
                if ($this->style == 'Ringer T-shirt') {
                    $this->blueprint_id = 412;
                }
                if ($this->style == 'Classic T-shirt') {
                    $this->blueprint_id = 36;
                }
                if ($this->style == 'Tri-blend T-shirt') {
                    $this->blueprint_id = 139;
                }
                if ($this->style == 'Tri-Blend T-Shirt (Extra Soft)') {
                    $this->blueprint_id = 139;
                }
                if ($this->style == 'Crewneck Sweatshirt') {
                    $this->blueprint_id = 49;
                }
                if ($this->style == 'Premium Sweatshirt') {
                    $this->blueprint_id = 446;
                }
                if ($this->style == 'Premium Hoodie') {
                    $this->blueprint_id = 439;
                }
                if ($this->style == 'Classic Hoodie') {
                    $this->blueprint_id = 77;
                }
                if ($this->style == 'Classic Long Sleeves') {
                    $this->blueprint_id = 80;
                }
                if ($this->style == 'Premium Long Sleeves') {
                    $this->blueprint_id = 41;
                }
                if ($this->style == 'Classic Tank') {
                    $this->blueprint_id = 39;
                }
                if ($this->style == 'Premium Tank') {
                    $this->blueprint_id = 313;
                }
                if ($this->style == 'Hoodie') {
                    $this->blueprint_id = 77;
                }
                break;
            case 'Youth':

                break;
            case 'Kids':
                if ($this->style == 'Kids Softstyle Tee') {
                    $this->blueprint_id = 81;
                }
                if ($this->style == 'Kids Long Sleeve') {
                    $this->blueprint_id = 586;
                }
                if ($this->style == 'Kids Pullover Hoodie') {
                    $this->blueprint_id = 603;
                }
                if ($this->style == 'Baby Onesie') {
                    $this->blueprint_id = 33;
                }
                break;
            default:

                break;
        }
    }

    public function addTriBlendColor()
    {

        if (in_array($this->blueprint_id, [139, 460])) {
            $this->queryColor[] = 'Tri-Blend ' . $this->color;
            $this->queryColor[] = 'Tri-Blend Vintage ' . $this->color;
            $this->queryColor[] = 'Tri-Blend Heather ' . $this->color;
            if (strpos($this->color, 'Vintage') !== false) {
                $this->queryColor[] = str_replace('Vintage ', '', $this->color);
            }
            if (strpos($this->color, ' Heather') !== false) {
                $this->queryColor[] = str_replace(' Heather', '', $this->color);
            }
        }
    }

    public function getBluePrint()
    {
        switch ($this->category_id) {
            case 8:
                $this->blueprint_id = 77;
                break;
            case 54:
                $this->blueprint_id = 49;
                break;
            case 151:
                $this->blueprint_id = 66;
                break;
            case 181:
                $this->blueprint_id = 66;
                break;
            case 48:
                $this->blueprint_id = 39;
                if ($this->type == 'Women') {
                    $this->blueprint_id = 18;
                }
                break;
            case 68:
                $this->blueprint_id = 80;
                break;
            case 180:
                $this->blueprint_id = 77;
                break;
            case 59:
                $this->blueprint_id = 147;
                if ($this->type == 'Women') {
                    $this->blueprint_id = 5;
                }
                break;
            case 74:
                $this->blueprint_id = 33;
                break;
            case 164:
                $this->blueprint_id = 603;
                break;
            default:
                break;
        }
        $this->getBluePrintByStyle();
        return $this->blueprint_id;
    }

    public function parseColor($color)
    {
        $retval = [$color];
        switch ($color) {
            case 'Royal blue':
            case 'Royal':
            case 'Royal Heather':
                $retval[] = 'Royal';
                $retval[] = 'Tri-Blend Vintage Royal';
                break;
            case 'Vintage Royal':
                $retval[] = 'Tri-Blend Vintage Royal';
                break;
            case 'Dark Heather':
                $retval[] = 'Dark Grey Heather';
            case 'Premium Heather':
                $retval[] = 'Tri-Blend Premium Heather';
                break;
            case 'Navy':
                $retval[] = 'Solid Midnight Navy';
                break;
            case 'Vintage Navy':
                $retval[] = 'Tri-Blend Vintage Navy';
                break;
            case 'Black':
                $retval[] = 'Solid Black';
                break;
            case 'WHITE':
                $retval[] = 'Solid White';
                break;
            case 'Baby Blue':
                $retval[] = 'Light Blue';
                break;
            case 'Heather Grey':
            case 'Gray':
            case 'Lightgray':
            case 'Grey':
                $retval[] = 'Sport Grey';
                $retval[] = 'Heather';
                break;
            case 'Vintage Red':
                $retval[] = 'Tri-Blend Vintage Red';
                break;
            case 'Vintage Green':
                $retval[] = 'Irish Green';
                $retval[] = 'Tri-Blend Envy';
                break;
            case 'Vintage Black':
                $retval[] = 'Tri-Blend Vintage Black';
                break;
            case 'Detroit Lions - Charcoal':
            case 'Charcoal Heather':
            case 'Coal':
            case 'Heavygray':
            case 'Asphalt':
                $retval[] = 'Charcoal';
                break;
            case 'Sport grey':
                $retval[] = 'Heather Grey';
                break;
            case 'Black T-shirt':
            case 'Black Unisex T-shirt':
            case 'Tee - Black':
                $retval[] = 'Black';
                break;
            case 'Navy Blue':
            case 'Blue Navy':
            case 'Navy Heather':
                $retval[] = 'Navy';
                break;
            case 'Athletic Heather':
                $retval[] = 'Tri-Blend Premium Heather';
                break;
            case 'Heather White':
            case 'Vintage White':
                $retval[] = 'Tri-Blend Heather White';
                $retval[] = 'White';
                break;
            case 'Armygreen':
                $retval[] = 'Military Green';
                break;
            case 'Light Pink':
                $retval[] = 'Solid Light Pink';
                break;
            case 'Heather':
                $retval[] = 'Sport Grey';
                $retval[] = 'Tri-Blend Premium Heather';
                break;
            case 'Red Heather':
                $retval[] = 'Tri-Blend Vintage Red';
                break;
            case 'Navy Heather':
                $retval[] = 'Tri-Blend Vintage Navy';
                break;
            default:
                break;
        }
        return $retval;
    }

    public function sendRequest($url, $token = null)
    {

        $apiToken = $this->getCredential()[1];

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer ' .  $apiToken
            ),
        ));

        $response = curl_exec($curl);

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