<?php
/**
 * Manage Color Swatches
 *
 * PHP version 5.6
 *
 * @category  Settings
 * @package   Eloquent
 * @author    sanjeeb Dakhinaray <steve@imprintnext.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */
namespace App\Modules\Integration\Controllers;

use App\Components\Controllers\Component as ParentController;
use App\Modules\Settings\Models\Currency;
use App\Modules\Settings\Models\Language;
use App\Modules\Settings\Models\QuotationDynamicForm;
use App\Modules\Settings\Models\Setting;
use App\Modules\Settings\Models\Unit;
use App\Modules\Integration\Models\PluginSettings;
use Illuminate\Database\Capsule\Manager as DB;
use App\Modules\Orders\Controllers\OrdersController;
use App\Modules\Orders\Models\CatalogOrderRel;
use OrderStoreSpace\Controllers\StoreOrdersController;
use App\Modules\Products\Controllers\ProductsCatalogController;
use App\Modules\Products\Controllers\OrderDownloadController;


/**
 * Setting Controller
 *
 * @category Class
 * @package  Setting
 * @author   sanjeeb Dakhinaray <steve@imprintnext.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */

 class PrintfulController extends ParentController {
    
    /**
     * Performs a get request to the instantiated class
     * 
     * Accepts the apiUrl to perform the request on
     * 
     * @author steve@imprintnext.com
     * @param $apiUrl string $apiUrl a string to perform get on
     * @return results or var_dump error
     */
    public function printfulGet($path, $params = array()){
        $accessToken = $this->getAccessToken();
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.printful.com/products',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'token: '.$accessToken,
            ),
        ));
        $storeResponse = curl_exec($curl);
        $storeResponse = json_clean_decode($storeResponse);
        $catalogobj = new ProductsCatalogController();
        $data = $storeResponse['result'];
        $i =  0;
        foreach ($data as $product) {
            $productSku = base64_encode("PRINTFUL-".$product['id']);          
            $productArr[$i]['id'] = $product['id'];
            $productArr[$i]['style_id'] =  $productSku;
            $productArr[$i]['currency'] = $product['currency'];
            $productArr[$i]['sku'] = $productSku;
            $productArr[$i]['part_number'] = '';
            $productArr[$i]['description'] = $product['description'];
            $productArr[$i]['title'] = $product['title'];
            $productArr[$i]['brand_name'] = $product['brand'];
            $productArr[$i]['base_category'] = $product['type'];
            $productArr[$i]['categories'] = $product['type'];
            $productArr[$i]['style_image'] = $product['image'];
            $productArr[$i]['brand_image'] = $product['image'];
            $existingProductID = $catalogobj->checkProductExist($product['id']);
            $productArr[$i]['existingProductID'] = $existingProductID;
            $productArr[$i]['is_imported'] = $existingProductID > 0 ? true : false;
            $i++;
        }
        $response['status'] = 1;
        $response['records'] = sizeof($data);
        $response['total_records'] = sizeof($data);
        $response['data'] = $productArr;
        curl_close($curl);
        return($response);
    }
    /**
     * Performs a get Printful Product Detail
     * 
     * Accepts the Product ID to perform the request on
     * 
     * @author steve@imprintnext.com
     * @param $pid int
     * @return json
     */
    public function getPrintfulProductDetail($pid, $module = 'all', $accessToken = '')
    {
        $curl = curl_init();
        // decoded at the caller function
        $pid = base64_decode($pid);
        $pid = explode("-", $pid)[1];
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.printful.com/products/' . $pid,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'token: ' . $accessToken,
            ),
        ));
        $productResponse = curl_exec($curl);
        curl_close($curl);
        $productResponse = json_clean_decode($productResponse);

        if ($productResponse['code'] == 200) {
            $productResponse = $productResponse['result'];
            $variants = $productResponse['variants'];
            $productResponse = $productResponse['product'];
            $productSku = base64_encode("PRINTFUL-" . $productResponse['id']);
            $size['name'] = 'Size';
            $size['position'] = '0';
            $size['variation'] = 'true';
            $size['visible'] = 'true';
            $color['name'] = 'Color';
            $color['position'] = '0';
            $color['variation'] = 'true';
            $color['visible'] = 'true';
            $size['options'] = [];
            $color['options'] = [];
            $stitch['options'] = [];
            $s = 0;
            $c = 0;
            $r = 0;
            $variations = [];
            $images = [];
            $attributes = [];
            $category = [];

            if ($module == 'all') {
                $side = [];
                foreach ($productResponse['files'] as $sideKey => $files) {
                    $side[$sideKey] = $files['title'];
                }
                $option = $productResponse['options'];
                $i = 0;
                if (!empty($option)) {
                    foreach ($option as $newAttr) {
                        if ($newAttr['id'] == 'stitch_color') {
                            foreach ($newAttr['values'] as $optionKey => $optionValue) {
                                if (!in_array($newAttr['id'], $stitch['options'])) {
                                    $stitch['options'][$r] = $optionValue;
                                    $r++;
                                } else {

                                    unset($stitch);
                                }
                                foreach ($variants as  $value) {
                                    $variantSku = base64_encode("PRINTFUL-" . $value['product_id'] . "-" . $value['id'] . '-' . $optionKey);

                                    if (!in_array($value['size'], $size['options'])) {
                                        $size['options'][$s] = $value['size'];
                                        $s++;
                                    }
                                    if (!in_array($value['color'], $color['options'])) {
                                        $color['option_details'][$c]['name'] = $value['color'];
                                        $color['option_details'][$c]['value'] = $value['color_code'];
                                        $color['options'][$c] = $value['color'];
                                        $c++;
                                    }
                                    $variations[$i]['attributes'] = ["color" => $value['color'], "size" => $value['size'], "stitch_color" => $optionValue];
                                    $variations[$i]['brand_name'] = $productResponse['brand'];
                                    $variations[$i]['color_hex'] = $value['color_code'];
                                    $variations[$i]['id'] = $value['id'];
                                    $variations[$i]['image_path'] = [$value['image']];
                                    $variations[$i]['piece_price'] = $value['price'];
                                    $variations[$i]['quantity'] = 0;
                                    $variations[$i]['side_name'] = $side;
                                    $variations[$i]['size'] = $value['size'];
                                    $variations[$i]['sku'] = $variantSku;
                                    $variations[$i]['style_name'] = $value['name'];
                                    $variations[$i]['unit_weight'] = '';
                                    $variations[$i]['quantity'] = 100;
                                    $i++;
                                }
                            }
                            $stitch['name'] = 'stitch_color';
                            $stitch['position'] = '0';
                            $stitch['variation'] = 'true';
                            $stitch['visible'] = 'true';
                            $attributes[] = $stitch;
                        } else {
                            foreach ($variants as $value) {
                                $variantSku = base64_encode("PRINTFUL-" . $value['product_id'] . "-" . $value['id'] );
                                if (!in_array($value['size'], $size['options'])) {
                                    $size['options'][$s] = $value['size'];
                                    $s++;
                                }
                                if (!in_array($value['color'], $color['options'])) {
                                    $color['option_details'][$c]['name'] = $value['color'];
                                    $color['option_details'][$c]['value'] = $value['color_code'];
                                    $color['options'][$c] = $value['color'];
                                    $c++;
                                }

                                $variations[$i]['attributes'] = ["color" => $value['color'], "size" => $value['size']];
                                $variations[$i]['brand_name'] = $productResponse['brand'];
                                $variations[$i]['color_hex'] = $value['color_code'];
                                $variations[$i]['id'] = $value['id'];
                                $variations[$i]['image_path'] = [$value['image']];
                                $variations[$i]['piece_price'] = $value['price'];
                                $variations[$i]['quantity'] = 0;
                                $variations[$i]['side_name'] = $side;
                                $variations[$i]['size'] = $value['size'];
                                $variations[$i]['sku'] = $variantSku;
                                $variations[$i]['style_name'] = $value['name'];
                                $variations[$i]['unit_weight'] = '';
                                $variations[$i]['quantity'] = 100;
                                $i++;
                            }
                        }

                        $variation[] = $variations;
                    }
                } else {
                    
                    foreach ($variants as $value) {
                        $variantSku = base64_encode("PRINTFUL-" . $value['product_id'] . "-" . $value['id']);
                        if (!in_array($value['size'], $size['options'])) {
                            $size['options'][$s] = $value['size'];
                            $s++;
                        }
                        if (!in_array($value['color'], $color['options'])) {
                            $color['option_details'][$c]['name'] = $value['color'];
                            $color['option_details'][$c]['value'] = $value['color_code'];
                            $color['options'][$c] = $value['color'];
                            $c++;
                        }

                        $variations[$i]['attributes'] = ["color" => $value['color'], "size" => $value['size']];
                        $variations[$i]['brand_name'] = $productResponse['brand'];
                        $variations[$i]['color_hex'] = $value['color_code'];
                        $variations[$i]['id'] = $value['id'];
                        $variations[$i]['image_path'] = [$value['image']];
                        $variations[$i]['piece_price'] = $value['price'];
                        $variations[$i]['quantity'] = 0;
                        $variations[$i]['side_name'] = $side;
                        $variations[$i]['size'] = $value['size'];
                        $variations[$i]['sku'] = $variantSku;
                        $variations[$i]['style_name'] = $value['name'];
                        $variations[$i]['unit_weight'] = '';
                        $variations[$i]['quantity'] = 100;
                        $i++;
                    }
                    $variation[] = $variations;
                }

                $attributes[] = $color;
                $attributes[] = $size;
                $category[0] = $productResponse['type_name'];
                $images['position'] = 0;
                $images['src'] = $variants[0]['image'];
            }

            $productData = [
                "name" => $productResponse['title'],
                "price" => $variants[0]['price'],
                "description" => $productResponse['description'],
                "sku" => $productSku,
                "total_qty" => 100,
                "type" => 'variable',
                "attributes" => $attributes,
                "category" => $category,
                "color_data" => $color['options'],
                "images" => $images,
                "size_data" => $size['options'],
                "stitch_color_data" => $stitch['options'],
                "variations" =>  $variation[0],
            ];

            $responseData = [
                'status' => 1,
                'records' => 1,
                'data' => $productData,

            ];
        } else {
            $responseData = [
                'status' => 0,
                'records' => 0,
                'message' => 'Product not found',

            ];
        }

        return ($responseData);
    }
    /**
     * Performs a get Refresh token Printful
     * 
     * Accepts the Product ID to perform the request on
     * @author steve@imprintnext.com
     * @return string
     */
    public function getAccessToken(){
        $pluginsObj = new PluginSettings();
        $checkRecord = $pluginsObj->where(
            ['catalog_code' => 'printful']
        );
        $checkRecord = $checkRecord->first()->toArray();
        $checkRecord = json_clean_decode($checkRecord['settings']);
        $refreshToken = $checkRecord['refresh_token'];
        if($checkRecord['expires_at'] > time()){
            $accessToken = $checkRecord['access_token'];            
        }
        else{
            $cliendId = PRINTFUL_CLIENT_ID;
            $clientSecret = PRINTFUL_CLIENT_SECRET;
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://www.printful.com/oauth/token?grant_type=refresh_token&client_id='.$cliendId.'&client_secret='.$clientSecret.'&refresh_token='.$refreshToken,
                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',              
            ));
            $response = curl_exec($curl);            
            curl_close($curl);
            $printFullData = json_decode($response,true);
            $pluginData = [
                'catalog_code' => $checkRecord['catalog_code'],
                'domain_imprint_path' => $checkRecord['domain_imprint_path'],
                'auth_code' => $checkRecord['auth_code'],
                'access_token' => $printFullData['access_token'],
                'expires_at' => $printFullData['expires_at'],
                'refresh_token' => $printFullData['refresh_token'],
            ];
            $pluginSettingData['settings'] = json_encode($pluginData,true);
            $pluginsObj = new PluginSettings();            
            $pluginsObj->where(['catalog_code' => 'printful'])->update($pluginSettingData);
            $accessToken = $printFullData['access_token'];
        }
        return($accessToken);
    }
    /**
     * Performs  create webhook
     * 
     * Accepts the productIds  to perform the request on
     * @author steve@imprintnext.com
     * @param $productIds array
     * @return string
     */
    public function createHookPrintfulProductStock($productIds){
        $accessToken = $this->getAccessToken();
        $post_json = [
            "url" => API_URL.'assets/settings/webhooks/printful_hook.php',
            "types" => ["package_shipped","stock_updated"],
            "params"=> [
                "stock_updated"=> [
                "product_ids" => $productIds
                ]
            ]
        ];
        $post_json = json_encode($post_json,true);
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.printful.com/webhooks',
            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 =>$post_json,
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer '.$accessToken,
                'Content-Type: application/json',
            ),
        ));
        $response =  curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    /**
     * Performs  Catalog product Order detail
     * 
     * Accepts the catalog_order_id  to perform the request on
     * @author steve@imprintnext.com
     * @param $args array
     * @return string
     */
    public function printfulGetOrderDetail($catalog_order_id){
        $accessToken = $this->getAccessToken();     
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.printful.com/orders/'.$catalog_order_id,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET', 
            CURLOPT_HTTPHEADER => array(
              'Authorization: Bearer '.$accessToken,
              'Content-Type: application/json',
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_clean_decode($response);
        return($response['result']);
    }
    /**
     * Performs  Catalog product Order detail
     * 
     * Accepts the catalog_order_id  to perform the request on
     * @author steve@imprintnext.com
     * @param $args array
     * @return string
     */

    public function printfulNewOrders($thisOrderID, $shipping, $billing, $printfulOrderItems,$orderDetails){
        $pluginsInit = new PluginSettings();
        $printfulStatus = $pluginsInit->where('catalog_code', 'printful')
        ->where('status', 1);
        $pluginCountprint = $printfulStatus->count();
        if($pluginCountprint > 0)
        {
            $printfulOrderReq = [
                "external_id"=> $thisOrderID,
                "shipping"=> "STANDARD",
                "recipient"=> [
                    "name"=> $shipping['first_name'].$shipping['last_name'],
                    "address1"=> '"'.$shipping['address_1'].'"',
                    "city"=> $shipping['city'],
                    "state_code"=> $shipping['state'],
                    "country_code"=> $shipping['country_code'],
                    "zip"=> $shipping['postcode']
                ],
                "items"=> $printfulOrderItems,
                "packing_slip"=> [
                    "email"=> $billing['email'],
                    "phone"=> $billing['phone'],
                    "message"=> '',
                    "logo_url"=> ''
                ]
            ];
            $order_json =  json_encode($printfulOrderReq,true);

            $accessToken = $this->getAccessToken();
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://api.printful.com/orders',
                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 =>$order_json,
                CURLOPT_HTTPHEADER => array(
                    'Authorization: Bearer '.$accessToken,
                    'Content-Type: application/json',
                ),
            ));
            $response = curl_exec($curl);                
            curl_close($curl);

            $response = json_clean_decode($response);
            $result = $response['result'];
            $error = $response['error'];

            $CatalogOrder = [];
            $IntegrationObj = new IntegrationController();
            $printfulPluginId = $IntegrationObj->getPluginId('printful');

            $CatalogOrder['catalog_code'] = $printfulPluginId;
            $CatalogOrder['order_id'] = $thisOrderID;
            $CatalogOrder['created_date'] = $orderDetails['order_details']['created_date'];
            if (!empty($error)) {
                $CatalogOrder['status'] = 0;
                $CatalogOrder['report'] = $error['message'];
            } else {
                if (!empty($response)) {
                    $printfulOrderId = $result['id'];
                    $CatalogOrder['catalog_order_id'] = $printfulOrderId;
                    $CatalogOrder['status'] = 1;
                    $CatalogOrder['report'] = 'Order Placed Successfully';
                }
            } 
            $CatalogOrderRelObj = new CatalogOrderRel($CatalogOrder);
            $CatalogOrderRelObj->save();
        }
    }
	
}