#!/usr/bin/perl

# Copyright 2017 R-Bit Technology, s.r.o. <rbit@rbit.cz>
#
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with Koha; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

use Modern::Perl;

use CGI qw ( -utf8 );

use Koha::Plugins::Handler;
use C4::Auth qw/check_api_auth/;
use C4::Output;
use C4::Debug;
use C4::Context;

my $cgi = new CGI;

my $staffClientUrl =  C4::Context->preference('staffClientBaseURL');
my $plugins_enabled = C4::Context->preference('UseKohaPlugins') && C4::Context->config("enable_plugins");
my $class  = 'Koha::Plugin::Com::RBitTechnology::GoPay';

unless ( $plugins_enabled ) {
    print $cgi->header(-type => 'text/plain');
    print "Payment plugins disabled";
    exit;
}

# this check is useless here, but the payment plugins will need this preference
unless ( $staffClientUrl ) {
    print $cgi->header(-type => 'text/plain');
    print "Missing staffClientBaseURL system preference";
    exit;
}

my $phase = $cgi->url_param('phase');
if ($phase && $phase eq 'return') {
    my $plugin = Koha::Plugins::Handler->run( { class => $class, method => 'opac_online_payment_end', cgi => $cgi } );
    exit;
}

my ($status, $cookie, $sessionID) = check_api_auth($cgi, { plugins => 'tool' } );
unless ($status eq "ok") {
    print $cgi->header(-type => 'text/plain');
    print "Bad credentials: $status";
    exit;
}

my $plugin = Koha::Plugins::Handler->run( { class => $class, method => 'opac_online_payment_begin', cgi => $cgi } );

1;
