<?php

namespace App\Adapter;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Shopify\Auth\Session;
use Shopify\Rest\Admin2023_04\Product;
use Shopify\Utils;

class ShopifyAdaptee
{
    public static function requestShopify($query)
    {
        $client = new Client();
        $headers = [
            'Content-Type' => 'application/json',
            'X-Shopify-Access-Token' => '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'
        ];
        $request = new Request('POST', 'https://89fff6.myshopify.com/admin/api/2023-07/graphql.json', $headers, $query);
        $res = $client->sendAsync($request)->wait();
        return json_decode($res->getBody()->getContents(), true);
    }

    public static function getItemIDBySku($sku)
    {
        $query = '{"query":"query {productVariants(first: 1, query: \\"sku:'.$sku.'\\") {\\r\\n    edges { \\r\\n        node {\\r\\n            id \\r\\n            sku  \\r\\n            displayName  \\r\\n            product {\\r\\n                id\\r\\n                totalInventory\\r\\n                tracksInventory\\r\\n            }\\r\\n            inventoryItem {\\r\\n                id\\r\\n                inventoryLevels(first: 250){\\r\\n                    edges {\\r\\n                        node {\\r\\n                            id\\r\\n                            available\\r\\n                            location{\\r\\n                                id\\r\\n                                isActive\\r\\n                            }            \\r\\n                        }\\r\\n                    }\\r\\n                }\\r\\n            }\\r\\n\\r\\n        }\\r\\n    }\\r\\n}}","variables":{}}';
        $response = self::requestShopify($query);
        if(empty($response['data']['productVariants']['edges'])){
            return false;
        }
        return $response['data']['productVariants']['edges'][0]['node'];
    }

    public static function updateProductStockById($locationId, $inventoryItem, $oldValue, $newValue)
    {
        $value = ($newValue - $oldValue) - 5;
        $query = '{"query":"mutation InventoryAdjustmentPopoverAdjustOnHand($input: InventoryAdjustQuantitiesInput!, $locationId: ID!) {\\r\\n  inventoryAdjustQuantities(input: $input) {\\r\\n    inventoryAdjustmentGroup {\\r\\n      id\\r\\n      changes {\\r\\n        item {\\r\\n          id\\r\\n          inventoryLevel(locationId: $locationId) {\\r\\n            id\\r\\n            quantities(\\r\\n              names: [\\"available\\", \\"committed\\", \\"incoming\\", \\"on_hand\\", \\"reserved\\", \\"damaged\\", \\"safety_stock\\", \\"quality_control\\"]\\r\\n            ) {\\r\\n              quantity\\r\\n              name   \\r\\n            }\\r\\n          }\\r\\n        }\\r\\n      }\\r\\n    }\\r\\n    userErrors {\\r\\n      field\\r\\n      message\\r\\n      \\r\\n    }\\r\\n    \\r\\n  }\\r\\n}\\r\\n","variables":{"locationId":"'.$locationId.'","input":{"changes":[{"delta":'.$value.',"locationId":"'.$locationId.'","inventoryItemId":"'.$inventoryItem.'"}],"reason":"correction","name":"available"}}}';
        $response = self::requestShopify($query);
        return $response;
    }
    
    public static function calcValueProduct($oldValue, $newValue)
    {
        return $newValue - $oldValue;
    }

    public static function updateProductPriceById($id, $price)
    {
        $query = '{"query":"mutation productVariantUpdate($input: ProductVariantInput!) {\\r\\n  productVariantUpdate(input: $input) {\\r\\n    product {\\r\\n      id\\r\\n    }\\r\\n    productVariant {\\r\\n      id\\r\\n    }\\r\\n    userErrors {\\r\\n      field\\r\\n      message\\r\\n    }\\r\\n  }\\r\\n}","variables":{"input":{"id":"'.$id.'","price":"'.$price.'"}}}';
        $response = self::requestShopify($query);
        return $response;
    }

    public static function updatePriceAndStock($sku, $newStock = 0, $newPrice = 0, $typeRequest = 2)
    {
        $Product = self::getItemIDBySku($sku);
        if(!$Product){
            return [
                'status' => 'error',
                'message' => 'Sku é invalido',
            ];
        }
        $response = self::updateProductStockById(
            $Product['inventoryItem']['inventoryLevels']['edges'][0]['node']['location']['id'],
            $Product['inventoryItem']['id'],
            $Product['inventoryItem']['inventoryLevels']['edges'][0]['node']['available'],
            $newStock
        );
        $response = self::updateProductPriceById($Product['id'], $newPrice);
        return $Product;
    }
}
