#!/usr/bin/perl

# This file is part of Koha.
#
# Copyright 2016 Aleisha Amohia <aleisha@catalyst.net.nz>
#
# 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 JSON qw( encode_json );
use C4::Service;
use C4::Auth qw( check_cookie_auth get_template_and_user );
use C4::Letters;
use CGI;
use C4::Output qw( is_ajax output_with_http_headers );
use C4::Scrubber;
use C4::Circulation;
use C4::Biblio;
use Koha::Checkouts;
use Koha::DateUtils qw( dt_from_string );
use Koha::Patrons;

=head1 NAME

svc/checkout_notes - Web service for setting patron notes on items

=head1 DESCRIPTION

=cut

# AJAX requests
my $is_ajax       = is_ajax();
my $query         = CGI->new;
my ($auth_status) = check_cookie_auth( $query->cookie('CGISESSID'), {} );
if ( $auth_status ne "ok" ) {
    exit 0;
}
if ($is_ajax) {
    my $op = $query->param('op');

    # Issue Note
    if ( $op eq 'cud-add_note' && C4::Context->preference('AllowCheckoutNotes') ) {
        my $scrubber   = C4::Scrubber->new();
        my $note       = $query->param('note');
        my $issue_id   = $query->param('issue_id');
        my $clean_note = $scrubber->scrub($note);
        my $status     = "saved";
        my ( $patron, $issue );

        my ( $template, $borrowernumber, $cookie ) = C4::Auth::get_template_and_user(
            {
                template_name   => "opac-user.tt",
                query           => $query,
                type            => "opac",
                authnotrequired => 1,
            }
        );

        # verify issue_id
        if ( $issue_id =~ /\d+/ ) {
            $patron = Koha::Patrons->find($borrowernumber);
            $issue  = Koha::Checkouts->find($issue_id);
            if ( $issue->borrowernumber != $borrowernumber ) {
                $status = "fail";
            }
        }

        if ( $issue && $status eq "saved" ) {
            $issue->set( { notedate => dt_from_string(), note => $clean_note, noteseen => 0 } )->store;
            if ($clean_note) {    # only send email if note not empty
                my $branch       = Koha::Libraries->find( $issue->branchcode );
                my $biblionumber = $issue->item->biblionumber;
                my $letter       = C4::Letters::GetPreparedLetter(
                    module      => 'circulation',
                    letter_code => 'CHECKOUT_NOTE',
                    branchcode  => $branch,
                    tables      => {
                        'biblio'    => $biblionumber,
                        'borrowers' => $borrowernumber,
                        'issues'    => $issue->itemnumber,
                        'items'     => $issue->itemnumber,
                    },
                );

                my $to_address    = $branch->inbound_email_address;
                my $reply_address = $patron->email || $patron->emailpro || $patron->B_email;

                C4::Letters::EnqueueLetter(
                    {
                        letter                 => $letter,
                        message_transport_type => 'email',
                        borrowernumber         => $patron->borrowernumber,
                        to_address             => $to_address,
                        reply_address          => $reply_address,
                    }
                );
            } else {    # note empty, i.e removed
                $status = "removed";
            }
        } else {
            $status = "fail";
        }

        my $json = encode_json( { status => $status, note => $clean_note, issue_id => $issue_id } );
        output_with_http_headers( $query, undef, $json, 'json' );
        exit;
    }    # END Issue Note
}
