<?php
namespace twa\htmlhelpers\helpers;

use twa\ecomgeneral\models\EcomStoreModel;
use twa\ecomprofile\models\EcomCountriesModel;
use Illuminate\Support\Facades\Http;
use GuzzleHttp\Cookie\CookieJar;

class gaTrackingHelper
{

    protected $store;
    protected $event;
    protected $umami_url = "https://umami.twalab.live";
    protected $umami_user = "twa_umami";
    protected $umami_pass = "ZkZWW5EkuhWqdg2j";
    protected $umami_token = false;

    function __construct(){

    }


    public function track(){

        $UserID = false;
        if(isset(request()->user['user']['id']) && request()->user['user']['id'] > 0){
            $UserID =  request()->user['user']['id'];
        }
        $store = ecom('stores')->getCurrent();

        if($store['ga_tracking'] && count($store['ga_tracking']) > 0){
            foreach ($store['ga_tracking'] AS $tracking){
                if(isset($tracking["tracking_id"]) && $tracking["tracking_id"] != ""){
                    echo "<!-- Global site tag (gtag.js) - Google Analytics -->
                    <script async src=\"https://www.googletagmanager.com/gtag/js?id=".$tracking["tracking_id"]."\"></script>
                        <script>
                                window.dataLayer = window.dataLayer || [];
                          function gtag(){dataLayer.push(arguments);}
                          gtag('js', new Date());

                          gtag('config', '".$tracking["tracking_id"]."');
                    </script>";



                }

                if(session("gaTrackingHelperEvents") && is_array(session("gaTrackingHelperEvents")) && count(session("gaTrackingHelperEvents")) >0){
                    foreach (session("gaTrackingHelperEvents") AS $event){
                        echo '<script>gtag("event",  "'.$event["event"].'",  '.json_encode($event["payload"]).' );</script>';
                    }
                }
            }
        }



        echo '<script>var twa_analytics_data = []; twa_analytics_data.push({"project":"'.env("APP_URL").'"}); twa_analytics_data.push({"store":"'.request()->store['id'].'"});</script>';

        if(session('login') && isset(session('login')['id'])){ echo '<script>twa_analytics_data.push({"user":'.session('login')['id'].'});</script>'; }

        if(session("gaTrackingHelperEvents") && is_array(session("gaTrackingHelperEvents")) && count(session("gaTrackingHelperEvents")) >0){
            foreach (session("gaTrackingHelperEvents") AS $event){
                $event['path'] = url()->current();
                $event['website'] = env('APP_URL');
                if($event['event'] == "view_item"){
                    $event['payload2']["item_id"] = $event['payload']['items'][0]['item_id'];
                    $event['payload2']["item_name"] = $event['payload']['items'][0]['item_name'];
                    $event['payload2']["price"] = $event['payload']['items'][0]['price'];
                    $event['payload2']["item_category"] = $event['payload']['items'][0]['item_category'];
                }
                if(session('login') && isset(session('login')['id'])){ $event["payload"]['user'] = session('login')['id']; }
                echo '<script>twa_analytics_data.push({"action":"'.$event["event"].'"});</script>';
                if($event["event"] == "view_item"){
                    echo "<script>twa_analytics_data.push({'item_id':'".$event['payload2']["item_id"]."'});</script>";
                }
                if($event["event"] == "purchase"){
                    echo "<script>twa_analytics_data.push({'item_id':'".$event['payload']["transaction_id"]."'});</script>";
                }

                echo "<script>twa_analytics_data.push({'data':'".json_encode($event["payload"])."'});</script>";
            }
        }else{
            echo '<script>twa_analytics_data.push({"action":"page_view"});</script>';
        }
        echo '<script src="https://cdn.jsdelivr.net/gh/thewebaddicts/ecom-cdn@7.2/packages/js/analytics/app.min.js" async></script>';
//        echo '<script src="https://analytics.twalab.test/js/app.js" async></script>';
        session(["gaTrackingHelperEvents" => false ]);
        session(['twa_analytics_events' => false ]);
    }

