<?php

function salesloo_fb_pixel_script_base()
{
    $script = "<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');
      </script>";

    return $script;
}

function salesloo_tiktok_pixel_script_base()
{
    $script = "<script>
!function (w, d, t) {
  w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var i='https://analytics.tiktok.com/i18n/pixel/events.js';ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement('script');o.type='text/javascript',o.async=!0,o.src=i+'?sdkid='+e+'&lib='+t;var a=document.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};
}(window, document, 'ttq');
</script>";

    return $script;
}

function salesloo_fb_pixel_script_init($pixel_ids)
{
    if (!is_array($pixel_ids)) {
        $pixel_ids = (array)$pixel_ids;
    }

    $script = '<script>';
    foreach ($pixel_ids as $id) {
        $script .= 'fbq(\'init\', \'' . $id . '\');';
    }

    $script .= '</script>';

    return $script;
}

function salesloo_fb_pixel_script_event($event = 'PageView', $args = [])
{
    $args = (object) $args;
    if ($event == 'PageView' || $event == 'SubmitApplication') {
        $script = 'fbq(\'track\', \'PageView\');';
    } else {
        $script = 'fbq(\'track\', \'' . $event . '\', ' . json_encode($args) . ');';
    }

    return $script;
}

function salesloo_insert_fb_pixel_on_checkout()
{
    $pixel_ids = salesloo_get_option('fb_pixel_ids');
    if (empty($pixel_ids)) return;
    $pixel_ids = explode(',', $pixel_ids);
    $affiliate_username = \Salesloo\Checkout::instance()->affiliate_id;
    $affiliate = get_userdata($affiliate_username);

    $products = \Salesloo\Cart::prepare()->get_items();
    $ids = [];
    foreach ($products as $product) {
        $ids[] = $product->slug;
        if ($affiliate && salesloo_get_option('affiliate_tracking_fbpixel')) {
            $affiliate_pixels = salesloo_get_product_meta($product->ID, 'fbpixel_' . $affiliate->ID, true);
            if ($affiliate_pixels) {
                $affiliate_pixels = explode(',', $affiliate_pixels);
                $pixel_ids = array_merge($pixel_ids, $affiliate_pixels);
            }
        }
    }

    echo salesloo_fb_pixel_script_base();
    echo salesloo_fb_pixel_script_init($pixel_ids);
    echo '<script>';

    $page_load_event = salesloo_get_option('fb_pixel_on_checkout_page_load_event');

    $summary = Salesloo\Checkout::instance()->summary();
    $total = $summary['total'];

    $data = (object)[
        // 'content_type' => 'product',
        // 'content_category' => '',
        // 'content_name'     => 'Salesloo Checkout Page',
        // 'content_ids'      => $ids,
        'currency'         => salesloo_get_option('currency'),
        'value'            => $total['value']
    ];
    echo 'document.addEventListener("DOMContentLoaded", function(event) {';
    echo salesloo_fb_pixel_script_event();
    if ($page_load_event && $page_load_event != 'none') {
        echo salesloo_fb_pixel_script_event($page_load_event, $data);
    }

    // if ($submit_button_event_button && $submit_button_event_button != 'none') {
    //     echo 'let buynow = document.getElementById(\'buynow\');';
    //     echo 'if( typeof(buynow) != \'undefined\' && buynow !== null ){';
    //     echo 'buynow.addEventListener(\'click\', function(){' . salesloo_fb_pixel_script_event($submit_button_event_button, $data) . '}, false);';
    //     echo '}';
    // }
    echo '});';

    echo '</script>';
}

add_action('salesloo/checkout/end', 'salesloo_insert_fb_pixel_on_checkout');

function salesloo_insert_fb_pixel_on_payment()
{
    $pixel_ids = salesloo_get_option('fb_pixel_ids');
    if (empty($pixel_ids)) return;
    $pixel_ids = explode(',', $pixel_ids);

    $vars = salesloo_vars();
    $invoice_id = salesloo_decrypt(sanitize_text_field($vars['__invoice']));
    $invoice = \Salesloo\Models\Invoice::query('WHERE ID = %d', $invoice_id)->first();
    $orders = $invoice->orders();
    if (isset($orders[0])) {
        $order = $orders[0];
        $affiliate_id = $order->meta('affiliate_id');
        $affiliate = get_userdata($affiliate_id);
        if ($affiliate && salesloo_get_option('affiliate_tracking_fbpixel')) {
            $affiliate_pixels = salesloo_get_product_meta($order->product_id, 'fbpixel_' . $affiliate->ID, true);
            if ($affiliate_pixels) {
                $affiliate_pixels = explode(',', $affiliate_pixels);
                $pixel_ids = array_merge($pixel_ids, $affiliate_pixels);
            }
        }
    }

    echo salesloo_fb_pixel_script_base();
    echo salesloo_fb_pixel_script_init($pixel_ids);
    echo '<script>';

    $page_load_event = salesloo_get_option('fb_pixel_on_payment_page_load_event');

    $total = Salesloo\Invoice::instance()->get_total();

    $data = (object)[
        // 'content_type' => 'product',
        // 'content_category' => '',
        // 'content_name'     => 'Salesloo Checkout Page',
        // 'content_ids'      => $ids,
        'currency'         => salesloo_get_option('currency'),
        'value'            => $total
    ];
    echo 'document.addEventListener("DOMContentLoaded", function(event) {';
    echo salesloo_fb_pixel_script_event();
    if ($page_load_event && $page_load_event != 'none') {
        echo salesloo_fb_pixel_script_event($page_load_event, $data);
    }

    echo '});';

    echo '</script>';
}
add_action('salesloo/payment/end', 'salesloo_insert_fb_pixel_on_payment');

