################################################################################
#
# Title:       payment.pl
# Author:      Lawrence G. Williams <law@hbcuconnect.com>
# Date:        2006-01-11
# Version:     $$1.1
# Description: This library contains the functions necessary to process payments
#              for the given domain. It is meant to be reusable along with the
#              Configurable Web Site code.
# Change 1.1:  Moved the processing functions out of the payment module
################################################################################
use warnings;
use strict;

use lib '../../../lib';

use HBCU::Database::CareerCenter;
use HBCU::Database::Configurable;
use HBCU::Database::HBCUCentral;
use LWP::Simple;
use SimLib;

require &getConfigValue('LIB_ROOT') . '/marketplace.pl';

my $db = HBCU::Database::HBCUCentral->new;
my $cdb = HBCU::Database::CareerCenter->new;
my $config_db = HBCU::Database::Configurable->new;

################################################################################
######################### LIBRARY FUNCTIONS ####################################
################################################################################
sub getTransactionDBHandle {
  return $db;
}

################################################################################
sub addTransaction {
  my ($params) = @_;

  return $db->addTransaction($params);
}

################################################################################
sub getTransaction {
  my ($id) = @_;

  # Get the site wide parameters of interest
  return $db->getTransaction({transaction_id => $id});
}

################################################################################
sub markTransactionPaid {
  my ($id) = @_;

  return $db->updateTransaction(PARAMS => {paid => 1, date_paid => 'now()'},
				WHERE => {transaction_id => $id});
}

################################################################################

sub getSiteCoreVariables {
  my $dbh = shift;
  my $sth = $dbh->prepare(q(
SELECT *
  FROM toolkit
 WHERE site = ?
   AND instance_of = 0
)) or die DBI->errstr;

  $sth->execute(@_) or die DBI->errstr;

  my %rows = ();
  my %vars = ();
  my $row = $sth->fetchrow_hashref();

  $sth->finish();

  $row->{variables} = getToolkitVariables($dbh, $row->{id});

  ### Get out the \$s
  foreach my $v (keys %{$row->{variables}}) {
    while ($row->{variables}->{$v}->{value} =~ /\$(\w+)/) {
      $row->{variables}->{$v}->{value} =~ s/\$(\w+)/$row->{variables}->{$1}->{value}/g;
    }
  }

  $vars{$_} = $row->{variables}->{$_}->{value} for keys %{ $row->{variables} };

  return \%vars;
}

################################################################################
sub getToolkitVariables {
  my $dbh = shift;
  my $sth = $dbh->prepare(q(
SELECT a.id As id
      ,a.toolkit As toolkit
      ,a.name As name
      ,a.value As value
      ,a.variable_type As variable_type_name
      ,a.access_level As access_level_name
      ,b.name As variable_type
      ,c.name As access_level
  FROM variable As a
  LEFT
  JOIN variable_type As b
    ON a.variable_type = b.id
  LEFT
  JOIN access_level As c
    ON a.access_level = c.id
 WHERE a.toolkit = ?
)) or die DBI->errstr;

  $sth->execute(@_) or die DBI->errstr;

  my %rows = ();

while (my $row = $sth->fetchrow_hashref()) {
    $rows{$row->{name}} = $row;
  }

  $sth->finish();

  return \%rows;
}
################################################################################
######################### END LIBRARY FUNCTIONS ################################
################################################################################