    public function addEvent($event,$payload){
        switch ($event){
            case "view_item":
                self::addEventViewItem($event,$payload);
                break;
            case "view_item_list":
                self::addEventViewItems($event,$payload);
                break;
            case "add_to_cart":
                self::addEventAddToBag($event,$payload);
                break;
            case "begin_checkout":
                self::addEventAddToBag($event,$payload);
                break;
            case "purchase":
                self::addEventPurchase($event,$payload);
                break;
        }

    }

    public static function addEventViewItem($event,$product){
        $payload = ["items" => [ ["item_id" => $product["sku"], "item_name" => $product["label"], "price" => (string)$product["price_ttc"], "item_brand" => "", "item_category" => (string)$product["ecom_subcategories_id"], "index"=> 0] ], "currency" => "USD" ];

        $tracking = session("gaTrackingHelperEvents");
        $tracking[] = [ "event" => $event, "payload" => $payload ];
        session(["gaTrackingHelperEvents" => $tracking ]);
        if(!session('twa_analytics_events')){ session(['twa_analytics_events' => []]); }
        session([ 'twa_analytics_events' => ["product" => $product["id"] , "action" => 'view_item'] ]);
    }


    public static function addEventViewItems($event,$products){
        $items = [];
        foreach ($products AS $product){
            $items[] = ["item_id" => $product["sku"], "item_name" => $product["label"], "price" => (string)$product["price_ttc"], "item_brand" => "", "item_category" => (string)$product["ecom_subcategories_id"], "index"=> 0];
        }
        $payload = ["items" => $items, "currency" => "USD" ];

        $tracking = session("gaTrackingHelperEvents");
        $tracking[] = [ "event" => $event, "payload" => $payload];
        session(["gaTrackingHelperEvents" => $tracking ]);


    }

    public static function addEventAddToBag($event,$product){
        if(!isset($product["ecom_subcategories_id"])){ $product["ecom_subcategories_id"] = ""; }
        $payload = ["items" => ["item_id" => $product["sku"], "item_name" => $product["label"], "price" => (string)$product["price_ttc"], "item_brand" => "", "item_category" => (string)$product["ecom_subcategories_id"], "index"=> 0, "item_variant" => "", "size" => ""], "currency" => "USD", "value" => $product["price_ttc"] * $product["quantity"] ];

        $tracking = session("gaTrackingHelperEvents");
        $tracking[] = [ "event" => $event, "payload" => $payload ];
        session(["gaTrackingHelperEvents" => $tracking ]);

        session([ 'twa_analytics_events' => ["product" => $product["id"] , "action" => 'add_to_bag'] ]);
    }

    public static function addEventPurchase($event,$purchase){
        $items = [];
        foreach($purchase["items"]["items"] AS $product) {
            if(!isset($product["ecom_subcategories_id"])){ $product["ecom_subcategories_id"] = ""; }
            $items[]= ["item_id" => $product["details"]["sku"], "item_name" => $product["details"]["label"], "price" => (string)$product["details"]['unit_price']['price'], "item_brand" => "", "item_category" => (string)$product["ecom_subcategories_id"], "index"=> 0, "item_variant" => "", "size" => ""];
        }

        if(!isset($product["ecom_subcategories_id"])){ $product["ecom_subcategories_id"] = ""; }
        $payload = [ "transaction_id" => $purchase['id'], "items" => $items, "currency" => "USD", "value" => $purchase["total"], "tax" => 0,  "shipping" => 0, ];

        $tracking = session("gaTrackingHelperEvents");
        $tracking[] = [ "event" => $event, "payload" => $payload ];
        session(["gaTrackingHelperEvents" => $tracking ]);
        session([ 'twa_analytics_events' => ["action" => 'purchase', 'purchase_id' => $purchase['id'], 'conversion' => $purchase["total"], 'conversion_currency' => "USD", 'products' => collect($purchase["items"]["items"])->pluck('ecom_products_id') ]]);
    }
}
