#!/usr/bin/perl
use strict;
use warnings;

package API::GiftCard;

our $Config;
BEGIN{
	use API::Config;
	$Config = $API::Config::Config;
}
use lib ($Config->{Website_libs});
use ECS::EMail::GiftCard;
use ECS::Payment::GiftCard;
use ECS::SQL;
my $dbh  = ECS::SQL::connect();
my $dbhr = ECS::SQL::connect('SLAVE');
my $site_dbh  = $dbh;
my $site_dbhr = $dbhr;
my @management_addresses = ('tom@ecstuning.com', 'amergy@ecstuning.com', 'tlilly@ecstuning.com');

sub update{
	
	my $self = shift;
	my $input = shift;
	
	$input->{siteID} ||= 1;
	if($input->{siteID} != 1)
	{
		$site_dbh = ECS::Site->fromID( $input->{siteID} )->site_dbh;
	}
	$input->{site_dbh} = $site_dbh;
	my $result = {
		'success'	=> 1,
		'error'		=> undef,
		'update_DB'	=> $Config->{update_DB},
		'reply'	=> {
			'giftCardID'	=> $input->{giftCardID}
		}
	};
	
	$input->{changed} ||= {};

	# IF we want to write to DB (Determined by API::Config)
	# --------------------------------------------------
	if ($Config->{update_DB}){
		# Ticket 1520 - rswiderski
		# Determine whether or not to set the dateActivated field.
		# When the active flag is Y and the dateActivated is null the date should be set.
		# When the active flag is N dateActivated should be set to null.
		
		my $newDate = "";
		if ($input->{active} eq 'Y') {
			if($input->{dateActivated} eq '') {
				$newDate = "NOW()";
			}
			else {
				$newDate = '"'.$input->{dateActivated}.'"';
			}
		}
		else {
			$newDate = "NULL";
		}
	
		my $sql = "UPDATE giftCard
                    SET
                        giftCard.originalValue = ?,
                        giftCard.currentValue = ?,
                        giftCard.type = ?,
                        giftCard.goodwill = ?,
                        giftCard.purchaseCode = ?,
                        giftCard.purchaseCodeOther = ?,
                        giftCard.active = ?,
                        giftCard.dateActivated = $newDate,
                        giftCard.ownerID = (SELECT customerID FROM customer WHERE email = ? AND email IS NOT NULL AND email <> ''),
                        giftCard.purchaserID = (SELECT customerID FROM customer WHERE email = ?  AND email IS NOT NULL AND email <> ''),
                        giftCard.sessionID = ?
                        
                    WHERE giftCard.giftCardID = ?";

		my $sth = $site_dbh->prepare($sql);
		
		unless (
			$sth->execute(
				$input->{originalValue},
				$input->{currentValue}, 
				$input->{type},
				$input->{goodwill},
				$input->{purchaseCode},
				$input->{purchaseCodeOther},
				$input->{active},
				$input->{ownerEmail},
				$input->{purchaserEmail},
				$input->{sessionID},
				$input->{giftCardID}
			)
		) {
			$result->{success} = 0;
			$result->{error} = 'Failed to update Gift Card';
			return $result;
		}
		
		unless (&writeLog($input)) {
			$result->{success} = 0;
			$result->{error} .= "Writing change log failed.";
			return $result;
		}
		
		$sql = "SELECT CONCAT(nameFirst, ' ', nameLast) AS name FROM employeeInfo WHERE employeeID = ?";
		$sth = $dbhr->prepare($sql);
		if(!$sth->execute($input->{employeeID})){
			$result->{success} = 0;
			$result->{error} = "Unable to get employee information.";
		}
		my $row = $sth->fetchrow_hashref();
		
		if (
			$input->{changed}->{currentValue}
			and $input->{currentValue}
			and $input->{changed}->{currentValue} < $input->{currentValue}
		) {
			# Send email to management
			ECS::EMail::GiftCard::send({ 
				DBH => $dbh, 
				template => "management-gift-card-value-increased",
				toEmail => \@management_addresses,
				giftCard => {
					cardNumber => $input->{cardNumber}, 
					oldValue =>$input->{changed}->{currentValue},
					newValue => $input->{currentValue},
					purchaserEmail => $input->{purchaserEmail},
					employeeName => $row->{'name'},
					purchaseCode => $input->{purchaseCode}, 
				},
			}); 
		}
	}
    return $result;
}