################################################################################
######################### OUTPUT FUNCTIONS #####################################
################################################################################
sub printPaymentForm {
  my ($q, $header, $footer) = @_;

  # Get the site wide parameters of interest
  my $transaction = getTransaction($q->param('transaction_id'));
  my $variables = getSiteCoreVariables($config_db->dbh, $transaction->{payment_site});
  my $redirect_name = $q->param('redirect_name') || $variables->{ROOT_URL};
  my $redirect = $q->param('redirect') || $variables->{ROOT_URL};
  $redirect = "http://$redirect" unless $redirect =~ /^http/;

  if ($transaction->{payment_site} == 0) {
    $variables->{HEADER} = 'http://www.hbcucruise.com/header.html';
    $variables->{FOOTER} = 'http://www.hbcucruise.com/footer.html';
  } else {
    $variables->{HEADER} = $header ? $header : $variables->{ROOT_URL} . '/header.html';
    $variables->{FOOTER} = $footer ? $footer : $variables->{ROOT_URL} . '/footer.html';
  }

  $variables->{SITE} ||= 'HBCU Connect';
  $variables->{VISA} ||= 'http://hbcuconnect.com/core/images/visa.gif';
  $variables->{MASTERCARD} ||= 'http://hbcuconnect.com/core/images/mastercard.gif';
  $variables->{AMEX} ||= 'http://hbcuconnect.com/core/images/amex.gif';

  print $q->header();

  getprint($variables->{HEADER});

print qq~
<script language=javascript>

function setMonth() {
  document.payform.x_Exp_Date.value= document.payform.x_Exp_Month[document.payform.x_Exp_Month.selectedIndex].value + document.payform.x_Exp_Year[document.payform.x_Exp_Year.selectedIndex].value
}

function setYear() {
  document.payform.x_Exp_Date.value= document.payform.x_Exp_Month[document.payform.x_Exp_Month.selectedIndex].value + document.payform.x_Exp_Year[document.payform.x_Exp_Year.selectedIndex].value

  msg="Exp Date:"+document.payform.x_Exp_Date.value;
}

function validateForm() {
  if ( document.payform.x_Card_Num.value == '' ) {
    alert('You must enter a valid credit card number!');
    return false;
  }

  return true;
}

function submitOnce()
    {

     if ( validateForm() ) {
       //if IE 4+ or NS 6+
       if (document.all)
        {
          document.payform.Go.disabled=true
          return true;
        }
     } else {
        return false;
     }
    }
</script>
    <table align=center class=data>
      <thead>
	<tr>
	  <th colspan=2>$variables->{SITE} Payment Form</th>
	</tr>
      </thead>
      <form name=payform method=post action="https://secure.authorize.net/gateway/transact.dll" onSubmit="return submitOnce();">

~;
  #### Get variables ready for after payment
  foreach my $x ( $q->param('item_id') ) {
    print "<input type=hidden name=x_item_id value=$x>";
  }

  # We need this stuff
  &SimLib::InsertFP('hbcu03', 'dSo3lGKLv6GVvDAf', $transaction->{payment_amount}, 'USD');

  ### if 'testing' is passed in on the query string we don't want a real transaction
  print "<input type=hidden name=\"x_Test_Request\" value=\"TRUE\" />\n" if $q->param('testing');

print qq~

	<input type=hidden name="x_Exp_Date" value="" />
	<input type=hidden name="x_Version" value="3.0" />
	<input type=hidden name="x_Login" value="hbcu03" />
	<input type=hidden name="x_ADC_Relay_Response" value="True" />
	<input type=hidden name="x_ADC_URL" value="https://hbcuconnect.com/core/cgi-bin/secure_response.cgi" />
        <input type=hidden name="x_Cust_ID" value="$transaction->{member_id}" />
        <input type=hidden name="x_description" value="$transaction->{payment_description}" />
        <input type=hidden name="x_Amount" value="$transaction->{payment_amount}" />
        <input type=hidden name="x_transaction_id" value="$transaction->{transaction_id}" />
        <input type=hidden name="x_redirect" value="$redirect" />
        <input type=hidden name="x_redirect_name" value="$redirect_name" />
        <input type=hidden name="x_header" value="$header" />
        <input type=hidden name="x_footer" value="$footer" />

~;
  $transaction->{payment_amount} = sprintf("\$%.2f", $transaction->{payment_amount});
print qq~

	<tbody>
	  <tr>
	    <th>
	      Purchase Description :
	    </th>
	    <td>
	      $transaction->{payment_description}
	    </td>
	  </tr>
	  <tr>
	    <th>
	      Amount To Be Billed :
	    </th>
	    <td>
	      <b>$transaction->{payment_amount}</b>
	    </td>
	  </tr>
	  <tr>
	    <th>
	      <font class=required>*</font>First Name On Card :
	    </th>
	    <td>
	      <input type="text" name="x_First_Name" size="30" />
	    </td>
	  </tr>
	  <tr>
	    <th>
	      <font class=required>*</font>Last Name On Card :
	    </th>
	    <td>
	      <input type="text" name="x_Last_Name" size="30" />
	    </td>
	  </tr>
	  <tr>
	    <th>
	      <font class=required>*</font>Billing Address :
	    </th>
	    <td>
	      <input type="text" name="x_address" size="30" />
	    </td>
	  </tr>
	  <tr>
	    <th>
	      <font class=required>*</font>City :
	    </th>
	    <td>
	      <input type="text" name="x_city" size="30" />
	    </td>
	  </tr>
	  <tr>
	    <th>
	      <font class=required>*</font>State/Province :
	    </th>
	    <td>
	      <input type="text" name="x_state" size="30" />
	    </td>
	  </tr>
	  <tr>
	    <th>
	      <font class=required>*</font>Zip/Postal Code :
	    </th>
	    <td>
	      <input type="text" name="x_zip" size="30" />
	    </td>
	  </tr>
	  <tr>
	    <th>
	      <font class=required>*</font>Country :
	    </th>
	    <td>
	      <input type="text" name="x_country" size="30" />
	    </td>
	  </tr>
	  <tr>
	    <th>
	      <font class=required>*</font>Credit Card Type :
	    </th>
	    <td>
	      <input type="radio" name="CardType" value="Visa" checked />
	      <img src=$variables->{VISA} alt="We accept Visa" align="middle">
	      &nbsp;&nbsp;
	      <input type="radio" name="CardType" value="MasterCard" />
	      <img src=$variables->{MASTERCARD} alt="We accept MasterCard" align="middle">
	      &nbsp;&nbsp;
	      <input type="radio" name="CardType" value="Amex" />
	      <img src=$variables->{AMEX} alt="We accept American Express" align="middle">
	    </td>
	  </tr>
	  <tr>
	    <th>
	      <font class=required>*</font>Credit Card Number (No Dashes or Spaces) :
	    </th>
	    <td>
	      <input type="text" name="x_Card_Num" size="30" />
	    </td>
	  </tr>
	  <tr>
	    <th>
	      <font class=required>*</font>Credit Card Expiration :
	    </th>
	    <td>
	      Month:
	      <select Name="x_Exp_Month" onChange=setMonth()>
                <Option Value="" Selected></Option>
                <Option Value="01" >01</Option>
                <Option Value="02">02</Option>
                <Option Value="03">03</Option>
                <Option Value="04">04</Option>
                <Option Value="05">05</Option>
                <Option Value="06">06</Option>
                <Option Value="07">07</Option>
                <Option Value="08">08</Option>
                <Option Value="09">09</Option>
                <Option Value="10">10</Option>
                <Option Value="11">11</Option>
                <Option Value="12">12</Option></select> /

	      Year:
	      <select Name="x_Exp_Year" onChange=setYear()>
                <Option Value="" Selected></Option>
                <Option Value="03">2003</Option>
                <Option Value="04">2004</Option>
                <Option Value="05">2005</Option>
                <Option Value="06">2006</Option>
                <Option Value="07">2007</Option>
                <Option Value="08">2008</Option>
                <Option Value="09">2009</Option>
                <Option Value="10">2010</Option>
                <Option Value="11">2011</Option>
                <Option Value="12">2012</Option>
                <Option Value="13">2013</Option>
                <Option Value="14">2014</Option>
                <Option Value="15">2015</Option>
                <Option Value="16">2016</Option>
                <Option Value="17">2017</Option>
                <Option Value="18">2018</Option>
                <Option Value="19">2019</Option>
	      </select>
	    </td>
	  </tr>
	  <tr class=buttons>
	    <td colspan=2 align=center>
	      <input type="submit" name=Go value="Process Payment">
	    </td>
	  </tr>
	</tbody>
    </table>
    <br />

    <div align=center>
      <b>Please be patient while we verify your payment information<br />
        Allow 15-30 seconds....<font class=required>DO NOT</font> press the payment button twice!</b>
      <br /><br />
      <b>NOTE:</b>
      $variables->{SITE} does not store any credit card information on our servers.
	Payment processing is handled by a secure protocol transaction with
	the internet's most trusted payment gateway.
    </div>
    <br />
~;

  getprint($variables->{FOOTER});
}

