<?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 coupon_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;
	}

	createCoupon( $data );

	debugLog( "Completed row number: " . $row );
}

// Close the CSV file
fclose( $handle );
exit();


// --------------- Helper Functions ----------------


// Try to create the coupon unless they already exist
function createCoupon( $data )
{
	global $siteUrl;

	debugLog( "Creating coupon: " . $data[0] );

	$requestData = createrequestData( $data );
	$coupon = MamboCouponsService::create( $siteUrl, $requestData );
	validateCouponCreation( $data[0], $coupon );
}


function createrequestData( $data )
{
	$code = $data[1];
	$usage = $data[2];
	$type = $data[3];

	$requestData = new CouponRequestData();
	$requestData->setName( $data[0] );
	$requestData->setActive( $data[1] );
	$requestData->setCode( $data[2] );
	$requestData->setUsage( $data[3] );
	$requestData->setType( $data[4] );
	$requestData->setAmount( $data[5] );
	$requestData->setCustomPrize( $data[6] );
	$requestData->setHelpMessage( $data[7] );
	$requestData->setExpiration( new NeverRecurrence() );

	$scarcity = new Scarcity();
	$scarcity->setLimit( $data[8] );
	$requestData->setScarcity( $scarcity );

	if( $data[9] !== "" ) {
		$point = new PointStore();
		$point->setPointId( $data[9] ); // Required
		$point->setPoints( $data[10] ); // Required
		$requestData->setPointsToBuy( $point );
	}

	return $requestData;
}


function validateCouponCreation( $name, $object ) {
	if( isset( $object->error ) ) {
	    if( strcmp( $object->error->type, "DuplicateException" ) === 0 ) {
			debugLog( "Existing object on server: " . $name );
	    } else {
			debugLog( "An unexpected error occurred! Dumping output and terminating." );
			var_dump( $object );
			exit();
	    }
	}
}


// Basic output to the terminal
function debugLog( $text ) {
	echo $text . "\n";
}