<?php

// Import the library files
require_once('sdk/Mambo.php');


// --------------- CONFIGURATION START ----------------

// Configure server and security variables
$serverUrl = "INSERT_MAMBO_SERVER_URL";
$publicKey = "INSERT_MAMBO_PUBLIC_KEY";
$privateKey = "INSERT_MAMBO_PRIVATE_KEY";
$siteUrl = "INSERT_MAMBO_SITE_URL";

// --------------- CONFIGURATION END ----------------


// Initialise the clients credentials and end point URL, this only needs to be done once
MamboClient::setCredentials( $publicKey, $privateKey );
MamboClient::setEndPointBaseUrl( $serverUrl );

// Use default timezone to parse dates
date_default_timezone_set("UTC");


// Check if a CSV file was supplied
if( $argc != 2 ) {
	exit("Please provide a CSV file name as an argument i.e. php point_loader my_file.csv");
}


// Open the CSV file
$csvFileName = $argv[1];
$handle = fopen( $csvFileName, "r" );

if( $handle === FALSE ) {
	exit("Failed to open the CSV file: " + $csvFileName);
}


// Process the CSV file
$row = 0;

while( ( $data = fgetcsv( $handle, 1000, "," ) ) !== FALSE )
{
	$row++;

	debugLog( "---------------------------------" );
	debugLog( "Parsing row number: " . $row );

	if( $row == 1 ) {
		debugLog( "Head row: skipping" );
		continue;
	}

	createActivity( $data );

	debugLog( "Completed row number: " . $row );
}

// Close the CSV file
fclose( $handle );
exit();


// --------------- Helper Functions ----------------


// Try to create the activity
function createActivity( $data )
{
	global $siteUrl;

	$uuid = $data[0];
	debugLog( "Creating activity for user: " . $uuid );

	$activityData = createActivityData( $uuid, $data );
	$activity = MamboActivitiesService::createSync( $siteUrl, $activityData );
	validateActivityCreation( $uuid, $activity );

	return $uuid;
}


function createActivityData( $uuid, $data )
{
	$pointAction = $data[1];
	$pointId = $data[2];
	$pointValue = $data[3];
	$createdOnOverride = $data[4];
	$reason = $data[5];

	$points = new PointStore();
	$points->setPointId( $pointId );
	$points->setPoints( $pointValue );

	$attrs = new ActivityPointAttrs();
	$attrs->setAction( $pointAction );
	$attrs->addPoint( $points );

	$data = new ActivityRequestData();
	$data->setUuid( $uuid );
	$data->setAttrs( $attrs );

	if( !empty( $createdOnOverride ) ) {
		$data->setCreatedOnOverride( $createdOnOverride );
	}
	if( !empty( $reason ) ) {
		$data->setReason( $reason );
	}

	return $data;
}


function validateActivityCreation( $uuid, $activity ) {
	if( isset( $activity->error ) ) {
		debugLog( "An unexpected error occurred! Dumping output and terminating." );
		var_dump( $activity );
		exit();
	}
}


// Basic output to the terminal
function debugLog( $text ) {
	echo $text . "\n";
}