<?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 fbqTrackingHelper
{

    protected $store;
    protected $event;


    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['fbq_tracking'] && count($store['fbq_tracking']) > 0){
            foreach ($store['fbq_tracking'] AS $tracking){
                if(isset($tracking["tracking_id"]) && $tracking["tracking_id"] != ""){
                    echo "

                                                <!-- Facebook Pixel Code -->
                            <script>
                            !function(f,b,e,v,n,t,s)
                            {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
                            n.callMethod.apply(n,arguments):n.queue.push(arguments)};
                            if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
                            n.queue=[];t=b.createElement(e);t.async=!0;
                            t.src=v;s=b.getElementsByTagName(e)[0];
                            s.parentNode.insertBefore(t,s)}(window,document,'script',
                            'https://connect.facebook.net/en_US/fbevents.js');
                            fbq('init', '".$tracking["tracking_id"]."');
                            fbq('track', 'PageView');";
                    if(session("fbqTrackingHelperEvents") && is_array(session("fbqTrackingHelperEvents")) && count(session("fbqTrackingHelperEvents")) >0){
                        foreach (session("fbqTrackingHelperEvents") AS $event){
                            echo 'fbq("track",  "'.$event["event"].'",  '.json_encode($event["payload"]).' );';
                        }
                    }
                    echo"
                            </script>
                            <noscript>
                            <img height=\"1\" width=\"1\"
                            src=\"https://www.facebook.com/tr?id=".$tracking["tracking_id"]."&ev=PageView
                            &noscript=1\"/>
                            </noscript>
                            <!-- End Facebook Pixel Code -->
                                                ";
                }


            }
        }



        session(["fbqTrackingHelperEvents" => false ]);

    }

    public function addEvent($event,$payload){

        switch ($event){
            case "Purchase":
                self::addEventPurchase($event,$payload);
                break;

            default:
                self::addGeneralEvent($event,$payload);
                break;
        }

    }

    public static function addGeneralEvent($event,$product){

        $payload = ["content_ids" =>[$product["sku"]],
            "content_type"=> "product_group",
            "value"=> (string)$product["price_ttc"],
            "currency" => "USD",
        ];

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

    }
    public static function addEventPurchase($event,$purchase){
        $items = [];
        foreach($purchase["items"]["items"] AS $product) {
            if(!isset($product["ecom_subcategories_id"])){ $product["ecom_subcategories_id"] = ""; }
            $items[]= ["id" => $product["details"]["sku"], "quantity" => $product["quantity"], "price" => (string)$product["details"]['unit_price']['usd'],];
        }
        $payload = [
            "content_type"=> "product",
            "value"=> $purchase["total"],
            "contents" => json_encode($items),
            "currency" => "USD",
            "status"=>1
        ];

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

    }
}