function salesloo_insert_tiktok_pixel_on_checkout()
{
    $pixel_ids = salesloo_get_option('tiktok_pixel_ids');
    if (empty($pixel_ids)) return;
    $pixel_ids = explode(',', $pixel_ids);
    $affiliate_username = \Salesloo\Checkout::instance()->affiliate_id;
    $affiliate = get_userdata($affiliate_username);

    $products = \Salesloo\Cart::prepare()->get_items();
    $ids = [];
    foreach ($products as $product) {
        $ids[] = $product->slug;
        if ($affiliate && salesloo_get_option('affiliate_tracking_tiktokpixel')) {
            $affiliate_pixels = salesloo_get_product_meta($product->ID, 'tiktokpixel_' . $affiliate->ID, true);
            if ($affiliate_pixels) {
                $affiliate_pixels = explode(',', $affiliate_pixels);
                $pixel_ids = array_merge($pixel_ids, $affiliate_pixels);
            }
        }
    }

    echo salesloo_tiktok_pixel_script_base();
    echo '<script>';

    $page_load_event = salesloo_get_option('tiktok_pixel_on_checkout_page_load_event');

    $summary = Salesloo\Checkout::instance()->summary();
    $total = $summary['total'];

    $data = (object)[
        // 'content_type' => 'product',
        // 'content_category' => '',
        'content_name'     => 'Salesloo Checkout Page',
        'content_id'      => $ids,
        'currency'         => salesloo_get_option('currency'),
        'value'            => $total['value']
    ];

    foreach ($pixel_ids as $id) {
        echo "ttq.load('{$id}');";
    }
    echo "ttq.page();";

    echo 'document.addEventListener("DOMContentLoaded", function(event) {';
    $data = json_encode($data);
    if ($page_load_event && $page_load_event != 'none') {
        echo "ttq.track('{$page_load_event}', {$data});";
    }
    echo '});';

    echo '</script>';
}
add_action('salesloo/checkout/end', 'salesloo_insert_tiktok_pixel_on_checkout', 10);

function salesloo_insert_tiktok_pixel_on_payment()
{
    $pixel_ids = salesloo_get_option('tiktok_pixel_ids');
    if (empty($pixel_ids)) return;
    $pixel_ids = explode(',', $pixel_ids);

    $vars = salesloo_vars();
    $invoice_id = salesloo_decrypt(sanitize_text_field($vars['__invoice']));
    $invoice = \Salesloo\Models\Invoice::query('WHERE ID = %d', $invoice_id)->first();
    $orders = $invoice->orders();
    $ids = [];
    foreach ($orders as $order) {
        $ids[] = $order->product_id;
    }
    if (isset($orders[0])) {
        $order = $orders[0];
        $affiliate_id = $order->meta('affiliate_id');
        $affiliate = get_userdata($affiliate_id);
        if ($affiliate && salesloo_get_option('affiliate_tracking_tiktokpixel')) {
            $affiliate_pixels = salesloo_get_product_meta($order->product_id, 'tiktokpixel_' . $affiliate->ID, true);
            if ($affiliate_pixels) {
                $affiliate_pixels = explode(',', $affiliate_pixels);
                $pixel_ids = array_merge($pixel_ids, $affiliate_pixels);
            }
        }
    }

    echo salesloo_tiktok_pixel_script_base();
    echo '<script>';

    $page_load_event = salesloo_get_option('tiktok_pixel_on_payment_page_load_event');

    $total = Salesloo\Invoice::instance()->get_total();
    $data = (object)[
        // 'content_type' => 'product',
        // 'content_category' => '',
        'content_name'     => 'Salesloo Payment Page',
        'content_id'      => $ids,
        'currency'         => salesloo_get_option('currency'),
        'value'            => $total
    ];

    foreach ($pixel_ids as $id) {
        echo "ttq.load('{$id}');";
    }
    echo "ttq.page();";

    echo 'document.addEventListener("DOMContentLoaded", function(event) {';
    $data = json_encode($data);
    if ($page_load_event && $page_load_event != 'none') {
        echo "ttq.track('{$page_load_event}', {$data});";
    }
    echo '});';

    echo '</script>';
}
add_action('salesloo/payment/end', 'salesloo_insert_tiktok_pixel_on_payment');
