<?php
require '../Helpers.php';


$HmacHeader = isset($_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256']) ? $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'] : '';
$webhookData = file_get_contents('php://input');

if (!empty($HmacHeader) && !empty($webhookData)) {
    $verified = verify_webhook($webhookData, $HmacHeader);
} else {
    $verified = true;
}



if ($verified) {
    // $myfile = fopen("order_data.txt", "w") or die("Unable to open file!");
    // $data = $webhookData;
    // fwrite($myfile, $data);
    // fclose($myfile);
    $decode_data = json_decode($webhookData, true);
    // dd($decode_data);
    if (isset($decode_data['line_items']) && !empty($decode_data['line_items'])) {
        $lineItems = $decode_data['line_items'];
        $result = update_inventory($lineItems);
        if ($result) {
            return true;
        } else {
            error_log("Inventory updated successfully Order ID  = " . $decode_data['id']);
            return true;
        }
    } else {
        if (isset($decode_data['id']) && !empty($decode_data['id'])) {
            error_log("Something Went Wrong Order Id = " . $decode_data['id']);
            return true;
        }
        return true;
    }

}



function update_inventory($lineItems)
{
    foreach ($lineItems as $lineItem) {
        if (isset($lineItem['properties']) && !empty($lineItem['properties'])) {
            if (in_array('_mainSwapBoxId', $lineItem['properties'][0])) {


                $total_items = count($lineItem['properties']);
                $count = 0;
                // dd($total_items);
                // dd($lineItem);
                foreach ($lineItem['properties'] as $items) {
                    if (strpos($items['name'], 'item') === 0) {
                        $client = graphql();
                        $variant_title = $items['value'];
                        $query = <<<QUERY
                            {
                                productVariants(first: 1, query: "title:$variant_title") {
                                edges {
                                node {
                                    displayName
                                    id
                                    inventoryQuantity
                                    inventoryItem {
                                    id
                                    sku
                                    locationsCount {
                                        count
                                    }
                                    inventoryLevels(first: 10) {
                                        nodes {
                                        location {
                                            id
                                        }
                                        }
                                    }
                                    }
                                }
                                }
                            }
                        }
            
                        QUERY;
                        $response = $client->query(['query' => $query]);
                        $getVaraint = $response->getDecodedBody();
                        // dd($getVaraint);
                        if (isset($getVaraint['data']['productVariants']['edges'][0]) && !empty($getVaraint['data']['productVariants']['edges'][0])) {
                            $inventoryQuantity = (int) $getVaraint['data']['productVariants']['edges'][0]['node']['inventoryQuantity'] - 1;
                            $inventoryItem_id = explode('/', $getVaraint['data']['productVariants']['edges'][0]['node']['inventoryItem']['id'])[4];
                            $location_id = explode('/', $getVaraint['data']['productVariants']['edges'][0]['node']['inventoryItem']['inventoryLevels']['nodes'][0]['location']['id'])[4];



                            $client = rest();
                            $body = [
                                "inventory_item_id" => $inventoryItem_id,
                                "location_id" => $location_id,
                                "available" => $inventoryQuantity,
                            ];

                            $response = $client->post("inventory_levels/set", $body);

                            $result = $response->getDecodedBody();

                            if (isset($result['inventory_level']) && !empty($result['inventory_level'])) {
                                error_log("Variant Updated Successfully = " . $variant_title);
                            } else {
                                error_log("inventory_level Not Update Due To Some Reasons = " . $variant_title);
                                continue;
                            }
                        } else {
                            error_log("Variant Not Found Variant Title= " . $variant_title);
                        }
                    }
                }

            }

        } else {
            return true;
        }
    }
    return true;
}



function update_customer($customer_id, $lineItems)
{
    // dd($lineItems);
    $data = [];
    foreach ($lineItems as $lineItem) {
        array_push($data, $lineItem['title']);
    }
    array_push($data, date("h:i:sa"));
    $data = json_encode($data);
    $body = [
        'customer' => [
            'id' => $customer_id,
            'metafields' => [
                [
                    "key" => "audio_listened",
                    "value" => "$data",
                    "type" => "list.single_line_text_field",
                    "namespace" => "custom"
                ],
            ],
            'tags' => ['audio_listened'],
        ]
    ];
    $client = rest();
    $response = $client->put("customers/$customer_id", $body);
    $result = $response->getDecodedBody();
    // dd($result);
    if (isset($result['customer']) && !empty($result['customer'])) {
        return true;
    }


}


