#!/usr/bin/perl

# Copyright 2013 BibLibre
#
# 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, see <http://www.gnu.org/licenses>.

use Modern::Perl;
use CGI;

use C4::Auth qw( check_cookie_auth );
use JSON qw( to_json );
use Koha::List::Patron qw( AddPatronList GetPatronLists AddPatronsToList );

my $input = CGI->new;

my ( $auth_status ) = check_cookie_auth(
    $input->cookie('CGISESSID'),
    { tools => 'manage_patron_lists' },
);

exit 0 if $auth_status ne "ok";
my $add_to_patron_list = $input->param('add_to_patron_list');
my $new_patron_list    = $input->param('new_patron_list');
my @borrowernumbers    = $input->multi_param('borrowernumbers[]');

my $response;
if ($add_to_patron_list) {
    my $patron_list = [];

    if ( $add_to_patron_list eq 'new' ) {
        $patron_list = AddPatronList( { name => $new_patron_list } );
    }
    else {
        $patron_list =
          [ GetPatronLists( { patron_list_id => $add_to_patron_list } ) ]->[0];
    }

    my @patrons_added_to_list = AddPatronsToList( { list => $patron_list, borrowernumbers => \@borrowernumbers } );

    $response->{patron_list} = { patron_list_id => $patron_list->patron_list_id, name => $patron_list->name };
    $response->{patrons_added_to_list} = scalar( @patrons_added_to_list );
}

binmode STDOUT, ":encoding(UTF-8)";
print $input->header(
    -type => 'application/json',
    -charset => 'UTF-8'
);

print to_json( $response );
