#!/usr/bin/perl

use strict;
use lib '/home/slowtwitch/forum.slowtwitch.com/cgi-bin/admin';
use GForum qw/:objects/;
use GForum::Payment qw/:status :log/;
use Data::Dumper;
use vars qw/%INVALID %EMPTY/;
use GT::Payment::Direct::AuthorizeDotNetRec;
use Slowtwitch::Payment;

GForum::init('/home/slowtwitch/forum.slowtwitch.com/cgi-bin/admin');

main();

sub main {
    silent_post();
}

sub silent_post {
# -----------------------------------------------------------------------------
# Handle PayPal postback
    my $unique = $IN->param('x_invoice_num');
    my $pay = $DB->table('Subscription_Payments');
    my $log = $DB->table('Subscription_PaymentLogs');
    my $in = $IN->get_hash();
    my $payment = $pay->get($unique);
    if (!$payment) {
        open (LOG, ">>/var/home/virginia/virginialo.com/cgi-bin/forum/admin/auth_silent_error.log");
        print LOG Dumper($in);
        close (LOG);
        print $IN->header . "No such invoice: $unique.";
        return;
    }

    open (LOG, ">>/var/home/virginia/virginialo.com/cgi-bin/forum/admin/auth_silent_live.log");
    print LOG Dumper($payment,$in);
    close (LOG);

    print $IN->header;
    GT::Payment::Direct::AuthorizeDotNetRec::process(
        param => $IN,
        test_mode => $CFG->{payment}->{direct}->{used}->{AuthorizeDotNetRec}->{test_mode},
        account_username => $CFG->{payment}->{direct}->{used}->{AuthorizeDotNetRec}->{account_username},
        md5_key => $CFG->{payment}->{direct}->{used}->{AuthorizeDotNetRec}->{md5_key},
        duplicate => sub {
            my $id = $IN->param('x_trans_id');
            my $cond = GT::SQL::Condition->new();
            $cond->add(paylogs_payments_id => '=' => $unique);
            $cond->add(paylogs_type => '=' => LOG_ACCEPTED);
            $cond->add(paylogs_text => LIKE => "%Transaction ID: $id\n%");
            my $found = $log->count($cond);
            #warn "$found ($id) **";
            return $found ? undef : 1; # True if everything checks out; undef if a duplicate was found
        },
        on_invalid => sub {
        },
        on_error => sub {
            my $errmsg = shift;
            print $errmsg . "\n";
            $pay->update(
                { payments_status => ERROR, payments_last => time },
                { payments_id => $payment->{payments_id} }
            );

            $log->insert({
                paylogs_payments_id => $payment->{payments_id},
                paylogs_type => LOG_ERROR,
                paylogs_time => time,
                paylogs_text => $errmsg
            });
        },
        on_recurring => sub {
            if ($IN->param('x_amount') < $payment->{payments_amount}) {
                $log->insert({
                    paylogs_payments_id => $payment->{payments_id},
                    paylogs_type => LOG_ERROR,
                    paylogs_time => time,
                    paylogs_text => "Invalid payment (payment amount is less than original charge): " .
                    $IN->param('x_amount') . " < " . $payment->{payments_amount}
                });
                return;
            }

            $pay->update(
                { payments_status => COMPLETED, payments_last => time },
                { payments_id => $payment->{payments_id} }
            );

            $log->insert({
                paylogs_payments_id => $payment->{payments_id},
                paylogs_type => LOG_ACCEPTED,
                paylogs_time => time,
                paylogs_text => (
                    "Transaction ID: " . $IN->param('x_trans_id') . "\n" .
                    "Amount: " . $IN->param('x_amount') . " " .
                    "Subscription payment #: " . $IN->param('x_subscription_paynum') . " " .
                    "Subscription ID: " . $IN->param('x_subscription_id') . "\n"
                )
            });

            Slowtwitch::Payment::process_payment($payment->{payments_userid}, '', $payment->{payments_id});
        }
    );

    1;
}
