<?php
/**
 *
 * Universal Analytics server-server tracking replacing the Gif request from Traditional
 * Analytics.
 * Assumes it is included in a payment gateway callback so there's $order variable defined.
 *
 */

$debug = DEV_MODE;

require_once dirname(__FILE__) . '/universal-analytics-php/universal-analytics.php';

$orderId = $order->getId();

// log an error if the file is called, but required settings are not defined
if (!defined('GOOGLE_ANALYTICS_USERAGENT') || !GOOGLE_ANALYTICS_USERAGENT) {
    $message = "Order id [$orderId]. GOOGLE_ANALYTICS_USERAGENT not defined. Unable to send Universal Analytics ecommerce tracking data.";
    gaLog($message);
    if (!$debug) {
        $message .= ' in ' . __FILE__ . ' on ' . __LINE__;
        error_log($message);
    }
    return;
}

// extract Client Id from ga cookie.
preg_match('#[^\.]+\.[^\.]+\.([\d]+\.[\d]+)#', $order->ga_ga, $m);
$clientId = isset($m[1]) ? $m[1] : '';

$tracker = new Tracker(GOOGLE_ANALYTICS_USERAGENT, $clientId, null, $debug);

ob_start();

// Send a transaction
$tracker->send('transaction', array(
    'transactionId'          => $orderId,
    'transactionAffiliation' => config('app.name'),
    'transactionRevenue'     => $order->getTotalCost(),
    'transactionShipping'    => $order->getDelivery()->cost,
    'transactionTax'         => $order->getVatCost(),
));

foreach($order->getItems() as $itemRow) {
    // Send an item record related to the preceding transaction
    $tracker->send('item', array(
        'transactionId' => $orderId,
        'itemName'      => $itemRow['item_name'],
        'itemCode'      => $itemRow['item_id'],
        'itemCategory'  => $itemRow['size'],
        'itemPrice'     => $itemRow['item_price'],
        'itemQuantity'  => $itemRow['quantity'],
    ));
}


// send data to Analytics server (in the destructor)
unset($tracker);

if ($debug) {
    $output = ob_get_clean();
    gaLog($output);
}

/**
 * Google Analytics log.
 *
 * Intended for use in this particular file to debug tracking issues.
 * Writes logs into the directory where the UA tracking code resides.
 *
 * @param $text
 */
function gaLog($text) {
    if ($fp = fopen(dirname(__FILE__) . '/log/debug.log', 'a')) {
        fwrite($fp, date('[Y-m-d H:i:s]') . PHP_EOL . $text . PHP_EOL . PHP_EOL);
        fclose($fp);
    }
}
