<?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 user_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;
	}

	createUser( $data );

	debugLog( "Completed row number: " . $row );
}

// Close the CSV file
fclose( $handle );
exit();


// --------------- Helper Functions ----------------


// Try to create the user unless they already exist
function createUser( $data )
{
	global $siteUrl;

	$uuid = $data[0];
	debugLog( "Creating user: " . $uuid );

	$userData = createUserData( $uuid, $data );
	$user = MamboUsersService::create( $siteUrl, $userData );
	validateUserCreation( $uuid, $user );

	return $uuid;
}


function createUserData( $uuid, $data )
{
	$email = $data[1];
	$firstName = $data[2];
	$lastName = $data[3];

	$userDetails = new UserDetails();
	$userDetails->setEmail( $email );
	$userDetails->setFirstName( $firstName );
	$userDetails->setLastName( $lastName );
	$userData = new UserRequestData();
	$userData->setUuid( $uuid );
	$userData->setIsMember( true );
	$userData->setDetails( $userDetails );
	return $userData;
}


function validateUserCreation( $uuid, $user ) {
	if( isset( $user->error ) ) {
	    if( strcmp( $user->error->type, "DuplicateException" ) === 0 ) {
			debugLog( "Existing user on server: " . $uuid );
	    } else {
			debugLog( "An unexpected error occurred! Dumping output and terminating." );
			var_dump( $user );
			exit();
	    }
	}
}


// Basic output to the terminal
function debugLog( $text ) {
	echo $text . "\n";
}