sub add{

	my $self = shift;
	my $input = shift;
	
	$input->{siteID} ||= 1;
    my $site = ECS::Site->fromID( $input->{siteID} );
    my $site_dbh  = $site->site_dbh;
    my $site_dbhr = $site->site_dbhr;
	$input->{site_dbh} = $site_dbh;
	my $result = {
		'success'	=> 1,
		'error'		=> undef,
		'update_DB'	=> $Config->{update_DB},
	};
	if($Config->{update_DB}){
		my $activationDate;
		if ($input->{active} and $input->{active} eq 'Y') {
			$activationDate = "NOW()";
		} else {
			$activationDate = "NULL";
		}

        my $ownerID;
        if ( $input->{ 'ownerEmail' } ) {
            my $sql = q{
                SELECT
                    customerID
                FROM customer
                WHERE
                    email = ?
            };
            my $sth = $site_dbhr->prepare( $sql );
            $sth->execute( $input->{ 'ownerEmail' } );
            ( $ownerID ) = $sth->fetchrow_array;
        }

        if ( not $ownerID ) {
            $result->{ 'success' } = 0;
            $result->{ 'error' } = "Card owner is invalid or missing";
            return $result;
        }

		my $sql = "	INSERT INTO giftCard (cardNumber, ownerID, purchaserID, originalValue, currentValue, type, goodwill, purchaseCode, purchaseCodeOther, active, sessionID, ts, dateActivated)
					VALUES (
						?,
						?,
						(SELECT customerID FROM customer WHERE email = ? AND email IS NOT NULL AND email <> ''),
						?,
						?,
						'eGC',
						?,
						?,
						?,
						?,
						?,
						NOW(),
						$activationDate
					)";
	
		my $sth = $site_dbh->prepare($sql);
		
		unless (
			$sth->execute(
				$input->{cardNumber},
				$ownerID,
				$input->{purchaserEmail},
				$input->{value},
				$input->{value},
				$input->{goodwill},
				$input->{purchaseCode},
				$input->{purchaseCodeOther},
				$input->{active},
				$input->{sessionID}
			)
		) {
			$result->{success} = 0;
			$result->{error} = "Unable to insert into database.";
			return $result;
		}
		
		$input->{giftCardID} = $input->{giftCardID} || $site_dbh->{mysql_insertid};
		$input->{changed}{created}='';
		$input->{created} = '';
		
		unless (&writeLog($input)) {
			$result->{success} = 0;
			$result->{error} .= "Writing change log failed.";
			return $result;
		}
	}
	
	my $sql = "
		SELECT 
			CONCAT(name_first, ' ', name_last) AS name
		FROM giftCard
			LEFT JOIN customer ON (customer.customerID = giftCard.ownerID)
			LEFT JOIN billinfo USING (billID)
		WHERE billinfo.name_first IS NOT NULL
			AND billinfo.name_last IS NOT NULL
			AND giftCardID = ?
	";
	my $sth = $site_dbhr->prepare($sql);
	if(!$sth->execute($input->{giftCardID})){
		$result->{success} = 0;
		$result->{error} = "Unable to get customer information.";
		return $result;
	}
	my $customerName = ($sth->fetchrow_hashref || {})->{'name'};
	
	$sql = "
		SELECT 
			CONCAT(nameFirst, ' ', nameLast) AS name 
		FROM employeeInfo 
		WHERE employeeID = ?
	";
	$sth = $dbhr->prepare($sql);
	if(!$sth->execute($input->{employeeID})){
		$result->{success} = 0;
		$result->{error} = "Unable to get employee information.";
		return $result;
	}
	my $employeeName = $sth->fetchrow_hashref()->{'name'};
	
	# Send email to customer
	if ($input->{ownerEmail}) {
		my @emails;
		push @emails, $input->{ownerEmail};
		ECS::EMail::GiftCard::send({ 
			DBH => $dbh, 
            site => $site,
			template => "customer-notice-of-gift-card-creation", 
			toEmail => [$input->{ownerEmail}],
			giftCard => {
				value => $input->{value},
				customerName => $customerName,
			},
		}); 
	}
	
	# Send email to management
	ECS::EMail::GiftCard::send({
		DBH => $dbh,
		template => "management-gift-card-created",
		toEmail => \@management_addresses,
		giftCard => {
			value => $input->{value},
			cardNumber => $input->{cardNumber},
			purchaserEmail => $input->{purchaserEmail},
			employeeName => $employeeName,
			purchaseCode => $input->{purchaseCode},
		}
	});
	
	return $result;
}

# -----------------------------------------------------------
sub writeLog{
	# This function is only called if update() succeeded
	my $input = shift;
	my $site_dbh = $input->{site_dbh};
	if ($input->{changed}) {
		my %fields_changed = %{$input->{changed}};
		foreach my $field_name ( keys  %fields_changed ){
			if (not defined $fields_changed{$field_name}) {
				$fields_changed{$field_name} = '';
			}
			my $sql = "INSERT into giftCardAdminLog values('', ?, ?, ?, ?, ?, NOW())";
			my $sth = $site_dbh->prepare($sql);
			return 0 unless $sth->execute($input->{employeeID}, $input->{giftCardID}, $field_name, $fields_changed{$field_name}, $input->{$field_name});
		}
	}

	return 1;
}
