add_action( 'woocommerce_thankyou', 'my_custom_tracking' );

function my_custom_tracking( $order_id ) {
// Lets grab the order
    $order = wc_get_order( $order_id );

    //Everflow order objects
    $efOrder = array();
    $efOrder['items'] = array();
    $efOrder['oid'] = $order_id;
    $efOrder['amt'] = $order->get_total();
    $efOrder['bs'] = $order->get_billing_state();
    $efOrder['bc'] = $order->get_billing_country();

    // Determine if any coupons were used for this transaction
    $coupons = '';
    if( $order->get_used_coupons() ) {
        foreach( $order->get_used_coupons() as $coupon) {
            $coupons .= $coupon.',';
        }
    }
    $efOrder['cc'] = $coupons;

    // This is how to grab line items from the order
    $line_items = $order->get_items();

    // This loops over line items
    $efItems = array();
    foreach ( $line_items as $item ) {
        //Init Everflow item
        $efItem = array();
        // This will be a product
        $product = $order->get_product_from_item( $item );
        // This is the products SKU (variant or parent)
        $efItem['vs'] = '';
        $efItem['ps'] = '';
        if ( $product->get_type() === 'variation' )
        { $efItem['vs'] = $product->get_sku(); }
        else
        { $efItem['ps'] = $product->get_sku(); }
        // This is the qty purchased
        $efItem['qty'] = $item['qty'];
        // Line item total cost including taxes and rounded
        $efItem['p'] = $order->get_line_total( $item, true, true );
        // Add this to Everflow items
        $efItems[] = $efItem;
    }
    $efOrder['items'] = $efItems;

    $javascriptCode = '
        <script>
        (function(){
            var script = document.createElement("iframe");
            script.width = 1;
            script.height = 1;
            script.frameBorder = 0;
            script.nid = "TO_BE_PROVIDED";
            script.oid = "TO_BE_PROVIDED";
            script.transaction_id = ""; //Optional

            script.order = '.json_encode($efOrder).';
            script.src = "https://www.servecvr.com/?nid=" + script.nid + "&oid=" + script.oid + "&transaction_id=" + script.transaction_id + "";

            script.src += "&amount=" + '.$order->get_total().';

            if (script.order) {
                script.src += "&order=" + encodeURIComponent(JSON.stringify(script.order));
            }

            document.getElementsByTagName("body")[0].appendChild(script);
        })();
        </script>
        <noscript><img src="https://www.servecvr.com/?nid=TO_BE_PROVIDED&oid=TO_BE_PROVIDED&orders='.urlencode(json_encode($efOrder)).'&amount=" + '.$order->get_total().'" height="1" width="1" style="display:none;"/></noscript>';
    echo $javascriptCode;
}