################################################################################
sub printPaymentReceipt {
  my ($q, $header, $footer) = @_;
  my $response_reason_text = $q->param('x_response_reason_text');
  my $response_reason_code = $q->param('x_response_reason_code');

  # Get the site wide parameters of interest
  my $transaction = getTransaction($q->param('x_transaction_id'));
  my $variables = getSiteCoreVariables($config_db->dbh, $transaction->{payment_site});
  my $redirect = $q->param('x_redirect') || $variables->{ROOT_URL};
  my $redirect_name = $q->param('x_redirect_name') || $variables->{ROOT_URL};

  if ($transaction->{payment_site} == 0) {
    $variables->{HEADER} = 'http://www.hbcucruise.com/header.html';
    $variables->{FOOTER} = 'http://www.hbcucruise.com/footer.html';
  } else {
    $variables->{HEADER} = $header ? $header : $variables->{ROOT_URL} . '/header.html';
    $variables->{FOOTER} = $footer ? $footer : $variables->{ROOT_URL} . '/footer.html';
  }

  $variables->{SITE} ||= 'HBCU Connect';

  print $q->header();

  getprint($variables->{HEADER});

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>$variables->{SITE} Payment Processing Center</th>
	</tr>
      </thead>
      <tbody>
	<tr>
          <th>
            RESULTS :
          </th>
          <td>
            $response_reason_text($response_reason_code)
          </td>
        </tr>
	<tr>
          <th>
            Return :
          </th>
          <td>
            <a href=$redirect>:: $redirect_name ::</a>
          </td>
        </tr>
      </tbody>
    </table>
    <br />
~;

  getprint($variables->{FOOTER});
}