function update_customers($customer_id, $lineItems)
{

    $client = graphql();

    $data = [];
    foreach ($lineItems as $lineItem) {
        array_push($data, $lineItem['title']);
    }
    array_push($data, date("h:i:sa"));

    // dd($data);
    $query = <<<QUERY
    query {
         customer(id: "gid://shopify/Customer/$customer_id") {
            metafield(key: "custom.audio_listened") {
            id
            key
            description
            createdAt
            namespace
            value
            }
        }

    }

    QUERY;
    $response = $client->query(['query' => $query]);


    $getMetafield = $response->getDecodedBody();


    if (isset($getMetafield['data']['customer']['metafield']) && !empty($getMetafield['data']['customer']['metafield'])) {


        $currentValue = $getMetafield['data']['customer']['metafield']['value'];

        if ($currentValue) {
            $currentValueArray = json_decode($currentValue, true);
        } else {
            $currentValueArray = [];
        }

        $updatedValueArray = array_merge($currentValueArray, $data);

        $updatedValue = json_encode($updatedValueArray);
        $mutation = <<<QUERY
        mutation MetafieldsSet(\$metafields: [MetafieldsSetInput!]!) {
            metafieldsSet(metafields: \$metafields) {
                metafields {
                    id
                    namespace
                    key
                    value
                    __typename
                }
                userErrors {
                    field
                    message
                    elementIndex
                    __typename
                }
            }
        }
        QUERY;


        $variables = [
            "metafields" => [
                [
                    "namespace" => "custom",
                    "key" => "audio_listened",
                    "value" => $updatedValue,
                    "type" => "list.single_line_text_field",
                    "ownerId" => "gid://shopify/Customer/$customer_id"
                ]
            ]
        ];
        $responseUpdate = $client->query(['query' => $mutation, 'variables' => $variables]);

        $setMetafield = $responseUpdate->getDecodedBody();
        if (isset($setMetafield['data']['metafieldsSet']['metafields']['0']) && !empty($setMetafield['data']['metafieldsSet']['metafields']['0'])) {
            return true;
        }
    } else {
        $data = json_encode($data);
        $client = graphql();
        $tags = [];
        $query = <<<QUERY
            query {
                customer(id: "gid://shopify/Customer/$customer_id") {
                id
                tags
            }
    
        }
    
        QUERY;
        $response = $client->query(['query' => $query]);

        $result = $response->getDecodedBody();
        if (isset($result['data']['customer']) && !empty($result['data']['customer'])) {
            array_push($result['data']['customer']['tags'], 'audio_listened');
            $body = [
                'customer' => [
                    'id' => $customer_id,
                    'metafields' => [
                        [
                            "key" => "audio_listened",
                            "value" => $data,
                            "type" => "list.single_line_text_field",
                            "namespace" => "custom"
                        ],
                    ],
                    'tags' => $result['data']['customer']['tags'],
                ]
            ];
        } else {
            $body = [
                'customer' => [
                    'id' => $customer_id,
                    'metafields' => [
                        [
                            "key" => "audio_listened",
                            "value" => $data,
                            "type" => "list.single_line_text_field",
                            "namespace" => "custom"
                        ],
                    ],
                    'tags' => ['audio_listened'],
                ]
            ];
        }

        $client = rest();
        $response = $client->put("customers/$customer_id", $body);
        $result = $response->getDecodedBody();
        // dd($result);
        if (isset($result['customer']) && !empty($result['customer'])) {
            return true;
        }
    }
}

// function update_customer_tags($customer_id)
// {

// }

function get_products()
{

    $query = <<<QUERY

    query {
         products(first: 10) {
            edges {
                node {
                id
                }
            }
        }

    }

    QUERY;



    $client = graphql();

    $response = $client->query(['query' => $query]);

    $getSku = $response->getDecodedBody();

    dd($getSku);

    // if (!empty($getSku['data']['inventoryItem']['sku'])) {

    //     return $getSku['data']['inventoryItem']['sku'];

    // } else {

    //     return "";

    // }

}


function verify_webhook($webhookData = null, $HmacHeader = null)
{

    $calculated_hmac = base64_encode(hash_hmac('sha256', $webhookData, 'e424d07126424b33fa69a5dd7585fd8d116f66e669e205df6d93d78a79ade5e7', true));

    if ($HmacHeader == $calculated_hmac) {

        return true;

    } else {

        return false;

    }

}








