<?php

namespace Modules\PrintSuppliers\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Modules\PrintSuppliers\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;


class SupplierController extends Controller
{
    
    public function supplierIndexFactory(Request $request, $supplierSlug, $action = null)
    {
        $routeParameters = Route::current()->parameters();

        $supplierSlug = $routeParameters['supplier_slug'];
        $action = (isset($routeParameters['action'])) ? $routeParameters['action'] : null;

        if ($action) {
            $controller = 'Modules\\PrintSuppliers\\Controllers\\' . ucwords($supplierSlug) . 'Controller';
            $action = preg_replace('/-/', ' ', $action);
            $action = lcfirst(preg_replace('/ /', '', ucwords($action)));

            return App::call($controller . '@' . $action);
            
        } else {
            $configs = Config::get('print-suppliers::' . $supplierSlug);
            $view = 'print-suppliers::suppliers.' . $supplierSlug . '/index';
            
            return view($view, ['configs' => $configs]);
        }
    }

    public function postFulfill(Request $request)
    {

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

        $dataConfigs = \Config::get('print-suppliers::connection');
        $configs = [];
        foreach ($dataConfigs as $key => $value) {
            switch ($key) {
                case 'printify': $configs['printify'] = loadPrintifyConfigs($value); break;
                case 'gelato': $configs['gelato'] = loadGelatoConfigs($value); break;
            }
        }

        $shopId = null;
        $apiToken = null;

        try {

            if (isset($configs['printify'])) {
                $shopId = $configs['printify']['shop_id'];
                $apiToken = $configs['printify']['api_token'];
            }
    
            $orderId = $request->input('order_id');
            if ($orderId && $shopId && $apiToken) {
                $orderDetail = $this->findOrderDetail($orderId);

                if (isset($orderDetail['items'])) {
                    
                    $item = end($orderDetail['items']);
                    $profile = $this->findProfile($item['product_sku_id']);
                    
                    if ($profile) {
                        $customerName = getCustomerName($orderDetail['customer']['full_name']);
                        $lastName = $customerName['last_name'];
                        $firstName = $customerName['first_name'];
    
                        $printifyOrder = [
                            "external_id" => "printerval-" . $orderDetail['code'] . '-' . round(microtime(true) * 1000),
                            "label" => "API" . $orderDetail['code'],
                            "line_items" => [],
                            "shipping_method" => ($orderDetail['shipping_type'] == 'express' ? 2 : 1),
                            "send_shipping_notification" => false,
                            "address_to" => [
                                "first_name" => $firstName,
                                "last_name" => $lastName,
                                "email" => 'info@megaads.vn',
                                "phone" => $orderDetail['customer']['phone'],
                                "country" => $orderDetail['country']['iso'],
                                "region" => $orderDetail['state_name'],
                                "address1" => $orderDetail['delivery_address'],
                                "address2" => " ",
                                "city" => $orderDetail['city_name'],
                                "zip" => $orderDetail['zip_code']
                            ]
                        ];
    
                        $lineItem = [
                            "blueprint_id" => $profile['blueprint_id'],
                            "print_provider_id" => $profile['print_provider_id'],
                            "variant_id" => $profile['variant_id'],
                            "print_areas" => $profile['print_areas'],
                            "quantity" => $item['quantity']
                        ];
    
                        $printAreas = $profile['print_areas'];
                        if (isset($profile['position']['position'])) {
                            foreach ($profile['position']['position'] as $prArea => $value) {
                                $urlDesign = $profile['print_areas'][$prArea];
                                if (isset($profile['print_areas'][$prArea])) {
                                    $printAreas[$prArea] = [array_merge(['src' => $urlDesign], $value)];
                                }
                            }
                        }
    
                        $lineItem['print_areas'] = $printAreas;
                        $printifyOrder['line_items'] = [$lineItem];
    
                        $printifyRes = $this->triggerSyncRequest('https://api.printify.com/v1/shops/' . $shopId . '/orders.json', 
                            'POST', $printifyOrder, [
                                'Authorization: Bearer ' . $apiToken
                            ]);
                        
                        $responseData = [
                            'result' => $printifyRes
                        ];

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

        return $responseData;
    }
}