################################################################################
sub printPaymentError {
  my ($q, $header, $footer) = @_;

  # Get the site wide parameters of interest
  my $transaction = getTransaction($q->param('x_transaction_id'));
  my $variables = getSiteCoreVariables($config_db->dbh, $transaction->{payment_site});
  my $response_reason_text = $q->param('x_response_reason_text');
  my $response_reason_code = $q->param('x_response_reason_code');

  if ($transaction->{payment_site} == 0) {
    $variables->{HEADER} = 'http://www.hbcucruise.com/header.html';
    $variables->{FOOTER} = 'http://www.hbcucruise.com/footer.html';
  } else {
    $variables->{HEADER} = $header ? $header : $variables->{ROOT_URL} . '/header.html';
    $variables->{FOOTER} = $footer ? $footer : $variables->{ROOT_URL} . '/footer.html';
  }

  $variables->{SITE} ||= 'HBCU Connect';

  print $q->header();

  getprint($variables->{HEADER});

print qq~
    <table class=data width=100%>
      <thead>
	<tr>
	  <th colspan=2>$variables->{SITE} Payment Processing Center</th>
	</tr>
      </thead>
      <tbody>
	<tr>
          <td align=center>
            <br /><br />
            ERROR :
            $response_reason_text($response_reason_code)
            <br /><br /><br />
          </td>
        </tr>
	<tr class=buttons>
          <td align=center>
            <input type=button name=back value="Go Back" onClick="javascript:history.go(-1)">
          </td>
        </tr>
      </tbody>
    </table>
    <br />
~;

  getprint($variables->{FOOTER});
}

################################################################################
######################### END OUTPUT FUNCTIONS #################################
################################################################################

1;
